Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

incrementalSnippet.ts

65 lines2.1 KB

1import type { HighlighterCore } from "@shikijs/core";
2​
3export function createIncrementalSnippet(
4 highlighter: HighlighterCore,
5 language: string,
6 theme: string,
7) {
8 const options = { lang: language, theme };
9 let cached:
10 | {
11 prefix: string;
12 tokens: ReturnType<HighlighterCore["codeToTokensBase"]>;
13 state: ReturnType<HighlighterCore["getLastGrammarState"]>;
14 }
15 | undefined;
16 let revision = 0;
17​
18 function* tokenize(code: string) {
19 const currentRevision = ++revision;
20 const previous = cached && code.startsWith(cached.prefix) ? cached : undefined;
21 const end = code.lastIndexOf("\n") + 1;
22 let state = previous?.state;
23 const tokens = [...(previous?.tokens ?? [])];
24 const completed = code.slice(previous?.prefix.length ?? 0, end);
25 if (completed) {
26 const lines = completed.slice(0, -1).split("\n");
27 for (let offset = 0; offset < lines.length; offset += 200) {
28 const batch = highlighter.codeToTokensBase(lines.slice(offset, offset + 200).join("\n"), {
29 ...options,
30 ...(state ? { grammarState: state } : {}),
31 });
32 state = highlighter.getLastGrammarState(batch);
33 tokens.push(...batch);
34 if (offset + 200 < lines.length) yield;
35 }
36 }
37 if (currentRevision === revision) {
38 cached = state ? { prefix: code.slice(0, end), tokens, state } : undefined;
39 }
40 return [
41 ...tokens,
42 ...highlighter.codeToTokensBase(code.slice(end), {
43 ...options,
44 ...(state ? { grammarState: state } : {}),
45 }),
46 ];
47 }
48 const highlight = async (code: string) => {
49 const work = tokenize(code);
50 let next = work.next();
51 while (!next.done) {
52 await new Promise<void>((resolve) => setTimeout(resolve, 0));
53 next = work.next();
54 }
55 return next.value;
56 };
57 highlight.read = (code: string) => {
58 if (!cached || !code.startsWith(cached.prefix)) return undefined;
59 const tail = code.slice(cached.prefix.length);
60 if (tail.length > 2_000 || tail.split("\n").length > 200) return undefined;
61 const next = tokenize(code).next();
62 return next.done ? next.value : undefined;
63 };
64 return highlight;