| 1 | "use client"; |
| 2 | |
| 3 | import { Fragment, useEffect |
| 4 | import type { ThemedToken |
| 5 | |
| 6 | import { highlightLines } |
| 7 | |
| 8 | /** A fenced block's code, plain until its tokens arrive. Coloured for every theme at once, so a theme switch needs no second pass. */ |
| 9 | export function HighlightedCode({ |
| 10 | code, |
| 11 | language, |
| 12 | }: { |
| 13 | code: string |
| 14 | language: string |
| 15 | }) { |
| 16 | const [highlighted, |
| 17 | code: string |
| 18 | tokens: ThemedToken |
| 19 | }>(); |
| 20 | |
| 21 | useEffect(() => |
| 22 | let cancelled = |
| 23 | // a bare language name resolves like a file extension: `ts`, `py`, `dockerfile` |
| 24 | highlightLines(code, language |
| 25 | .then((tokens) |
| 26 | if (!cancelled) |
| 27 | }) |
| 28 | // a grammar the engine cannot run leaves the block plain |
| 29 | .catch(() => |
| 30 | return () => |
| 31 | cancelled = true; |
| 32 | }; |
| 33 | }, [code, |
| 34 | |
| 35 | // tokens for text that has since been edited would show the old text |
| 36 | if (highlighted?.code |
| 37 | |
| 38 | return ( |
| 39 | <code data-shiki> |
| 40 | {highlighted.tokens.map |
| 41 | <Fragment key={ |
| 42 | {index > 0 |
| 43 | {line.map(( |
| 44 | <span key={token |
| 45 | {token.content} |
| 46 | </span> |
| 47 | ))} |
| 48 | </Fragment> |
| 49 | ))} |
| 50 | </code> |
| 51 | ); |
| 52 | } |