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 ';': pico.yellow,
15 ':': pico.yellow,
16 '(': pico.cyan,
17 ')': pico.cyan,
18 '[': pico.yellow,
19 ']': pico.yellow,
20 '{': pico.yellow,
21 '}': pico.yellow,
22 'at-word': pico.cyan,
23 'brackets': pico.cyan,
24 'call': pico.cyan,
25 'class': pico.yellow,
26 'comment': pico.gray,
27 'hash': pico.magenta,
28 'string': pico.green
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