|
| 1 | +import { type TokenColors, highlight as baseHighlight } from 'tinyhighlight' |
| 2 | +import type { ColorName } from './colors' |
| 3 | +import { getColors } from './colors' |
| 4 | + |
| 5 | +type Colors = Record<ColorName, (input: string) => string> |
| 6 | + |
| 7 | +function getDefs(c: Colors): TokenColors { |
| 8 | + const Invalid = (text: string) => c.white(c.bgRed(c.bold(text))) |
| 9 | + return { |
| 10 | + Keyword: c.magenta, |
| 11 | + IdentifierCapitalized: c.yellow, |
| 12 | + Punctuator: c.yellow, |
| 13 | + StringLiteral: c.green, |
| 14 | + NoSubstitutionTemplate: c.green, |
| 15 | + MultiLineComment: c.gray, |
| 16 | + SingleLineComment: c.gray, |
| 17 | + RegularExpressionLiteral: c.cyan, |
| 18 | + NumericLiteral: c.blue, |
| 19 | + TemplateHead: text => c.green(text.slice(0, text.length - 2)) + c.cyan(text.slice(-2)), |
| 20 | + TemplateTail: text => c.cyan(text.slice(0, 1)) + c.green(text.slice(1)), |
| 21 | + TemplateMiddle: text => c.cyan(text.slice(0, 1)) + c.green(text.slice(1, text.length - 2)) + c.cyan(text.slice(-2)), |
| 22 | + IdentifierCallable: c.blue, |
| 23 | + PrivateIdentifierCallable: text => `#${c.blue(text.slice(1))}`, |
| 24 | + Invalid, |
| 25 | + |
| 26 | + JSXString: c.green, |
| 27 | + JSXIdentifier: c.yellow, |
| 28 | + JSXInvalid: Invalid, |
| 29 | + JSXPunctuator: c.yellow, |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +interface HighlightOptions { |
| 34 | + jsx?: boolean |
| 35 | + colors?: Colors |
| 36 | +} |
| 37 | + |
| 38 | +export function highlight(code: string, options: HighlightOptions = { jsx: false }) { |
| 39 | + return baseHighlight(code, { |
| 40 | + jsx: options.jsx, |
| 41 | + colors: getDefs(options.colors || getColors()), |
| 42 | + }) |
| 43 | +} |
0 commit comments