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

DiffWorkerPoolProvider.tsx

162 lines5.3 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 { subscribeClientSettings } from "../hooks/useSettings";
7import { getRenderedAppearance, subscribeRenderedAppearance } from "../hooks/useTheme";
8import { resolveDiffThemeName } 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", "t3-light"]),
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 readonly unsubscribeTheme: () => void;
31 consumers: number;
32 idleTimer: ReturnType<typeof setTimeout> | undefined;
33 }
34 | undefined;
35​
36function applyDiffWorkerTheme(pool: WorkerPoolManager) {
37 const themeName = resolveDiffThemeName(getRenderedAppearance());
38 let operation: DiffWorkerError["operation"] = "get-render-options";
39 void (async () => {
40 try {
41 const current = pool.getDiffRenderOptions();
42 if (current.theme === themeName) return;
43 operation = "set-render-options";
44 await pool.setRenderOptions({ ...current, theme: themeName });
45 } catch (cause) {
46 console.error(new DiffWorkerError({ operation, themeName, cause }));
47 }
48 })();
50​
51// The pool follows the rendered appearance for as long as it lives, so it never depends on a
52// mounted provider to carry a theme change across.
53function createDiffWorkerPool(poolSize: number) {
54 const themeName = resolveDiffThemeName(getRenderedAppearance());
55 const pool = new WorkerPoolManager(
56 {
57 workerFactory: () => {
58 try {
59 return new DiffsWorker();
60 } catch (cause) {
61 throw new DiffWorkerError({ operation: "create-worker", themeName, cause });
62 }
63 },
64 poolSize,
65 totalASTLRUCacheSize: 240,
66 },
67 {
68 theme: themeName,
69 preferredHighlighter: PREFERRED_HIGHLIGHTER,
70 tokenizeMaxLineLength: 1_000,
71 useTokenTransformer: true,
72 },
73 );
74 return {
75 pool,
76 unsubscribeTheme: (() => {
77 const apply = () => applyDiffWorkerTheme(pool);
78 // The New design picks the light syntax palette, so a settings change can switch it too.
79 const unsubscribes = [subscribeRenderedAppearance(apply), subscribeClientSettings(apply)];
80 return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
81 })(),
82 consumers: 0,
83 idleTimer: undefined,
84 };
86​
87function acquireDiffWorkerPool(poolSize: number) {
88 const entry = (sharedWorkerPool ??= createDiffWorkerPool(poolSize));
89 clearTimeout(entry.idleTimer);
90 entry.idleTimer = undefined;
91 entry.consumers += 1;
92 return entry;
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​
128// Module-level so the subscribe identity is stable: a new one would release and reacquire
129// the shared pool on every render.
130function subscribeSharedWorkerPool(onStoreChange: () => void) {
131 if (typeof window === "undefined") return () => {};
132 const entry = acquireDiffWorkerPool(resolveDiffWorkerPoolSize());
133 onStoreChange();
134 return () => {
135 entry.consumers -= 1;
136 if (entry.consumers !== 0) return;
137 entry.idleTimer = setTimeout(() => {
138 entry.idleTimer = undefined;
139 entry.unsubscribeTheme();
140 entry.pool.terminate();
141 if (sharedWorkerPool === entry) sharedWorkerPool = undefined;
142 }, DIFF_WORKER_IDLE_TTL_MS);
143 };
145​
146export function useDiffWorkerPool() {
147 return useSyncExternalStore(
148 subscribeSharedWorkerPool,
149 () => sharedWorkerPool?.pool,
150 () => undefined,
151 );
153​
154export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
155 const workerPool = useDiffWorkerPool();
156​
157 return (
158 <WorkerPoolContext value={workerPool}>
159 <DiffWorkerReady>{children}</DiffWorkerReady>
160 </WorkerPoolContext>
161 );