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

DiffWorkerPoolProvider.tsx

84 lines2.6 KB

1import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
2import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
3import * as Schema from "effect/Schema";
4import { useEffect, useMemo, type ReactNode } from "react";
5import { useTheme } from "../hooks/useTheme";
6import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
7​
8export class DiffWorkerError extends Schema.TaggedErrorClass<DiffWorkerError>()("DiffWorkerError", {
9 operation: Schema.Literals(["create-worker", "get-render-options", "set-render-options"]),
10 themeName: Schema.Literals(["pierre-light", "pierre-dark"]),
11 cause: Schema.Defect(),
12}) {
13 override get message(): string {
14 return `Diff worker operation ${this.operation} failed for theme ${this.themeName}.`;
15 }
17​
18function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
19 const workerPool = useWorkerPool();
20​
21 useEffect(() => {
22 if (!workerPool) {
23 return;
24 }
25​
26 let operation: DiffWorkerError["operation"] = "get-render-options";
27 void (async () => {
28 try {
29 const current = workerPool.getDiffRenderOptions();
30 if (current.theme === themeName) {
31 return;
32 }
33​
34 operation = "set-render-options";
35 await workerPool.setRenderOptions({
36 ...current,
37 theme: themeName,
38 });
39 } catch (cause) {
40 console.error(new DiffWorkerError({ operation, themeName, cause }));
41 }
42 })();
43 }, [themeName, workerPool]);
44​
45 return null;
47​
48export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
49 const { resolvedTheme } = useTheme();
50 const diffThemeName = resolveDiffThemeName(resolvedTheme);
51 const workerPoolSize = useMemo(() => {
52 const cores =
53 typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
54 return Math.max(2, Math.min(6, Math.floor(cores / 2)));
55 }, []);
56​
57 return (
58 <WorkerPoolContextProvider
59 poolOptions={{
60 workerFactory: () => {
61 try {
62 return new DiffsWorker();
63 } catch (cause) {
64 throw new DiffWorkerError({
65 operation: "create-worker",
66 themeName: diffThemeName,
67 cause,
68 });
69 }
70 },
71 poolSize: workerPoolSize,
72 totalASTLRUCacheSize: 240,
73 }}
74 highlighterOptions={{
75 theme: diffThemeName,
76 tokenizeMaxLineLength: 1_000,
77 useTokenTransformer: true,
78 }}
79 >
80 <DiffWorkerThemeSync themeName={diffThemeName} />
81 {children}
82 </WorkerPoolContextProvider>
83 );