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

DiffWorkerPoolProvider.tsx

159 lines4.9 KB

1import { WorkerPoolContext, useWorkerPool } from "@pierre/diffs/react";
2import { WorkerPoolManager } from "@pierre/diffs/worker";
3import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
4import * as Schema from "effect/Schema";
5import { useEffect, useState, useSyncExternalStore, type ReactNode } from "react";
6import { useStableCallback } from "../hooks/useStableCallback";
7import { useTheme } from "../hooks/useTheme";
8import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
9import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
10​
11export class DiffWorkerError extends Schema.TaggedError<DiffWorkerError>()("DiffWorkerError", {
12 operation: Schema.Literals(["create-worker", "get-render-options", "set-render-options"]),
13 themeName: Schema.Literals(["pierre-light", "pierre-dark"]),
14 cause: Schema.Defect(),
15}) {
16 override get message(): string {
17 return `Diff worker operation ${this.operation} failed for theme ${this.themeName}.`;
18 }
20​
21const DIFF_WORKER_IDLE_TTL_MS = 30_000;
22function resolveDiffWorkerPoolSize() {
23 const cores =
24 typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
25 return Math.max(2, Math.min(6, Math.floor(cores / 2)));
27let sharedWorkerPool:
28 | {
29 readonly pool: WorkerPoolManager;
30 consumers: number;
31 idleTimer: ReturnType<typeof setTimeout> | undefined;
32 }
33 | undefined;
34​
35function acquireDiffWorkerPool(themeName: DiffThemeName, poolSize: number) {
36 const entry = (sharedWorkerPool ??= {
37 pool: new WorkerPoolManager(
38 {
39 workerFactory: () => {
40 try {
41 return new DiffsWorker();
42 } catch (cause) {
43 throw new DiffWorkerError({ operation: "create-worker", themeName, cause });
44 }
45 },
46 poolSize,
47 totalASTLRUCacheSize: 240,
48 },
49 {
50 theme: themeName,
51 preferredHighlighter: PREFERRED_HIGHLIGHTER,
52 tokenizeMaxLineLength: 1_000,
53 useTokenTransformer: true,
54 },
55 ),
56 consumers: 0,
57 idleTimer: undefined,
58 });
59 clearTimeout(entry.idleTimer);
60 entry.idleTimer = undefined;
61 entry.consumers += 1;
62 return entry;
64​
65function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
66 const workerPool = useWorkerPool();
67​
68 useEffect(() => {
69 if (!workerPool) {
70 return;
71 }
72​
73 let operation: DiffWorkerError["operation"] = "get-render-options";
74 void (async () => {
75 try {
76 const current = workerPool.getDiffRenderOptions();
77 if (current.theme === themeName) {
78 return;
79 }
80​
81 operation = "set-render-options";
82 await workerPool.setRenderOptions({
83 ...current,
84 theme: themeName,
85 });
86 } catch (cause) {
87 console.error(new DiffWorkerError({ operation, themeName, cause }));
88 }
89 })();
90 }, [themeName, workerPool]);
91​
92 return null;
94​
95// Plain-text views do not queue a highlight task that could retry a blank first render.
96function DiffWorkerReady({ children }: { children?: ReactNode }) {
97 const workerPool = useWorkerPool();
98 const [readyPool, setReadyPool] = useState<WorkerPoolManager>();
99 const ready = workerPool
100 ? readyPool === workerPool || workerPool.isInitialized() || !workerPool.isWorkingPool()
101 : typeof window === "undefined";
102​
103 useEffect(() => {
104 if (ready || !workerPool) return;
105​
106 let mounted = true;
107 const finish = () => {
108 if (mounted) setReadyPool(workerPool);
109 };
110 void workerPool.initialize().then(finish, finish);
111 return () => {
112 mounted = false;
113 };
114 }, [ready, workerPool]);
115​
116 return ready ? (
117 children
118 ) : (
119 <div
120 role="status"
121 className="flex min-h-0 flex-1 items-center justify-center p-4 text-xs text-muted-foreground"
122 >
123 Loading code...
124 </div>
125 );
127​
128export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
129 const { resolvedTheme } = useTheme();
130 const diffThemeName = resolveDiffThemeName(resolvedTheme);
131 const [workerPoolSize] = useState(resolveDiffWorkerPoolSize);
132 // A new subscribe identity makes React release and reacquire the shared pool on every render.
133 const subscribe = useStableCallback((onStoreChange: () => void) => {
134 if (typeof window === "undefined") return () => {};
135 const entry = acquireDiffWorkerPool(diffThemeName, workerPoolSize);
136 onStoreChange();
137 return () => {
138 entry.consumers -= 1;
139 if (entry.consumers !== 0) return;
140 entry.idleTimer = setTimeout(() => {
141 entry.idleTimer = undefined;
142 entry.pool.terminate();
143 if (sharedWorkerPool === entry) sharedWorkerPool = undefined;
144 }, DIFF_WORKER_IDLE_TTL_MS);
145 };
146 });
147 const workerPool = useSyncExternalStore(
148 subscribe,
149 () => sharedWorkerPool?.pool,
150 () => undefined,
151 );
152​
153 return (
154 <WorkerPoolContext value={workerPool}>
155 <DiffWorkerThemeSync themeName={diffThemeName} />
156 <DiffWorkerReady>{children}</DiffWorkerReady>
157 </WorkerPoolContext>
158 );