2023-08-17 09:47:40 +00:00
|
|
|
'use strict'
|
2022-01-21 08:28:41 +00:00
|
|
|
|
2023-08-17 09:47:40 +00:00
|
|
|
let pico = require('picocolors')
|
2022-01-21 08:28:41 +00:00
|
|
|
|
2023-08-17 09:47:40 +00:00
|
|
|
let tokenizer = require('./tokenize')
|
2022-01-21 08:28:41 +00:00
|
|
|
|
2023-08-17 09:47:40 +00:00
|
|
|
let Input
|
2022-01-21 08:28:41 +00:00
|
|
|
|
2023-08-17 09:47:40 +00:00
|
|
|
function registerInput(dependant) {
|
|
|
|
Input = dependant
|
|
|
|
}
|
2022-01-21 08:28:41 +00:00
|
|
|
|
2023-08-17 09:47:40 +00:00
|
|
|
const HIGHLIGHT_THEME = {
|
|
|
|
';': pico.yellow,
|
|
|
|
':': pico.yellow,
|
|
|
|
'(': pico.cyan,
|
|
|
|
')': pico.cyan,
|
|
|
|
'[': pico.yellow,
|
|
|
|
']': pico.yellow,
|
|
|
|
'{': pico.yellow,
|
|
|
|
'}': pico.yellow,
|
|
|
|
'at-word': pico.cyan,
|
|
|
|
'brackets': pico.cyan,
|
|
|
|
'call': pico.cyan,
|
|
|
|
'class': pico.yellow,
|
|
|
|
'comment': pico.gray,
|
|
|
|
'hash': pico.magenta,
|
|
|
|
'string': pico.green
|
|
|
|
}
|
2022-01-21 08:28:41 +00:00
|
|
|
|
2023-08-17 09:47:40 +00:00
|
|
|
function getTokenType([type, value], processor) {
|
2022-01-21 08:28:41 +00:00
|
|
|
if (type === 'word') {
|
|
|
|
if (value[0] === '.') {
|
2023-08-17 09:47:40 +00:00
|
|
|
return 'class'
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
if (value[0] === '#') {
|
2023-08-17 09:47:40 +00:00
|
|
|
return 'hash'
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!processor.endOfFile()) {
|
2023-08-17 09:47:40 +00:00
|
|
|
let next = processor.nextToken()
|
|
|
|
processor.back(next)
|
|
|
|
if (next[0] === 'brackets' || next[0] === '(') return 'call'
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
|
2023-08-17 09:47:40 +00:00
|
|
|
return type
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function terminalHighlight(css) {
|
2023-08-17 09:47:40 +00:00
|
|
|
let processor = tokenizer(new Input(css), { ignoreErrors: true })
|
|
|
|
let result = ''
|
|
|
|
while (!processor.endOfFile()) {
|
|
|
|
let token = processor.nextToken()
|
|
|
|
let color = HIGHLIGHT_THEME[getTokenType(token, processor)]
|
2022-01-21 08:28:41 +00:00
|
|
|
if (color) {
|
2023-08-17 09:47:40 +00:00
|
|
|
result += token[1]
|
|
|
|
.split(/\r?\n/)
|
|
|
|
.map(i => color(i))
|
|
|
|
.join('\n')
|
2022-01-21 08:28:41 +00:00
|
|
|
} else {
|
2023-08-17 09:47:40 +00:00
|
|
|
result += token[1]
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
}
|
2023-08-17 09:47:40 +00:00
|
|
|
return result
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
|
2023-08-17 09:47:40 +00:00
|
|
|
terminalHighlight.registerInput = registerInput
|
|
|
|
|
|
|
|
module.exports = terminalHighlight
|