Skip to content
TypeScript

perf(web): highlighted code tokens compile without manual memoization (#20678)

Julius Marmingecba00ae1971f
diff --git a/apps/web/src/components/chat/HighlightedTokens.tsx b/apps/web/src/components/chat/HighlightedTokens.tsx
index 67686370aae..e686267df09 100644
--- a/apps/web/src/components/chat/HighlightedTokens.tsx
+++ b/apps/web/src/components/chat/HighlightedTokens.tsx
@@ -1,4 +1,4 @@
-import { use, useMemo, type CSSProperties } from "react";
+import { use, type CSSProperties } from "react";
import { resolveDiffThemeName } from "../../lib/diffRendering";
import type { EmbeddedScript } from "../../lib/embeddedScripts";
@@ -29,6 +29,20 @@ function syntaxTokenStyle(token: SyntaxToken): CSSProperties {
* Suspends while the grammar loads; wrap it in Suspense with the plain text as
* the fallback.
*/
+function useHighlightedLines(
+ highlighter: Awaited<ReturnType<typeof getSyntaxHighlighterPromise>>,
+ code: string,
+ language: string,
+ embedded: ReadonlyArray<EmbeddedScript>,
+ theme: "light" | "dark",
+) {
+ "use memo";
+ const themeName = resolveDiffThemeName(theme);
+ const tokenize = (text: string, lang: string) =>
+ highlighter.codeToTokens(text, { lang, theme: themeName }).tokens;
+ return keyedLines(code, withEmbeddedScripts(code, tokenize(code, language), embedded, tokenize));
+}
+
export function HighlightedTokens({
code,
language,
@@ -44,15 +58,7 @@ export function HighlightedTokens({
}) {
const highlighter = use(getSyntaxHighlighterPromise(language));
for (const script of embedded) use(getSyntaxHighlighterPromise(script.language));
- const lines = useMemo(() => {
- const themeName = resolveDiffThemeName(theme);
- const tokenize = (text: string, lang: string) =>
- highlighter.codeToTokens(text, { lang, theme: themeName }).tokens;
- return keyedLines(
- code,
- withEmbeddedScripts(code, tokenize(code, language), embedded, tokenize),
- );
- }, [code, embedded, highlighter, language, theme]);
+ const lines = useHighlightedLines(highlighter, code, language, embedded, theme);
return lines.map(({ key, tokens, ending }) => (
<span key={key}>