@anaralabs/lector 3.12.9 → 3.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -132,6 +132,23 @@ declare interface AnnotationTooltipProps {
132
132
  }) => React.ReactNode;
133
133
  }
134
134
 
135
+ /**
136
+ * Recolors a 2D context at draw time: every fill/stroke whose style is a
137
+ * string is painted with `map(style)` and the original style is restored
138
+ * right after, so pdf.js readbacks (`ctx.fillStyle`, `copyCtxState`,
139
+ * save/restore) always observe original-document colors and nothing is ever
140
+ * mapped twice. Gradients are recolored per stop at creation. `drawImage`
141
+ * and `putImageData` are deliberately untouched — photos keep their pixels —
142
+ * with one exception: a drawImage that composes a luminosity soft mask
143
+ * (destination-in through a pdf.js `*_luminosity_map_*` filter) draws a
144
+ * luma-corrected copy of the mask so the recoloring doesn't invert the
145
+ * mask's alpha.
146
+ *
147
+ * Wrapping installs own properties on the context instance (the prototype is
148
+ * never modified). Returns a cleanup that restores the pristine context.
149
+ */
150
+ export declare function applyContextRecolor(ctx: CanvasRenderingContext2D, map: RenderColorMap): () => void;
151
+
135
152
  /**
136
153
  * Calculates the highlight rectangles for a given text match.
137
154
  *
@@ -151,6 +168,11 @@ export declare const cancellable: <T extends Promise<unknown>>(promise: T) => {
151
168
  cancel: () => void;
152
169
  };
153
170
 
171
+ declare interface CanvasAndContext {
172
+ canvas: HTMLCanvasElement | null;
173
+ context: CanvasRenderingContext2D | null;
174
+ }
175
+
154
176
  export declare const CanvasLayer: MemoExoticComponent<({ style, background, ...props }: HTMLProps<HTMLCanvasElement> & {
155
177
  background?: string;
156
178
  }) => JSX.Element>;
@@ -182,6 +204,49 @@ declare type ColoredHighlightLayerProps = {
182
204
  onHighlight?: (highlight: ColoredHighlight) => void;
183
205
  };
184
206
 
207
+ declare type ColorScheme = "light" | "dark";
208
+ export { ColorScheme }
209
+ export { ColorScheme as ColorScheme_alias_1 }
210
+
211
+ /**
212
+ * Builds a memoized color map that flips perceived lightness onto the
213
+ * background<->foreground ramp while preserving hue and chroma (OKLab).
214
+ * Position on the ramp follows gamma-encoded BT.709 luma — the same measure
215
+ * "luminance inversion" night modes use — so saturated accents move the way
216
+ * readers expect (red becomes pink, not cyan; blue links become light blue).
217
+ * Neutrals land exactly on the ramp: white maps to `background`, black to
218
+ * `foreground`, including the palette's tint.
219
+ */
220
+ declare function createDarkModeColorMap(colors?: DarkModeColors): RenderColorMap;
221
+ export { createDarkModeColorMap }
222
+ export { createDarkModeColorMap as createDarkModeColorMap_alias_1 }
223
+
224
+ /**
225
+ * pdf.js paints transparency groups, soft masks, tiling/shading patterns and
226
+ * image-mask fills on internal scratch canvases obtained from the document's
227
+ * CanvasFactory — that content never touches the context we hand to
228
+ * `page.render()`. Passing this factory via getDocument's `CanvasFactory`
229
+ * option extends dark-mode recoloring to those canvases, which is what makes
230
+ * the scheme complete (pages with a page-level transparency group otherwise
231
+ * render entirely on a scratch canvas).
232
+ *
233
+ * The map is captured per canvas at creation time from `mapRef`; scratch
234
+ * canvases only live for a single render task, so toggling the scheme simply
235
+ * takes effect on the next render.
236
+ */
237
+ export declare function createRecolorCanvasFactory(mapRef: RenderColorMapRef): {
238
+ new ({ ownerDocument, enableHWA, }?: {
239
+ ownerDocument?: Document;
240
+ enableHWA?: boolean;
241
+ }): {
242
+ "__#44@#document": Document;
243
+ "__#44@#enableHWA": boolean;
244
+ create(width: number, height: number): CanvasAndContext;
245
+ reset(canvasAndContext: CanvasAndContext, width: number, height: number): void;
246
+ destroy(canvasAndContext: CanvasAndContext): void;
247
+ };
248
+ };
249
+
185
250
  export declare const CurrentPage: ({ ...props }: HTMLProps<HTMLInputElement>) => JSX.Element;
186
251
 
187
252
  export declare const CurrentZoom: ({ ...props }: HTMLProps<HTMLInputElement>) => JSX.Element;
@@ -190,6 +255,19 @@ export declare const CustomLayer: MemoExoticComponent<({ children }: {
190
255
  children: (pageNumber: number) => JSX_2.Element;
191
256
  }) => JSX_2.Element>;
192
257
 
258
+ declare interface DarkModeColors {
259
+ /** Replaces the white paper background. Any CSS hex/rgb color. */
260
+ background?: string;
261
+ /** Replaces black text and line art. Any CSS hex/rgb color. */
262
+ foreground?: string;
263
+ }
264
+ export { DarkModeColors }
265
+ export { DarkModeColors as DarkModeColors_alias_1 }
266
+
267
+ declare const DEFAULT_DARK_MODE_COLORS: Required<DarkModeColors>;
268
+ export { DEFAULT_DARK_MODE_COLORS }
269
+ export { DEFAULT_DARK_MODE_COLORS as DEFAULT_DARK_MODE_COLORS_alias_1 }
270
+
193
271
  export declare const ensureAnnotationLayerStyles: () => void;
194
272
 
195
273
  export declare const firstMemo: <T>(first: boolean, memo: unknown, initializer: () => T) => T;
@@ -238,6 +316,9 @@ export declare interface InitialPDFState {
238
316
  zoom: number;
239
317
  isZoomFitWidth?: boolean;
240
318
  zoomOptions?: ZoomOptions;
319
+ colorScheme?: ColorScheme;
320
+ darkModeColors?: DarkModeColors;
321
+ renderColorMapRef?: RenderColorMapRef;
241
322
  }
242
323
 
243
324
  export declare class LinkService {
@@ -349,6 +430,14 @@ declare interface PDFState {
349
430
  renderedPages: Record<number, true>;
350
431
  markPageRendered: (pageNumber: number) => void;
351
432
  unmarkPageRendered: (pageNumber: number) => void;
433
+ colorScheme: ColorScheme;
434
+ darkModeColors: Required<DarkModeColors>;
435
+ setColorScheme: (colorScheme: ColorScheme, colors?: DarkModeColors) => void;
436
+ /**
437
+ * Shared with the document's pdf.js CanvasFactory so internal scratch
438
+ * canvases (transparency groups, soft masks, patterns) follow the scheme.
439
+ */
440
+ renderColorMapRef: RenderColorMapRef;
352
441
  }
353
442
 
354
443
  export declare const PDFStore: {
@@ -364,6 +453,27 @@ export declare type PDFVirtualizer = Virtualizer<any, any>;
364
453
 
365
454
  export declare const PreviousPage: () => void;
366
455
 
456
+ /**
457
+ * Removes any recolor wrapper installed on the context. For long-lived
458
+ * contexts (the visible canvas in the no-buffer fallback, thumbnails) that
459
+ * are about to render in the light scheme: a still-pending dark render's
460
+ * deferred restore could otherwise leave its wrapper active across the
461
+ * scheme switch.
462
+ */
463
+ export declare function removeContextRecolor(ctx: CanvasRenderingContext2D): void;
464
+
465
+ /**
466
+ * Maps a color from the original document to its dark-scheme equivalent.
467
+ * Unparseable and fully-transparent colors are returned unchanged.
468
+ */
469
+ declare type RenderColorMap = (color: string) => string;
470
+ export { RenderColorMap }
471
+ export { RenderColorMap as RenderColorMap_alias_1 }
472
+
473
+ export declare interface RenderColorMapRef {
474
+ current: RenderColorMap | null;
475
+ }
476
+
367
477
  export declare const Root: ForwardRefExoticComponent<Omit<Omit<HTMLProps<HTMLDivElement>, "onError"> & usePDFDocumentParams & {
368
478
  loader?: ReactNode;
369
479
  }, "ref"> & RefAttributes<unknown>>;
@@ -462,7 +572,7 @@ declare const usePdf: <T>(selector: (state: PDFState) => T) => T;
462
572
  export { usePdf }
463
573
  export { usePdf as usePdf_alias_1 }
464
574
 
465
- export declare const usePDFDocumentContext: ({ onDocumentLoad, onError, source, initialRotation, isZoomFitWidth, zoom, zoomOptions, documentOptions, }: usePDFDocumentParams) => {
575
+ export declare const usePDFDocumentContext: ({ onDocumentLoad, onError, source, initialRotation, isZoomFitWidth, zoom, zoomOptions, documentOptions, colorScheme, darkModeColors, }: usePDFDocumentParams) => {
466
576
  initialState: InitialPDFState | null | undefined;
467
577
  };
468
578
 
@@ -501,6 +611,19 @@ export declare interface usePDFDocumentParams {
501
611
  * Must be a stable reference (module-level constant or useMemo) to avoid reloading the document.
502
612
  */
503
613
  documentOptions?: Partial<DocumentInitParameters>;
614
+ /**
615
+ * Initial color scheme for page rendering. "dark" recolors the document at
616
+ * render time (native dark mode): perceived lightness is flipped onto the
617
+ * darkModeColors ramp while hue is preserved, and images keep their
618
+ * original pixels. Changing the prop after mount updates the scheme; the
619
+ * runtime equivalent is `usePdf((s) => s.setColorScheme)`.
620
+ */
621
+ colorScheme?: ColorScheme;
622
+ /**
623
+ * Palette for the dark scheme: `background` replaces white paper,
624
+ * `foreground` replaces black text. Defaults to #141210 / #eae6e0.
625
+ */
626
+ darkModeColors?: DarkModeColors;
504
627
  }
505
628
 
506
629
  export declare const usePdfJump: () => {
package/dist/index.d.ts CHANGED
@@ -42,3 +42,8 @@ export { useSelectionDimensions } from './_tsup-dts-rollup.js';
42
42
  export { ColoredHighlight } from './_tsup-dts-rollup.js';
43
43
  export { HighlightRect } from './_tsup-dts-rollup.js';
44
44
  export { usePdf } from './_tsup-dts-rollup.js';
45
+ export { ColorScheme } from './_tsup-dts-rollup.js';
46
+ export { createDarkModeColorMap } from './_tsup-dts-rollup.js';
47
+ export { DarkModeColors } from './_tsup-dts-rollup.js';
48
+ export { DEFAULT_DARK_MODE_COLORS } from './_tsup-dts-rollup.js';
49
+ export { RenderColorMap } from './_tsup-dts-rollup.js';
package/dist/index.js CHANGED
@@ -15,6 +15,209 @@ var clamp = (value, minimum, maximum) => {
15
15
  return Math.min(Math.max(value, minimum), maximum);
16
16
  };
17
17
 
18
+ // src/lib/dark-mode.ts
19
+ var DEFAULT_DARK_MODE_COLORS = {
20
+ background: "#141210",
21
+ foreground: "#eae6e0"
22
+ };
23
+ var NAMED_COLORS = {
24
+ white: [1, 1, 1, 1],
25
+ black: [0, 0, 0, 1],
26
+ transparent: [0, 0, 0, 0]
27
+ };
28
+ function clamp01(value) {
29
+ return value < 0 ? 0 : value > 1 ? 1 : value;
30
+ }
31
+ function parseColor(input) {
32
+ const str = input.trim().toLowerCase();
33
+ const named = Object.hasOwn(NAMED_COLORS, str) ? NAMED_COLORS[str] : void 0;
34
+ if (named) return named;
35
+ if (str.startsWith("#")) {
36
+ const hex = str.slice(1);
37
+ if (!/^[0-9a-f]{3,8}$/.test(hex)) return null;
38
+ if (hex.length === 3 || hex.length === 4) {
39
+ const r2 = Number.parseInt(hex[0], 16) / 15;
40
+ const g = Number.parseInt(hex[1], 16) / 15;
41
+ const b = Number.parseInt(hex[2], 16) / 15;
42
+ const a = hex.length === 4 ? Number.parseInt(hex[3], 16) / 15 : 1;
43
+ return [r2, g, b, a];
44
+ }
45
+ if (hex.length === 6 || hex.length === 8) {
46
+ const r2 = Number.parseInt(hex.slice(0, 2), 16) / 255;
47
+ const g = Number.parseInt(hex.slice(2, 4), 16) / 255;
48
+ const b = Number.parseInt(hex.slice(4, 6), 16) / 255;
49
+ const a = hex.length === 8 ? Number.parseInt(hex.slice(6, 8), 16) / 255 : 1;
50
+ return [r2, g, b, a];
51
+ }
52
+ return null;
53
+ }
54
+ const fn = /^rgba?\(([^)]+)\)$/.exec(str);
55
+ if (fn) {
56
+ const parts = fn[1].split(/[,\s/]+/).filter(Boolean);
57
+ if (parts.length < 3) return null;
58
+ const channel = (part) => part.endsWith("%") ? Number.parseFloat(part) / 100 : Number.parseFloat(part) / 255;
59
+ const alpha = (part) => part.endsWith("%") ? Number.parseFloat(part) / 100 : Number.parseFloat(part);
60
+ const r2 = channel(parts[0]);
61
+ const g = channel(parts[1]);
62
+ const b = channel(parts[2]);
63
+ const a = parts[3] !== void 0 ? alpha(parts[3]) : 1;
64
+ if (Number.isNaN(r2) || Number.isNaN(g) || Number.isNaN(b) || Number.isNaN(a))
65
+ return null;
66
+ return [clamp01(r2), clamp01(g), clamp01(b), clamp01(a)];
67
+ }
68
+ const normalized = normalizeCssColor(str);
69
+ if (normalized !== null && normalized !== str) return parseColor(normalized);
70
+ return null;
71
+ }
72
+ var normalizeCtx;
73
+ function normalizeCssColor(input) {
74
+ if (normalizeCtx === void 0) {
75
+ normalizeCtx = typeof document === "undefined" ? null : document.createElement("canvas").getContext("2d", {
76
+ willReadFrequently: true
77
+ });
78
+ }
79
+ const ctx = normalizeCtx;
80
+ if (!ctx) return null;
81
+ ctx.fillStyle = "#000000";
82
+ ctx.fillStyle = input;
83
+ const first = ctx.fillStyle;
84
+ ctx.fillStyle = "#ffffff";
85
+ ctx.fillStyle = input;
86
+ return first === ctx.fillStyle ? first : null;
87
+ }
88
+ function srgbToLinear(c) {
89
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
90
+ }
91
+ function linearToSrgb(c) {
92
+ return c <= 31308e-7 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
93
+ }
94
+ function rgbToOklab(r2, g, b) {
95
+ const lr = srgbToLinear(r2);
96
+ const lg = srgbToLinear(g);
97
+ const lb = srgbToLinear(b);
98
+ const l = Math.cbrt(
99
+ 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb
100
+ );
101
+ const m = Math.cbrt(
102
+ 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb
103
+ );
104
+ const s = Math.cbrt(
105
+ 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb
106
+ );
107
+ return [
108
+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
109
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
110
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s
111
+ ];
112
+ }
113
+ function oklabToLinearRgb(L, a, b) {
114
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
115
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
116
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
117
+ return [
118
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
119
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
120
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s
121
+ ];
122
+ }
123
+ var GAMUT_EPSILON = 5e-4;
124
+ function oklabToSrgbExact(L, a, b) {
125
+ const [lr, lg, lb] = oklabToLinearRgb(L, a, b);
126
+ if (lr < -GAMUT_EPSILON || lr > 1 + GAMUT_EPSILON || lg < -GAMUT_EPSILON || lg > 1 + GAMUT_EPSILON || lb < -GAMUT_EPSILON || lb > 1 + GAMUT_EPSILON) {
127
+ return null;
128
+ }
129
+ return [
130
+ linearToSrgb(clamp01(lr)),
131
+ linearToSrgb(clamp01(lg)),
132
+ linearToSrgb(clamp01(lb))
133
+ ];
134
+ }
135
+ function oklabToSrgbGamutMapped(L, a, b) {
136
+ const exact = oklabToSrgbExact(L, a, b);
137
+ if (exact) return exact;
138
+ let lo = 0;
139
+ let hi = 1;
140
+ for (let i = 0; i < 12; i++) {
141
+ const mid = (lo + hi) / 2;
142
+ if (oklabToSrgbExact(L, a * mid, b * mid)) lo = mid;
143
+ else hi = mid;
144
+ }
145
+ const [lr, lg, lb] = oklabToLinearRgb(L, a * lo, b * lo);
146
+ return [
147
+ linearToSrgb(clamp01(lr)),
148
+ linearToSrgb(clamp01(lg)),
149
+ linearToSrgb(clamp01(lb))
150
+ ];
151
+ }
152
+ function toHexByte(channel) {
153
+ return Math.round(clamp01(channel) * 255).toString(16).padStart(2, "0");
154
+ }
155
+ function toCssColor(r2, g, b, a) {
156
+ const rgb = `#${toHexByte(r2)}${toHexByte(g)}${toHexByte(b)}`;
157
+ return a >= 1 ? rgb : `${rgb}${toHexByte(a)}`;
158
+ }
159
+ var NEUTRAL_CHROMA_THRESHOLD = 0.04;
160
+ var COLOR_CACHE_MAX = 4096;
161
+ var mapInstances = /* @__PURE__ */ new Map();
162
+ function createDarkModeColorMap(colors) {
163
+ const background = colors?.background ?? DEFAULT_DARK_MODE_COLORS.background;
164
+ const foreground = colors?.foreground ?? DEFAULT_DARK_MODE_COLORS.foreground;
165
+ const instanceKey = `${background}|${foreground}`;
166
+ const existing = mapInstances.get(instanceKey);
167
+ if (existing) {
168
+ mapInstances.delete(instanceKey);
169
+ mapInstances.set(instanceKey, existing);
170
+ return existing;
171
+ }
172
+ const bgRgba = parseColor(background) ?? parseColor(DEFAULT_DARK_MODE_COLORS.background);
173
+ const fgRgba = parseColor(foreground) ?? parseColor(DEFAULT_DARK_MODE_COLORS.foreground);
174
+ const bgLab = rgbToOklab(bgRgba[0], bgRgba[1], bgRgba[2]);
175
+ const fgLab = rgbToOklab(fgRgba[0], fgRgba[1], fgRgba[2]);
176
+ const cache = /* @__PURE__ */ new Map();
177
+ const backgroundCss = toCssColor(bgRgba[0], bgRgba[1], bgRgba[2], 1);
178
+ const foregroundCss = toCssColor(fgRgba[0], fgRgba[1], fgRgba[2], 1);
179
+ const seedPoles = () => {
180
+ for (const white of ["#ffffff", "#fff", "white"])
181
+ cache.set(white, backgroundCss);
182
+ for (const black of ["#000000", "#000", "black"])
183
+ cache.set(black, foregroundCss);
184
+ };
185
+ seedPoles();
186
+ const transform = (input) => {
187
+ const parsed = parseColor(input);
188
+ if (!parsed || parsed[3] === 0) return input;
189
+ const [r2, g, b, alpha] = parsed;
190
+ const [, labA, labB] = rgbToOklab(r2, g, b);
191
+ const luma = 0.2126 * r2 + 0.7152 * g + 0.0722 * b;
192
+ const rampL = fgLab[0] + (bgLab[0] - fgLab[0]) * luma;
193
+ const rampA = fgLab[1] + (bgLab[1] - fgLab[1]) * luma;
194
+ const rampB = fgLab[2] + (bgLab[2] - fgLab[2]) * luma;
195
+ const chroma = Math.hypot(labA, labB);
196
+ const hueWeight = Math.min(1, chroma / NEUTRAL_CHROMA_THRESHOLD);
197
+ const outA = rampA + (labA - rampA) * hueWeight;
198
+ const outB = rampB + (labB - rampB) * hueWeight;
199
+ const [sr, sg, sb] = oklabToSrgbGamutMapped(rampL, outA, outB);
200
+ return toCssColor(sr, sg, sb, alpha);
201
+ };
202
+ const map = (input) => {
203
+ const hit = cache.get(input);
204
+ if (hit !== void 0) return hit;
205
+ const out = transform(input);
206
+ if (cache.size >= COLOR_CACHE_MAX) {
207
+ cache.clear();
208
+ seedPoles();
209
+ }
210
+ cache.set(input, out);
211
+ return out;
212
+ };
213
+ if (mapInstances.size >= 16) {
214
+ const oldest = mapInstances.keys().next().value;
215
+ if (oldest !== void 0) mapInstances.delete(oldest);
216
+ }
217
+ mapInstances.set(instanceKey, map);
218
+ return map;
219
+ }
220
+
18
221
  // src/lib/zoom.ts
19
222
  var getFitWidthZoom = (containerWidth, viewports, zoomOptions) => {
20
223
  const { minZoom, maxZoom } = zoomOptions;
@@ -39,6 +242,15 @@ var createZustandContext = (getStore) => {
39
242
  // src/internal.ts
40
243
  var PDFStore = createZustandContext(
41
244
  (initialState) => {
245
+ const initialColorScheme = initialState.colorScheme ?? "light";
246
+ const initialDarkModeColors = {
247
+ ...DEFAULT_DARK_MODE_COLORS,
248
+ ...initialState.darkModeColors
249
+ };
250
+ const renderColorMapRef = initialState.renderColorMapRef ?? {
251
+ current: null
252
+ };
253
+ renderColorMapRef.current = initialColorScheme === "dark" ? createDarkModeColorMap(initialDarkModeColors) : null;
42
254
  return createStore((set, get) => ({
43
255
  pdfDocumentProxy: initialState.pdfDocumentProxy,
44
256
  zoom: initialState.zoom,
@@ -131,6 +343,21 @@ var PDFStore = createZustandContext(
131
343
  (rect) => rect.uuid !== uuid
132
344
  )
133
345
  })),
346
+ colorScheme: initialColorScheme,
347
+ darkModeColors: initialDarkModeColors,
348
+ renderColorMapRef,
349
+ setColorScheme: (colorScheme, colors) => {
350
+ const prev = get();
351
+ const darkModeColors = {
352
+ background: colors?.background ?? prev.darkModeColors.background,
353
+ foreground: colors?.foreground ?? prev.darkModeColors.foreground
354
+ };
355
+ if (prev.colorScheme === colorScheme && prev.darkModeColors.background === darkModeColors.background && prev.darkModeColors.foreground === darkModeColors.foreground) {
356
+ return;
357
+ }
358
+ prev.renderColorMapRef.current = colorScheme === "dark" ? createDarkModeColorMap(darkModeColors) : null;
359
+ set({ colorScheme, darkModeColors });
360
+ },
134
361
  renderedPages: {},
135
362
  markPageRendered: (pageNumber) => {
136
363
  const current = get().renderedPages;
@@ -1165,6 +1392,129 @@ function clampScaleForPage(targetScale, pageWidth, pageHeight) {
1165
1392
  );
1166
1393
  return Math.max(safeScale, 0);
1167
1394
  }
1395
+
1396
+ // src/lib/recolor-context.ts
1397
+ var RECOLOR_CLEANUP = Symbol("lectorRecolorCleanup");
1398
+ var RECOLOR_PAINTED = Symbol("lectorRecolorPainted");
1399
+ var FILL_METHODS = ["fill", "fillRect", "fillText"];
1400
+ var STROKE_METHODS = ["stroke", "strokeRect", "strokeText"];
1401
+ var GRADIENT_METHODS = [
1402
+ "createLinearGradient",
1403
+ "createRadialGradient"
1404
+ ];
1405
+ function ntscLuma(r2, g, b) {
1406
+ return 0.3 * r2 + 0.59 * g + 0.11 * b;
1407
+ }
1408
+ function parseHexLuma(color) {
1409
+ if (!/^#[0-9a-f]{6}$/i.test(color)) return null;
1410
+ return ntscLuma(
1411
+ Number.parseInt(color.slice(1, 3), 16),
1412
+ Number.parseInt(color.slice(3, 5), 16),
1413
+ Number.parseInt(color.slice(5, 7), 16)
1414
+ );
1415
+ }
1416
+ function correctLuminosityMask(source, mappedWhiteLuma, mappedBlackLuma) {
1417
+ if (typeof document === "undefined") return null;
1418
+ if (!(typeof HTMLCanvasElement !== "undefined" && source instanceof HTMLCanvasElement) && !(typeof OffscreenCanvas !== "undefined" && source instanceof OffscreenCanvas)) {
1419
+ return null;
1420
+ }
1421
+ const width = source.width;
1422
+ const height = source.height;
1423
+ if (!width || !height) return null;
1424
+ const span = mappedWhiteLuma - mappedBlackLuma;
1425
+ if (Math.abs(span) < 1) return null;
1426
+ const tmp = document.createElement("canvas");
1427
+ tmp.width = width;
1428
+ tmp.height = height;
1429
+ const tmpCtx = tmp.getContext("2d", { willReadFrequently: true });
1430
+ if (!tmpCtx) return null;
1431
+ tmpCtx.drawImage(source, 0, 0);
1432
+ let image;
1433
+ try {
1434
+ image = tmpCtx.getImageData(0, 0, width, height);
1435
+ } catch {
1436
+ return null;
1437
+ }
1438
+ const data = image.data;
1439
+ for (let i = 0; i < data.length; i += 4) {
1440
+ const luma = ntscLuma(data[i], data[i + 1], data[i + 2]);
1441
+ const t = (luma - mappedBlackLuma) / span;
1442
+ const gray = t <= 0 ? 0 : t >= 1 ? 255 : Math.round(t * 255);
1443
+ data[i] = data[i + 1] = data[i + 2] = gray;
1444
+ }
1445
+ tmpCtx.putImageData(image, 0, 0);
1446
+ return tmp;
1447
+ }
1448
+ function applyContextRecolor(ctx, map) {
1449
+ const target = ctx;
1450
+ target[RECOLOR_CLEANUP]?.();
1451
+ const mappedWhiteLuma = parseHexLuma(map("#ffffff"));
1452
+ const mappedBlackLuma = parseHexLuma(map("#000000"));
1453
+ const withMaskCorrection = (original) => function(...args) {
1454
+ if (mappedWhiteLuma !== null && mappedBlackLuma !== null && this.globalCompositeOperation === "destination-in" && typeof this.filter === "string" && this.filter.includes("luminosity")) {
1455
+ const source = args[0];
1456
+ const sourcePainted = (typeof HTMLCanvasElement !== "undefined" && source instanceof HTMLCanvasElement || typeof OffscreenCanvas !== "undefined" && source instanceof OffscreenCanvas) && source.getContext("2d")?.[RECOLOR_PAINTED] === true;
1457
+ const corrected = sourcePainted ? correctLuminosityMask(source, mappedWhiteLuma, mappedBlackLuma) : null;
1458
+ if (corrected) {
1459
+ const next = [corrected, ...args.slice(1)];
1460
+ return original.apply(this, next);
1461
+ }
1462
+ }
1463
+ return original.apply(this, args);
1464
+ };
1465
+ const withMappedStyle = (original, styleProp) => function(...args) {
1466
+ const style = this[styleProp];
1467
+ if (typeof style === "string") {
1468
+ const mapped = map(style);
1469
+ if (mapped !== style) {
1470
+ this[RECOLOR_PAINTED] = true;
1471
+ this[styleProp] = mapped;
1472
+ try {
1473
+ return original.apply(this, args);
1474
+ } finally {
1475
+ this[styleProp] = style;
1476
+ }
1477
+ }
1478
+ }
1479
+ return original.apply(this, args);
1480
+ };
1481
+ const withMappedStops = (original) => function(...args) {
1482
+ const gradient = original.apply(this, args);
1483
+ const addColorStop = gradient.addColorStop.bind(gradient);
1484
+ const context = this;
1485
+ gradient.addColorStop = (offset3, color) => {
1486
+ const mapped = map(color);
1487
+ if (mapped !== color) context[RECOLOR_PAINTED] = true;
1488
+ addColorStop(offset3, mapped);
1489
+ };
1490
+ return gradient;
1491
+ };
1492
+ const record = target;
1493
+ for (const name of FILL_METHODS)
1494
+ record[name] = withMappedStyle(target[name], "fillStyle");
1495
+ for (const name of STROKE_METHODS)
1496
+ record[name] = withMappedStyle(target[name], "strokeStyle");
1497
+ for (const name of GRADIENT_METHODS)
1498
+ record[name] = withMappedStops(target[name]);
1499
+ record.drawImage = withMaskCorrection(target.drawImage);
1500
+ const cleanup = () => {
1501
+ if (target[RECOLOR_CLEANUP] !== cleanup) return;
1502
+ for (const name of [
1503
+ ...FILL_METHODS,
1504
+ ...STROKE_METHODS,
1505
+ ...GRADIENT_METHODS,
1506
+ "drawImage"
1507
+ ])
1508
+ delete record[name];
1509
+ delete target[RECOLOR_CLEANUP];
1510
+ delete target[RECOLOR_PAINTED];
1511
+ };
1512
+ target[RECOLOR_CLEANUP] = cleanup;
1513
+ return cleanup;
1514
+ }
1515
+ function removeContextRecolor(ctx) {
1516
+ ctx[RECOLOR_CLEANUP]?.();
1517
+ }
1168
1518
  var useDpr = () => {
1169
1519
  const [dpr, setDPR] = useState(
1170
1520
  typeof window === "undefined" ? 1 : Math.min(window.devicePixelRatio, 2)
@@ -1208,16 +1558,16 @@ function clearBitmapCache(documentId) {
1208
1558
  cacheEntries.splice(i, 1);
1209
1559
  }
1210
1560
  }
1211
- function cacheKey(scale, background) {
1212
- const bg = background ?? "white";
1561
+ function cacheKey(scale, background, recolorKey) {
1562
+ const bg = `${background ?? "white"}|${recolorKey ?? ""}`;
1213
1563
  let hash = Math.round(scale * 1e4);
1214
1564
  for (let i = 0; i < bg.length; i++) {
1215
1565
  hash = hash * 31 + bg.charCodeAt(i) | 0;
1216
1566
  }
1217
1567
  return hash;
1218
1568
  }
1219
- function getCachedBitmap(proxy, scale, background) {
1220
- const key = cacheKey(scale, background);
1569
+ function getCachedBitmap(proxy, scale, background, recolorKey) {
1570
+ const key = cacheKey(scale, background, recolorKey);
1221
1571
  const bitmap = canvasBitmapCache.get(proxy)?.get(key);
1222
1572
  if (!bitmap) return null;
1223
1573
  const idx = cacheEntries.findIndex((e) => e.proxy === proxy && e.key === key);
@@ -1227,8 +1577,8 @@ function getCachedBitmap(proxy, scale, background) {
1227
1577
  }
1228
1578
  return bitmap;
1229
1579
  }
1230
- function setCachedBitmap(docId, proxy, scale, background, bitmap) {
1231
- const key = cacheKey(scale, background);
1580
+ function setCachedBitmap(docId, proxy, scale, background, recolorKey, bitmap) {
1581
+ const key = cacheKey(scale, background, recolorKey);
1232
1582
  let map = canvasBitmapCache.get(proxy);
1233
1583
  if (!map) {
1234
1584
  map = /* @__PURE__ */ new Map();
@@ -1255,8 +1605,9 @@ function setCachedBitmap(docId, proxy, scale, background, bitmap) {
1255
1605
  }
1256
1606
  var useCanvasLayer = ({ background }) => {
1257
1607
  const canvasRef = useRef(null);
1258
- const hasContentRef = useRef(false);
1608
+ const paintedKeyRef = useRef(null);
1259
1609
  const pageNumber = usePDFPageNumber();
1610
+ const store = PDFStore.useContext();
1260
1611
  const dpr = useDpr();
1261
1612
  const bouncyZoom = usePdf((state) => state.zoom);
1262
1613
  const isResizing = usePdf((state) => state.isResizing);
@@ -1264,6 +1615,10 @@ var useCanvasLayer = ({ background }) => {
1264
1615
  const pdfPageProxy = usePdf((state) => state.getPdfPageProxy(pageNumber));
1265
1616
  const markPageRendered = usePdf((state) => state.markPageRendered);
1266
1617
  const unmarkPageRendered = usePdf((state) => state.unmarkPageRendered);
1618
+ const colorScheme = usePdf((state) => state.colorScheme);
1619
+ const darkModeColors = usePdf((state) => state.darkModeColors);
1620
+ const recolor = colorScheme === "dark" ? createDarkModeColorMap(darkModeColors) : null;
1621
+ const recolorKey = recolor ? `dark:${darkModeColors.background},${darkModeColors.foreground}` : void 0;
1267
1622
  const [zoom] = useDebounce(bouncyZoom, 100);
1268
1623
  useLayoutEffect(() => {
1269
1624
  if (!canvasRef.current) return;
@@ -1271,13 +1626,14 @@ var useCanvasLayer = ({ background }) => {
1271
1626
  const baseViewport = pdfPageProxy.getViewport({ scale: 1 });
1272
1627
  const pageWidth = baseViewport.width;
1273
1628
  const pageHeight = baseViewport.height;
1274
- if (isResizing && hasContentRef.current) {
1629
+ const contentKey = `${background ?? "white"}|${recolorKey ?? ""}`;
1630
+ if (isResizing && paintedKeyRef.current === contentKey) {
1275
1631
  baseCanvas.style.visibility = "";
1276
1632
  baseCanvas.style.width = `${pageWidth}px`;
1277
1633
  baseCanvas.style.height = `${pageHeight}px`;
1278
1634
  return;
1279
1635
  }
1280
- hasContentRef.current = false;
1636
+ paintedKeyRef.current = null;
1281
1637
  const targetBaseScale = dpr * Math.min(zoom, 1);
1282
1638
  const baseScale = clampScaleForPage(targetBaseScale, pageWidth, pageHeight);
1283
1639
  baseCanvas.width = Math.floor(pageWidth * baseScale);
@@ -1290,15 +1646,20 @@ var useCanvasLayer = ({ background }) => {
1290
1646
  baseCanvas.style.transform = "translate(0px, 0px)";
1291
1647
  baseCanvas.style.zIndex = "0";
1292
1648
  baseCanvas.style.pointerEvents = "none";
1293
- baseCanvas.style.backgroundColor = background ?? "white";
1649
+ baseCanvas.style.backgroundColor = recolor ? recolor(background ?? "#ffffff") : background ?? "white";
1294
1650
  baseCanvas.style.visibility = "";
1295
1651
  const context = baseCanvas.getContext("2d");
1296
1652
  if (!context) return;
1297
- const cached = getCachedBitmap(pdfPageProxy, baseScale, background);
1653
+ const cached = getCachedBitmap(
1654
+ pdfPageProxy,
1655
+ baseScale,
1656
+ background,
1657
+ recolorKey
1658
+ );
1298
1659
  if (cached) {
1299
1660
  context.drawImage(cached, 0, 0);
1300
1661
  markPageRendered(pageNumber);
1301
- hasContentRef.current = true;
1662
+ paintedKeyRef.current = contentKey;
1302
1663
  return;
1303
1664
  }
1304
1665
  context.setTransform(1, 0, 0, 1, 0, 0);
@@ -1313,28 +1674,48 @@ var useCanvasLayer = ({ background }) => {
1313
1674
  const useBuffer = bufferCtx !== null;
1314
1675
  const renderCanvas = useBuffer ? buffer : baseCanvas;
1315
1676
  const renderCtx = bufferCtx ?? context;
1316
- const renderingTask = pdfPageProxy.render({
1317
- canvas: renderCanvas,
1318
- canvasContext: renderCtx,
1319
- viewport,
1320
- background
1321
- });
1677
+ let restoreRecolor = null;
1678
+ if (recolor) {
1679
+ restoreRecolor = applyContextRecolor(renderCtx, recolor);
1680
+ } else {
1681
+ removeContextRecolor(renderCtx);
1682
+ }
1683
+ let renderingTask;
1684
+ try {
1685
+ renderingTask = pdfPageProxy.render({
1686
+ canvas: renderCanvas,
1687
+ canvasContext: renderCtx,
1688
+ viewport,
1689
+ background
1690
+ });
1691
+ } catch (error) {
1692
+ restoreRecolor?.();
1693
+ throw error;
1694
+ }
1322
1695
  const releaseBuffer = () => {
1323
1696
  buffer.width = 0;
1324
1697
  buffer.height = 0;
1325
1698
  };
1326
- renderingTask.promise.then(() => {
1699
+ renderingTask.promise.finally(() => {
1700
+ restoreRecolor?.();
1701
+ }).then(() => {
1327
1702
  if (cancelled) {
1328
1703
  releaseBuffer();
1329
1704
  return;
1330
1705
  }
1706
+ const state = store.getState();
1707
+ const currentRecolorKey = state.colorScheme === "dark" ? `dark:${state.darkModeColors.background},${state.darkModeColors.foreground}` : void 0;
1708
+ if (currentRecolorKey !== recolorKey) {
1709
+ releaseBuffer();
1710
+ return;
1711
+ }
1331
1712
  if (useBuffer) {
1332
1713
  context.clearRect(0, 0, baseCanvas.width, baseCanvas.height);
1333
1714
  context.drawImage(buffer, 0, 0);
1334
1715
  }
1335
1716
  baseCanvas.style.visibility = "";
1336
1717
  markPageRendered(pageNumber);
1337
- hasContentRef.current = true;
1718
+ paintedKeyRef.current = contentKey;
1338
1719
  if (typeof createImageBitmap !== "undefined") {
1339
1720
  createImageBitmap(renderCanvas).then((bitmap) => {
1340
1721
  if (cancelled) {
@@ -1346,6 +1727,7 @@ var useCanvasLayer = ({ background }) => {
1346
1727
  pdfPageProxy,
1347
1728
  baseScale,
1348
1729
  background,
1730
+ recolorKey,
1349
1731
  bitmap
1350
1732
  );
1351
1733
  }).catch(() => {
@@ -1372,7 +1754,10 @@ var useCanvasLayer = ({ background }) => {
1372
1754
  isResizing,
1373
1755
  pageNumber,
1374
1756
  markPageRendered,
1375
- docId
1757
+ docId,
1758
+ recolor,
1759
+ recolorKey,
1760
+ store
1376
1761
  ]);
1377
1762
  useEffect(() => {
1378
1763
  const canvas = canvasRef.current;
@@ -1454,6 +1839,7 @@ var subscribeToViewportInvalidation = (viewport, callback) => {
1454
1839
 
1455
1840
  // src/hooks/layers/useDetailCanvasLayer.tsx
1456
1841
  var DETAIL_RENDER_IDLE_MS = 80;
1842
+ var ZOOM_SETTLE_MS = 250;
1457
1843
  var useDetailCanvasLayer = ({
1458
1844
  background,
1459
1845
  baseCanvasRef
@@ -1467,7 +1853,20 @@ var useDetailCanvasLayer = ({
1467
1853
  const isPinching = usePdf((state) => state.isPinching);
1468
1854
  const pdfPageProxy = usePdf((state) => state.getPdfPageProxy(pageNumber));
1469
1855
  const viewportRef = usePdf((state) => state.viewportRef);
1856
+ const colorScheme = usePdf((state) => state.colorScheme);
1857
+ const darkModeColors = usePdf((state) => state.darkModeColors);
1858
+ const recolor = colorScheme === "dark" ? createDarkModeColorMap(darkModeColors) : null;
1859
+ const recolorKey = recolor ? `dark:${darkModeColors.background},${darkModeColors.foreground}` : "light";
1860
+ const paintedKeyRef = useRef(null);
1470
1861
  const [zoom] = useDebounce(bouncyZoom, 200);
1862
+ const lastZoomChangeRef = useRef(
1863
+ store.getState().isPinching ? performance.now() : 0
1864
+ );
1865
+ const prevBouncyZoomRef = useRef(bouncyZoom);
1866
+ if (prevBouncyZoomRef.current !== bouncyZoom) {
1867
+ prevBouncyZoomRef.current = bouncyZoom;
1868
+ lastZoomChangeRef.current = performance.now();
1869
+ }
1471
1870
  const pageDimsRef = useRef(null);
1472
1871
  if (!pageDimsRef.current || pageDimsRef.current.proxy !== pdfPageProxy) {
1473
1872
  const vp = pdfPageProxy.getViewport({ scale: 1 });
@@ -1489,7 +1888,8 @@ var useDetailCanvasLayer = ({
1489
1888
  }
1490
1889
  let renderingTask = null;
1491
1890
  let renderTimeoutId = null;
1492
- const bgColor = background ?? "white";
1891
+ const bgColor = recolor ? recolor(background ?? "#ffffff") : background ?? "white";
1892
+ const contentKey = `${background ?? "white"}|${recolorKey}`;
1493
1893
  const detailBaseStyle = `position:absolute;top:0;left:0;pointer-events:none;z-index:1;background-color:${bgColor}`;
1494
1894
  const hideDetailCanvas = () => {
1495
1895
  renderingTask?.cancel();
@@ -1502,6 +1902,10 @@ var useDetailCanvasLayer = ({
1502
1902
  scheduleRender(160);
1503
1903
  return;
1504
1904
  }
1905
+ if (store.getState().isPinching || performance.now() - lastZoomChangeRef.current < ZOOM_SETTLE_MS) {
1906
+ scheduleRender(160);
1907
+ return;
1908
+ }
1505
1909
  const pageContainer = baseCanvasRef.current?.parentElement ?? null;
1506
1910
  if (!pageContainer) {
1507
1911
  hideDetailCanvas();
@@ -1569,6 +1973,7 @@ var useDetailCanvasLayer = ({
1569
1973
  const detailViewport = pdfPageProxy.getViewport({
1570
1974
  scale: effectiveScale
1571
1975
  });
1976
+ if (recolor) applyContextRecolor(bufferCtx, recolor);
1572
1977
  const currentRenderingTask = pdfPageProxy.render({
1573
1978
  canvas: buffer,
1574
1979
  canvasContext: bufferCtx,
@@ -1579,6 +1984,9 @@ var useDetailCanvasLayer = ({
1579
1984
  renderingTask = currentRenderingTask;
1580
1985
  currentRenderingTask.promise.then(() => {
1581
1986
  if (renderingTask !== currentRenderingTask) return;
1987
+ const state = store.getState();
1988
+ const currentRecolorKey = state.colorScheme === "dark" ? `dark:${state.darkModeColors.background},${state.darkModeColors.foreground}` : "light";
1989
+ if (currentRecolorKey !== recolorKey) return;
1582
1990
  detailCanvas.width = actualWidth;
1583
1991
  detailCanvas.height = actualHeight;
1584
1992
  detailCanvas.style.cssText = `${detailBaseStyle};display:block;opacity:1;width:${visibleWidth * zoom}px;height:${visibleHeight * zoom}px;transform-origin:center center;transform:translate(${visibleLeft * zoom}px,${visibleTop * zoom}px)`;
@@ -1587,6 +1995,7 @@ var useDetailCanvasLayer = ({
1587
1995
  if (ctx) {
1588
1996
  ctx.drawImage(buffer, 0, 0);
1589
1997
  }
1998
+ paintedKeyRef.current = contentKey;
1590
1999
  }).catch((error) => {
1591
2000
  if (error.name === "RenderingCancelledException") {
1592
2001
  return;
@@ -1617,6 +2026,10 @@ var useDetailCanvasLayer = ({
1617
2026
  if (zoom <= 1 || isPinching) {
1618
2027
  hideDetailCanvas();
1619
2028
  } else {
2029
+ if (paintedKeyRef.current !== null && paintedKeyRef.current !== contentKey) {
2030
+ hideDetailCanvas();
2031
+ paintedKeyRef.current = null;
2032
+ }
1620
2033
  scheduleRender(0);
1621
2034
  }
1622
2035
  return () => {
@@ -1634,7 +2047,9 @@ var useDetailCanvasLayer = ({
1634
2047
  dpr,
1635
2048
  viewportRef,
1636
2049
  baseCanvasRef,
1637
- store
2050
+ store,
2051
+ recolor,
2052
+ recolorKey
1638
2053
  ]);
1639
2054
  useEffect(() => {
1640
2055
  const canvas = detailCanvasRef.current;
@@ -2353,8 +2768,11 @@ var ColoredHighlightComponent = ({
2353
2768
  const deleteColoredHighlight = usePdf(
2354
2769
  (state) => state.deleteColoredHighlight
2355
2770
  );
2771
+ const colorScheme = usePdf((state) => state.colorScheme);
2772
+ const darkModeColors = usePdf((state) => state.darkModeColors);
2356
2773
  const [showButton, setShowButton] = useState(false);
2357
2774
  const pageNumber = usePDFPageNumber();
2775
+ const highlightColor = colorScheme === "dark" ? createDarkModeColorMap(darkModeColors)(selection.color) : selection.color;
2358
2776
  const pageRectangles = useMemo(
2359
2777
  () => selection.rectangles.filter((r2) => r2.pageNumber === pageNumber),
2360
2778
  [selection.rectangles, pageNumber]
@@ -2377,11 +2795,10 @@ var ColoredHighlightComponent = ({
2377
2795
  width: rect.width,
2378
2796
  cursor: "pointer",
2379
2797
  zIndex: 30,
2380
- backgroundColor: selection.color,
2381
- // mixBlendMode: "lighten", // changes the color of the text
2382
- mixBlendMode: "darken",
2383
- // best results
2384
- // mixBlendMode: "multiply", // works but coloring has some inconsistencies
2798
+ backgroundColor: highlightColor,
2799
+ // "darken" keeps dark text legible on a light page; on a dark
2800
+ // page the equivalent is "lighten" (keeps light text legible).
2801
+ mixBlendMode: colorScheme === "dark" ? "lighten" : "darken",
2385
2802
  borderRadius: "0.2rem"
2386
2803
  }
2387
2804
  },
@@ -2676,6 +3093,7 @@ var useTextLayer = () => {
2676
3093
  const pageNumber = usePDFPageNumber();
2677
3094
  const pdfPageProxy = usePdf((state) => state.getPdfPageProxy(pageNumber));
2678
3095
  const viewportRef = usePdf((state) => state.viewportRef);
3096
+ const store = PDFStore.useContext();
2679
3097
  useEffect(() => {
2680
3098
  const textContainer = textContainerRef.current;
2681
3099
  if (!textContainer) {
@@ -2780,11 +3198,22 @@ var useTextLayer = () => {
2780
3198
  const show = () => {
2781
3199
  textContainer.style.visibility = "";
2782
3200
  };
2783
- const onScroll = () => {
3201
+ const restoreWhenSettled = () => {
3202
+ settleTimer = null;
3203
+ if (store.getState().isPinching) {
3204
+ settleTimer = setTimeout(restoreWhenSettled, TEXT_SCROLL_SETTLE_MS);
3205
+ return;
3206
+ }
3207
+ show();
3208
+ };
3209
+ const hideAndDebounce = () => {
2784
3210
  if (selecting) return;
2785
3211
  textContainer.style.visibility = "hidden";
2786
3212
  if (settleTimer) clearTimeout(settleTimer);
2787
- settleTimer = setTimeout(show, TEXT_SCROLL_SETTLE_MS);
3213
+ settleTimer = setTimeout(restoreWhenSettled, TEXT_SCROLL_SETTLE_MS);
3214
+ };
3215
+ const onScroll = () => {
3216
+ hideAndDebounce();
2788
3217
  };
2789
3218
  const onPointerDown = () => {
2790
3219
  pointerDown = true;
@@ -2816,6 +3245,19 @@ var useTextLayer = () => {
2816
3245
  unsubscribe = subscribeToViewportInvalidation(scrollViewport, onScroll);
2817
3246
  };
2818
3247
  attachScrollSubscription();
3248
+ const initialState = store.getState();
3249
+ let prevZoom = initialState.zoom;
3250
+ let prevPinching = initialState.isPinching;
3251
+ if (prevPinching) hideAndDebounce();
3252
+ const unsubscribeStore = store.subscribe(
3253
+ (state) => {
3254
+ const zoomChanged = state.zoom !== prevZoom;
3255
+ const pinchStarted = state.isPinching && !prevPinching;
3256
+ prevZoom = state.zoom;
3257
+ prevPinching = state.isPinching;
3258
+ if (zoomChanged || pinchStarted) hideAndDebounce();
3259
+ }
3260
+ );
2819
3261
  document.addEventListener("pointerdown", onPointerDown, true);
2820
3262
  document.addEventListener("pointerup", clearPointer, true);
2821
3263
  document.addEventListener("pointercancel", clearPointer, true);
@@ -2824,6 +3266,7 @@ var useTextLayer = () => {
2824
3266
  return () => {
2825
3267
  if (attachRaf !== null) cancelAnimationFrame(attachRaf);
2826
3268
  unsubscribe?.();
3269
+ unsubscribeStore();
2827
3270
  document.removeEventListener("pointerdown", onPointerDown, true);
2828
3271
  document.removeEventListener("pointerup", clearPointer, true);
2829
3272
  document.removeEventListener("pointercancel", clearPointer, true);
@@ -2832,7 +3275,7 @@ var useTextLayer = () => {
2832
3275
  if (settleTimer) clearTimeout(settleTimer);
2833
3276
  show();
2834
3277
  };
2835
- }, [viewportRef]);
3278
+ }, [viewportRef, store]);
2836
3279
  return {
2837
3280
  textContainerRef,
2838
3281
  pageNumber: pdfPageProxy.pageNumber
@@ -3038,6 +3481,9 @@ var Page = memo(
3038
3481
  }) => {
3039
3482
  const pdfPageProxy = usePdf((state) => state.getPdfPageProxy(pageNumber));
3040
3483
  const viewport = usePdf((state) => state.viewports[pageNumber - 1]);
3484
+ const colorScheme = usePdf((state) => state.colorScheme);
3485
+ const darkModeColors = usePdf((state) => state.darkModeColors);
3486
+ const pageBackground = colorScheme === "dark" ? createDarkModeColorMap(darkModeColors)("#ffffff") : "white";
3041
3487
  const width = viewport?.width ?? (pdfPageProxy.view[2] ?? 0) - (pdfPageProxy.view[0] ?? 0);
3042
3488
  const height = viewport?.height ?? (pdfPageProxy.view[3] ?? 0) - (pdfPageProxy.view[1] ?? 0);
3043
3489
  return /* @__PURE__ */ jsx(PDFPageNumberContext.Provider, { value: pdfPageProxy.pageNumber, children: /* @__PURE__ */ jsx(
@@ -3052,7 +3498,7 @@ var Page = memo(
3052
3498
  style: {
3053
3499
  "--scale-factor": 1,
3054
3500
  "--total-scale-factor": 1,
3055
- backgroundColor: "white",
3501
+ backgroundColor: pageBackground,
3056
3502
  position: "relative",
3057
3503
  width,
3058
3504
  height,
@@ -5595,8 +6041,63 @@ var getDefaultPdfJsAssetUrls = (version) => {
5595
6041
  };
5596
6042
  };
5597
6043
 
6044
+ // src/lib/recolor-canvas-factory.ts
6045
+ function createRecolorCanvasFactory(mapRef) {
6046
+ return class RecolorCanvasFactory {
6047
+ #document;
6048
+ #enableHWA;
6049
+ constructor({
6050
+ ownerDocument = globalThis.document,
6051
+ enableHWA = false
6052
+ } = {}) {
6053
+ this.#document = ownerDocument;
6054
+ this.#enableHWA = enableHWA;
6055
+ }
6056
+ create(width, height) {
6057
+ if (width <= 0 || height <= 0) {
6058
+ throw new Error("Invalid canvas size");
6059
+ }
6060
+ const canvas = this.#document.createElement("canvas");
6061
+ canvas.width = width;
6062
+ canvas.height = height;
6063
+ const context = canvas.getContext("2d", {
6064
+ willReadFrequently: !this.#enableHWA
6065
+ });
6066
+ const map = mapRef.current;
6067
+ if (context && map) {
6068
+ applyContextRecolor(context, map);
6069
+ }
6070
+ return { canvas, context };
6071
+ }
6072
+ reset(canvasAndContext, width, height) {
6073
+ if (!canvasAndContext.canvas) {
6074
+ throw new Error("Canvas is not specified");
6075
+ }
6076
+ if (width <= 0 || height <= 0) {
6077
+ throw new Error("Invalid canvas size");
6078
+ }
6079
+ canvasAndContext.canvas.width = width;
6080
+ canvasAndContext.canvas.height = height;
6081
+ if (canvasAndContext.context) {
6082
+ const map = mapRef.current;
6083
+ if (map) applyContextRecolor(canvasAndContext.context, map);
6084
+ else removeContextRecolor(canvasAndContext.context);
6085
+ }
6086
+ }
6087
+ destroy(canvasAndContext) {
6088
+ if (!canvasAndContext.canvas) {
6089
+ throw new Error("Canvas is not specified");
6090
+ }
6091
+ canvasAndContext.canvas.width = 0;
6092
+ canvasAndContext.canvas.height = 0;
6093
+ canvasAndContext.canvas = null;
6094
+ canvasAndContext.context = null;
6095
+ }
6096
+ };
6097
+ }
6098
+
5598
6099
  // src/hooks/document/document.ts
5599
- function buildDocumentInitParams(source, pdfJsVersion, overrides) {
6100
+ function buildDocumentInitParams(source, pdfJsVersion, renderColorMapRef, overrides) {
5600
6101
  let params;
5601
6102
  if (typeof source === "string" || source instanceof URL) {
5602
6103
  params = { url: source };
@@ -5632,7 +6133,12 @@ function buildDocumentInitParams(source, pdfJsVersion, overrides) {
5632
6133
  cMapUrl: assetUrls.cMapUrl,
5633
6134
  cMapPacked: true,
5634
6135
  standardFontDataUrl: assetUrls.standardFontDataUrl,
5635
- iccUrl: assetUrls.iccUrl
6136
+ iccUrl: assetUrls.iccUrl,
6137
+ // Internal pdf.js scratch canvases (transparency groups, soft masks,
6138
+ // patterns) go through this factory so native dark mode can recolor
6139
+ // content that never touches the context passed to render(). A no-op
6140
+ // while the light scheme is active.
6141
+ CanvasFactory: createRecolorCanvasFactory(renderColorMapRef)
5636
6142
  };
5637
6143
  return { ...defaults, ...params, ...overrides };
5638
6144
  }
@@ -5644,15 +6150,24 @@ var usePDFDocumentContext = ({
5644
6150
  isZoomFitWidth,
5645
6151
  zoom = 1,
5646
6152
  zoomOptions,
5647
- documentOptions
6153
+ documentOptions,
6154
+ colorScheme,
6155
+ darkModeColors
5648
6156
  }) => {
5649
6157
  const [_, setProgress] = useState(0);
5650
6158
  const [initialState, setInitialState] = useState();
5651
6159
  const [rotation] = useState(initialRotation);
6160
+ const [renderColorMapRef] = useState(() => ({
6161
+ current: null
6162
+ }));
5652
6163
  const documentOptionsRef = useRef(documentOptions);
5653
6164
  documentOptionsRef.current = documentOptions;
5654
6165
  const onErrorRef = useRef(onError);
5655
6166
  onErrorRef.current = onError;
6167
+ const colorSchemeRef = useRef(colorScheme);
6168
+ colorSchemeRef.current = colorScheme;
6169
+ const darkModeColorsRef = useRef(darkModeColors);
6170
+ darkModeColorsRef.current = darkModeColors;
5656
6171
  useEffect(() => {
5657
6172
  const generateViewports = async (pdf) => {
5658
6173
  const pageProxies = [];
@@ -5680,7 +6195,10 @@ var usePDFDocumentContext = ({
5680
6195
  pageProxies: sortedPageProxies,
5681
6196
  pdfDocumentProxy: pdf,
5682
6197
  zoom,
5683
- zoomOptions
6198
+ zoomOptions,
6199
+ colorScheme: colorSchemeRef.current,
6200
+ darkModeColors: darkModeColorsRef.current,
6201
+ renderColorMapRef
5684
6202
  }));
5685
6203
  };
5686
6204
  const loadDocument = () => {
@@ -5696,6 +6214,7 @@ var usePDFDocumentContext = ({
5696
6214
  buildDocumentInitParams(
5697
6215
  source,
5698
6216
  version,
6217
+ renderColorMapRef,
5699
6218
  documentOptionsRef.current
5700
6219
  )
5701
6220
  );
@@ -5757,6 +6276,38 @@ var usePDFDocumentContext = ({
5757
6276
  initialState
5758
6277
  };
5759
6278
  };
6279
+ var ColorSchemeSync = ({
6280
+ colorScheme,
6281
+ darkModeColors
6282
+ }) => {
6283
+ const setColorScheme = usePdf((state) => state.setColorScheme);
6284
+ const storeColorScheme = usePdf((state) => state.colorScheme);
6285
+ const storeBackground = usePdf((state) => state.darkModeColors.background);
6286
+ const storeForeground = usePdf((state) => state.darkModeColors.foreground);
6287
+ const hasPalette = darkModeColors !== void 0;
6288
+ const background = darkModeColors?.background;
6289
+ const foreground = darkModeColors?.foreground;
6290
+ useEffect(() => {
6291
+ if (!colorScheme && !hasPalette) return;
6292
+ setColorScheme(
6293
+ colorScheme ?? storeColorScheme,
6294
+ hasPalette ? {
6295
+ background: background ?? DEFAULT_DARK_MODE_COLORS.background,
6296
+ foreground: foreground ?? DEFAULT_DARK_MODE_COLORS.foreground
6297
+ } : void 0
6298
+ );
6299
+ }, [
6300
+ colorScheme,
6301
+ storeColorScheme,
6302
+ storeBackground,
6303
+ storeForeground,
6304
+ hasPalette,
6305
+ background,
6306
+ foreground,
6307
+ setColorScheme
6308
+ ]);
6309
+ return null;
6310
+ };
5760
6311
  var Root = forwardRef(
5761
6312
  ({
5762
6313
  children,
@@ -5768,6 +6319,8 @@ var Root = forwardRef(
5768
6319
  zoom,
5769
6320
  zoomOptions,
5770
6321
  documentOptions,
6322
+ colorScheme,
6323
+ darkModeColors,
5771
6324
  ...props
5772
6325
  }, ref) => {
5773
6326
  const { initialState } = usePDFDocumentContext({
@@ -5777,7 +6330,9 @@ var Root = forwardRef(
5777
6330
  isZoomFitWidth,
5778
6331
  zoom,
5779
6332
  zoomOptions,
5780
- documentOptions
6333
+ documentOptions,
6334
+ colorScheme,
6335
+ darkModeColors
5781
6336
  });
5782
6337
  const linkService = useCreatePDFLinkService(
5783
6338
  initialState?.pdfDocumentProxy ?? null
@@ -5789,7 +6344,16 @@ var Root = forwardRef(
5789
6344
  clearBitmapCache(documentId);
5790
6345
  };
5791
6346
  }, [documentId]);
5792
- return /* @__PURE__ */ jsx(Primitive.div, { ref, ...props, children: initialState ? /* @__PURE__ */ jsx(PDFStore.Provider, { initialValue: initialState, children: /* @__PURE__ */ jsx(PDFLinkServiceContext.Provider, { value: linkService, children }) }) : loader ?? "Loading..." });
6347
+ return /* @__PURE__ */ jsx(Primitive.div, { ref, ...props, children: initialState ? /* @__PURE__ */ jsxs(PDFStore.Provider, { initialValue: initialState, children: [
6348
+ /* @__PURE__ */ jsx(
6349
+ ColorSchemeSync,
6350
+ {
6351
+ colorScheme,
6352
+ darkModeColors
6353
+ }
6354
+ ),
6355
+ /* @__PURE__ */ jsx(PDFLinkServiceContext.Provider, { value: linkService, children })
6356
+ ] }) : loader ?? "Loading..." });
5793
6357
  }
5794
6358
  );
5795
6359
  Root.displayName = "Root";
@@ -5836,6 +6400,9 @@ var useThumbnail = (pageNumber, config = {}) => {
5836
6400
  const { visible } = useVisibility({ elementRef: containerRef });
5837
6401
  const [debouncedVisible] = useDebounce(visible, 50);
5838
6402
  const dpr = useDpr();
6403
+ const colorScheme = usePdf((state) => state.colorScheme);
6404
+ const darkModeColors = usePdf((state) => state.darkModeColors);
6405
+ const recolor = colorScheme === "dark" ? createDarkModeColorMap(darkModeColors) : null;
5839
6406
  const isVisible = isFirstPage || debouncedVisible;
5840
6407
  useEffect(() => {
5841
6408
  const renderThumbnail = async () => {
@@ -5852,13 +6419,23 @@ var useThumbnail = (pageNumber, config = {}) => {
5852
6419
  canvas2.height = scaledViewport.height;
5853
6420
  const context = canvas2.getContext("2d");
5854
6421
  if (!context) return;
5855
- const renderTask = pageProxy.render({
5856
- canvas: canvas2,
5857
- canvasContext: context,
5858
- viewport: scaledViewport
5859
- });
5860
- renderTaskRef.current = renderTask;
5861
- await renderTask.promise;
6422
+ let restoreRecolor = null;
6423
+ if (recolor) {
6424
+ restoreRecolor = applyContextRecolor(context, recolor);
6425
+ } else {
6426
+ removeContextRecolor(context);
6427
+ }
6428
+ try {
6429
+ const renderTask = pageProxy.render({
6430
+ canvas: canvas2,
6431
+ canvasContext: context,
6432
+ viewport: scaledViewport
6433
+ });
6434
+ renderTaskRef.current = renderTask;
6435
+ await renderTask.promise;
6436
+ } finally {
6437
+ restoreRecolor?.();
6438
+ }
5862
6439
  } catch (error) {
5863
6440
  if (error instanceof Error && error.name === "RenderingCancelledException") {
5864
6441
  console.log("Rendering cancelled");
@@ -5876,7 +6453,7 @@ var useThumbnail = (pageNumber, config = {}) => {
5876
6453
  canvas.height = 1;
5877
6454
  }
5878
6455
  };
5879
- }, [pageProxy, isVisible, dpr, maxHeight, maxWidth]);
6456
+ }, [pageProxy, isVisible, dpr, maxHeight, maxWidth, recolor]);
5880
6457
  return {
5881
6458
  canvasRef,
5882
6459
  containerRef,
@@ -6212,4 +6789,4 @@ function mergeAdjacentRects(rects) {
6212
6789
  // src/hooks/usePageRendered.ts
6213
6790
  var usePageRendered = (pageNumber) => usePdf((state) => !!state.renderedPages[pageNumber]);
6214
6791
 
6215
- export { AnnotationHighlightLayer, AnnotationLayer, AnnotationTooltip, AnnotationsStoreProvider, CanvasLayer, ColoredHighlightLayer, CurrentPage, CurrentZoom, CustomLayer, HighlightLayer, LinkService, NextPage, Outline, OutlineChildItems, OutlineItem, PDFLinkServiceContext, Page, Pages, PreviousPage, Root, Search, SelectionTooltip, TextLayer, Thumbnail, Thumbnails, TotalPages, ZoomIn, ZoomOut, calculateHighlightRects, useAnnotations, useCreatePDFLinkService, usePDFLinkService, usePDFPageNumber, usePageRendered, usePdf, usePdfJump, useSearch, useSelectionDimensions };
6792
+ export { AnnotationHighlightLayer, AnnotationLayer, AnnotationTooltip, AnnotationsStoreProvider, CanvasLayer, ColoredHighlightLayer, CurrentPage, CurrentZoom, CustomLayer, DEFAULT_DARK_MODE_COLORS, HighlightLayer, LinkService, NextPage, Outline, OutlineChildItems, OutlineItem, PDFLinkServiceContext, Page, Pages, PreviousPage, Root, Search, SelectionTooltip, TextLayer, Thumbnail, Thumbnails, TotalPages, ZoomIn, ZoomOut, calculateHighlightRects, createDarkModeColorMap, useAnnotations, useCreatePDFLinkService, usePDFLinkService, usePDFPageNumber, usePageRendered, usePdf, usePdfJump, useSearch, useSelectionDimensions };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anaralabs/lector",
3
- "version": "3.12.9",
3
+ "version": "3.13.1",
4
4
  "description": "A headless PDF viewer for React",
5
5
  "author": "andrewdr (https://github.com/andrewdoro)",
6
6
  "license": "MIT",