({
code,
language,
theme,
}: UseCodeHighlightProps)
| 63 | } |
| 64 | |
| 65 | export function useCodeHighlight({ |
| 66 | code, |
| 67 | language, |
| 68 | theme, |
| 69 | }: UseCodeHighlightProps) { |
| 70 | const [html, setHtml] = useState(() => getCachedHtml(code, language) ?? ""); |
| 71 | const [loading, setLoading] = useState(() => !getCachedHtml(code, language)); |
| 72 | const prevThemeRef = useRef(theme); |
| 73 | |
| 74 | const cssVariables = useMemo(() => { |
| 75 | const vars = theme.variables; |
| 76 | return Object.entries(vars) |
| 77 | .map(([key, value]) => `${key}: ${value};`) |
| 78 | .join("\n"); |
| 79 | }, [theme.variables]); |
| 80 | |
| 81 | useEffect(() => { |
| 82 | prevThemeRef.current = theme; |
| 83 | }, [theme]); |
| 84 | |
| 85 | useEffect(() => { |
| 86 | let cancelled = false; |
| 87 | |
| 88 | const highlight = async () => { |
| 89 | const cached = getCachedHtml(code, language); |
| 90 | if (!cached) setLoading(true); |
| 91 | |
| 92 | try { |
| 93 | const result = await codeToHtml(code, { |
| 94 | lang: language as Parameters<typeof codeToHtml>[1]["lang"], |
| 95 | theme: shikiTheme, |
| 96 | transformers: [ |
| 97 | transformerNotationDiff(), |
| 98 | transformerNotationHighlight(), |
| 99 | transformerNotationWordHighlight(), |
| 100 | transformerNotationFocus(), |
| 101 | transformerNotationErrorLevel(), |
| 102 | ], |
| 103 | }); |
| 104 | if (!cancelled) { |
| 105 | const processed = result.replace( |
| 106 | /<pre([^>]*)>/g, |
| 107 | '<pre$1 style="background: transparent; margin: 0; overflow-x: auto;">', |
| 108 | ); |
| 109 | setHtml(processed); |
| 110 | setLoading(false); |
| 111 | setCachedHtml(code, language, processed); |
| 112 | } |
| 113 | } catch { |
| 114 | if (!cancelled) { |
| 115 | setHtml(`<pre><code>${code}</code></pre>`); |
| 116 | setLoading(false); |
| 117 | } |
| 118 | } |
| 119 | }; |
| 120 | |
| 121 | highlight(); |
| 122 | return () => { |
no test coverage detected