You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.4 KiB

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