Skip to content

Commit 82fd7d2

Browse files
committed
perf: memoize syntax highlighting in CodeBlock
hljs.highlightAuto() ran inline in the template on every render.
1 parent f6d0657 commit 82fd7d2

1 file changed

Lines changed: 9 additions & 3 deletions

File tree

src/lib/components/chat/Messages/CodeBlock.svelte

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,14 @@
5353
updateCode();
5454
}
5555
56+
$: highlightedCode = (() => {
57+
try {
58+
return hljs.highlightAuto(code, hljs.getLanguage(lang)?.aliases).value || code;
59+
} catch {
60+
return code;
61+
}
62+
})();
63+
5664
const updateCode = () => {
5765
_code = code;
5866
};
@@ -62,7 +70,6 @@
6270
let renderHTML = null;
6371
let renderError = null;
6472
65-
let highlightedCode = null;
6673
let executing = false;
6774
6875
let stdout = null;
@@ -544,8 +551,7 @@
544551
result) &&
545552
'border-bottom-left-radius: 0px; border-bottom-right-radius: 0px;'}"><code
546553
class="language-{lang} rounded-t-none whitespace-pre text-sm"
547-
>{@html hljs.highlightAuto(code, hljs.getLanguage(lang)?.aliases).value ||
548-
code}</code
554+
>{@html highlightedCode}</code
549555
></pre>
550556
{/if}
551557
{:else}

0 commit comments

Comments
 (0)