forked from little-core-labs/chromafi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
403 lines (325 loc) · 9.65 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
const hljs = require('highlight.js')
const cheerio = require('cheerio')
const camelCase = require('camelcase')
const chalk = require('chalk')
const stripAnsi = require('strip-ansi')
const merge = require('deepmerge')
const stripIndent = require('strip-indent')
const detectIndent = require('detect-indent')
const darkPalette = {
addition: chalk.green,
attr: chalk.yellow,
attribute: chalk.blue,
attrString: chalk.cyan,
base: chalk.white,
builtIn: chalk.blue,
builtInName: chalk.blue,
bullet: chalk.magenta,
class: chalk.green,
code: chalk.yellow,
comment: chalk.white.dim,
deletion: chalk.red,
doctag: chalk.blue,
emphasis: chalk.magenta,
function: chalk.white,
formula: chalk.green,
keyword: chalk.red,
lineNumbers: chalk.grey,
literal: chalk.magenta,
link: chalk.blue.underline,
meta: chalk.cyan,
name: chalk.cyan,
number: chalk.green,
params: chalk.blue,
quote: chalk.gray,
regexp: chalk.magenta,
selectorAttr: chalk.green,
selectorClass: chalk.yellow,
selectorId: chalk.blue,
selectorPseudo: chalk.cyan,
selectorTag: chalk.magenta,
string: chalk.yellow,
strong: chalk.red,
subst: chalk.cyan,
symbol: chalk.cyan,
tag: chalk.blue,
templateTag: chalk.magenta,
templateVariable: chalk.green,
title: chalk.green,
trailingSpace: chalk,
type: chalk.magenta,
variable: chalk.red
}
const filter = (node, opts) => {
let color
let text
let childText
if (node.type === 'text') {
text = node.data
return text
}
if (node.name === 'span' && node.type === 'tag') {
color = camelCase(node.attribs.class.split('-')[1])
}
if (node.childNodes && node.childNodes.length > 0) {
childText = node.childNodes.map(childNode => filter(childNode, opts)).join('')
if (typeof color === 'string') {
return opts.colors[color](childText)
}
return childText
}
return ''
}
const findLongestLine = (text, opts) => {
let tabPad = ''
if (opts.$indent.tabs) {
tabPad = String().padEnd(opts.consoleTabWidth, ' ')
}
const lines = stripAnsi(text)
.replace(/\t/g, tabPad)
.split('\n')
let max = 0
lines.forEach(line => {
if (line.length > max) {
max = line.length
}
})
return max
}
const padLine = (line, padding) => {
const padStr = String().padStart(padding, ' ')
return padStr + line + padStr
}
const getIndentStr = opts => {
if (opts.$indent.tabs) {
return String().padStart(1, '\t')
}
// Opts.$indent.spaces === true
if (opts.tabsToSpaces === 0) {
return '\u0000'
}
return String().padEnd(opts.tabsToSpaces, ' ')
}
const syntaxHlStr = (lang, script, opts, indentStart) => {
let output = ''
const indentStr = getIndentStr(opts)
if (opts.$indent.tabs) {
script = script.replace(/\t/g, indentStr)
}
if (opts.$indent.spaces) {
script = script.replace(/\t/g, indentStr)
}
if (indentStart) {
script = indentStr + script
}
const code = hljs.highlight(script, { language: lang }).value
const lines = code.split('\n')
lines.forEach((line, lineNumber) => {
const html = `<code>${line}</code>`
const $body = cheerio.load(html).root().find('code')[0]
const text = filter($body, opts)
output += text
if (lineNumber !== lines.length - 1) {
output += '\n'
}
})
return output
}
const syntaxHlJson = (json, opts) => {
const indentStr = getIndentStr(opts)
try {
json = JSON.stringify(json, (key, val) => {
if (val instanceof Function) {
return `[FUNCTION]${String(val)}[FUNCTION]`
}
return val
}, indentStr)
} catch (err) {
err.message = '🦅 Chromafi: ' + err.message
throw new Error(err)
}
const highlighted = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, match => {
let colorClass = 'number'
if (/^"/.test(match)) {
if (/:$/.test(match)) {
if (match.includes('-')) {
colorClass = 'attrString'
match = match.replace(/"/g, '\'')
} else {
colorClass = 'attr'
match = match.replace(/"/g, '')
}
} else {
colorClass = 'string'
if (match.substr(1, 10) === '[FUNCTION]' &&
match.substr(match.length - 11, 10) === '[FUNCTION]') {
colorClass = 'function'
} else {
match = match.replace(/"/g, '\'')
match = match.replace(/\\n/g, '\n')
match = match.replace(/\\t/g, indentStr)
}
}
} else if (/true|false/.test(match)) {
colorClass = 'literal'
} else if (/null/.test(match)) {
colorClass = 'literal'
}
return opts.colors[colorClass](match)
})
const getFnStrIndent = (fnStr, opts) => {
fnStr = fnStr.replace(/\t/g, indentStr)
const indent = detectIndent(fnStr)
if (opts.$indent.spaces) {
const indentLevel = indent.amount / opts.tabsToSpaces
return indentLevel
}
if (opts.$indent.tabs) {
const indentLevel = indent.amount
return indentLevel
}
}
const lines = highlighted.split('\n').map(line => {
const fnParts = line.split('[FUNCTION]')
if (fnParts.length === 3) {
const plain = stripAnsi(line)
let outerIndent
if (opts.$indent.spaces) {
outerIndent = plain.match(/^[ \\t]*/)[0].length / opts.tabsToSpaces
}
if (opts.$indent.tabs) {
outerIndent = plain.match(/^\t*/)[0].length
}
const fnStr = fnParts[1]
.replace(/"/g, '\'')
.replace(/\\n/g, '\n')
.replace(/\\t/g, '\t')
const innerIndent = getFnStrIndent(fnStr, opts)
const indentOffset = Math.abs(outerIndent - (innerIndent - 1))
const re = new RegExp(`\n(\t){${indentOffset}}`, 'g')
const reTabbed = fnStr
.replace(re, '\n')
.replace(/\\t/g, indentStr)
const preFn = fnParts[0].substr(0, fnParts[0].length - 1)
const postFn = fnParts[2].substr(1)
const jsHighlighted = syntaxHlStr('javascript', reTabbed, opts)
return preFn + jsHighlighted + postFn
}
return line
}).join('\n')
return lines
}
const lineNumberPad = (number, opts) => {
if (!opts.lineNumbers) {
return ''
}
let output = ''
const offsetLineN = number + (opts.lineNumberStart - 1)
if (opts.$indent.spaces) {
const padStr = String().padStart(opts.lineNumberPad, ' ')
const prePad = opts.lineNumberPad + opts.$maxDigitWidth
output = String(offsetLineN).padStart(prePad) + padStr
}
// Indent using spaces - up to the tabwidth required to contain number str
if (opts.$indent.tabs) {
output = String(offsetLineN).padStart(opts.$maxTabSpace, ' ')
}
return opts.colors.lineNumbers(output)
}
const cropPadAndNumber = (text, opts) => {
let output = ''
const lines = text.split('\n')
const maxDigitWidth = String(lines.length + (opts.lineNumberStart - 1)).length
// Tabs needed to contain digits (so we dont break code tab indentation)
const tabsNeeded = Math.ceil(maxDigitWidth / opts.consoleTabWidth)
const maxTabSpace = tabsNeeded * opts.consoleTabWidth
const longestLineLen = findLongestLine(text, opts)
opts.$maxTabSpace = maxTabSpace
opts.$maxDigitWidth = maxDigitWidth
lines.forEach((line, i) => {
const lineNumber = i + 1
if (lineNumber < opts.firstLine || lineNumber > opts.lastLine) {
return
}
const lineNo = lineNumberPad(lineNumber, opts)
const tabCount = (line.match(/\t/g) || []).length
const tabAdjust = (tabCount * opts.consoleTabWidth)
const plain = stripAnsi(line).replace(/\t/g, '')
const linePad = String().padEnd((longestLineLen - plain.length) - tabAdjust, ' ')
const runLengthLine = line + opts.colors.trailingSpace(linePad)
let lineOutput
if (opts.tabsToSpaces === false) {
lineOutput = lineNo + runLengthLine
}
if (typeof opts.tabsToSpaces === 'number') {
lineOutput = lineNo + padLine(runLengthLine, opts.codePad)
}
output += lineOutput + '\n'
})
return opts.colors.base(output)
}
const decorate = (ansiStr, opts) => {
ansiStr = cropPadAndNumber(ansiStr, opts)
return ansiStr
}
const nameifyArrowFn = (fn, opts) => {
if (Reflect.has(fn, 'prototype') &&
Reflect.has(fn.prototype, 'constructor')) {
return ''
}
return `${opts.arrowKeyword} ${fn.name} = `
}
const procOpts = (opts = {}) => {
let options = {
lineNumbers: true,
lang: 'javascript',
lineNumberPad: 0,
lineNumberStart: 1,
start: 1,
end: Infinity,
highlight: false,
stripIndent: true,
codePad: 1,
colors: darkPalette,
tabsToSpaces: 4,
consoleTabWidth: 8,
arrowKeyword: 'const'
}
options = merge(options, opts)
options.$indent = {
spaces: typeof options.tabsToSpaces === 'number',
tabs: typeof options.tabsToSpaces === 'boolean' &&
options.tabsToSpaces === false,
size: typeof options.tabsToSpaces === 'number' ? options.tabsToSpaces : 1
}
return options
}
const chromafi = (value, opts) => {
opts = procOpts(opts)
if (typeof value === 'function') {
value = nameifyArrowFn(value, opts) + String(value)
const indentStart = true
value = syntaxHlStr('javascript', value, opts, indentStart)
value = stripIndent(value)
if (!opts || false !== opts.decorate) {
value = decorate(value, opts)
}
return value
}
if (typeof value === 'string') {
value = syntaxHlStr(opts.lang, value, opts)
if (!opts || false !== opts.decorate) {
value = decorate(value, opts)
}
return value
}
if (typeof value === 'object') {
value = syntaxHlJson(value, opts)
if (!opts || false !== opts.decorate) {
value = decorate(value, opts)
}
return value
}
throw new Error('🦅 Chromafi: You must pass a function, string or object.')
}
module.exports = chromafi