Open History to see the last commit
1import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
2import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
3import { useEffect, useMemo, type ReactNode } from "react";
4import { useTheme } from "../hooks/useTheme";
5
6function resolveDiffThemeName(theme: "light" | "dark") {
7 return theme === "dark" ? "pierre-dark" : "pierre-light";
8}
9
10function DiffWorkerThemeSync({ themeName }: { themeName: "pierre-light" | "pierre-dark" }) {
11 const workerPool = useWorkerPool();
12
13 useEffect(() => {
14 if (!workerPool) {
15 return;
16 }
17
18 const current = workerPool.getDiffRenderOptions();
19 if (current.theme === themeName) {
20 return;
21 }
22
23 void workerPool
24 .setRenderOptions({
25 ...current,
26 theme: themeName,
27 })
28 .catch(() => undefined);
29 }, [themeName, workerPool]);
30
31 return null;
32}
33
34export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
35 const { resolvedTheme } = useTheme();
36 const diffThemeName = resolveDiffThemeName(resolvedTheme);
37 const workerPoolSize = useMemo(() => {
38 const cores =
39 typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
40 return Math.max(2, Math.min(6, Math.floor(cores / 2)));
41 }, []);
42
43 return (
44 <WorkerPoolContextProvider
45 poolOptions={{
46 workerFactory: () => new DiffsWorker(),
47 poolSize: workerPoolSize,
48 totalASTLRUCacheSize: 240,
49 }}
50 highlighterOptions={{
51 theme: diffThemeName,
52 tokenizeMaxLineLength: 1_000,
53 }}
54 >
55 <DiffWorkerThemeSync themeName={diffThemeName} />
56 {children}
57 </WorkerPoolContextProvider>
58 );
59}