UNPKG

1.4 kBJavaScriptView Raw
1'use strict'
2
3let pico = require('picocolors')
4
5let tokenizer = require('./tokenize')
6
7let Input
8
9function registerInput(dependant) {
10 Input = dependant
11}
12
13const HIGHLIGHT_THEME = {
14 'brackets': pico.cyan,
15 'at-word': pico.cyan,
16 'comment': pico.gray,
17 'string': pico.green,
18 'class': pico.yellow,
19 'hash': pico.magenta,
20 'call': pico.cyan,
21 '(': pico.cyan,
22 ')': pico.cyan,
23 '{': pico.yellow,
24 '}': pico.yellow,
25 '[': pico.yellow,
26 ']': pico.yellow,
27 ':': pico.yellow,
28 ';': pico.yellow
29}
30
31function getTokenType([type, value], processor) {
32 if (type === 'word') {
33 if (value[0] === '.') {
34 return 'class'
35 }
36 if (value[0] === '#') {
37 return 'hash'
38 }
39 }
40
41 if (!processor.endOfFile()) {
42 let next = processor.nextToken()
43 processor.back(next)
44 if (next[0] === 'brackets' || next[0] === '(') return 'call'
45 }
46
47 return type
48}
49
50function terminalHighlight(css) {
51 let processor = tokenizer(new Input(css), { ignoreErrors: true })
52 let result = ''
53 while (!processor.endOfFile()) {
54 let token = processor.nextToken()
55 let color = HIGHLIGHT_THEME[getTokenType(token, processor)]
56 if (color) {
57 result += token[1]
58 .split(/\r?\n/)
59 .map(i => color(i))
60 .join('\n')
61 } else {
62 result += token[1]
63 }
64 }
65 return result
66}
67
68terminalHighlight.registerInput = registerInput
69
70module.exports = terminalHighlight