@cosmicdrift/kumiko-renderer 0.406.0 → 0.409.0

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.
Files changed (143) hide show
  1. package/dist/app/action-form-body.js +23 -8
  2. package/dist/app/action-form-support.d.ts +7 -0
  3. package/dist/app/action-form-support.js +14 -1
  4. package/dist/app/config-edit-action-row.d.ts +7 -0
  5. package/dist/app/config-edit-action-row.js +45 -0
  6. package/dist/app/config-edit-body.js +32 -4
  7. package/dist/app/entity-list-screen.js +8 -11
  8. package/dist/app/nav.js +2 -1
  9. package/dist/app/projection-detail-body.js +3 -1
  10. package/dist/app/projection-detail-header.d.ts +1 -0
  11. package/dist/app/projection-detail-header.js +1 -1
  12. package/dist/app/projection-detail-navigation.d.ts +2 -1
  13. package/dist/app/projection-detail-navigation.js +6 -3
  14. package/dist/app/projection-detail-shim.js +3 -1
  15. package/dist/app/projection-list-render-props.d.ts +1 -1
  16. package/dist/app/projection-list-render-props.js +4 -2
  17. package/dist/app/projection-list-render.js +1 -1
  18. package/dist/app/screen-access.js +4 -2
  19. package/dist/app/screen-shared.d.ts +3 -2
  20. package/dist/app/screen-shared.js +29 -1
  21. package/dist/app/use-embedded-screen.d.ts +2 -0
  22. package/dist/app/use-embedded-screen.js +7 -1
  23. package/dist/components/edit-mounts.d.ts +3 -1
  24. package/dist/components/edit-mounts.js +3 -3
  25. package/dist/components/related-list-section.d.ts +3 -1
  26. package/dist/components/related-list-section.js +2 -2
  27. package/dist/components/render-edit-field-grid.d.ts +2 -2
  28. package/dist/components/render-edit-field-grid.js +12 -4
  29. package/dist/components/render-edit-fields-section.js +6 -7
  30. package/dist/components/render-edit-helpers.d.ts +4 -0
  31. package/dist/components/render-edit-helpers.js +5 -0
  32. package/dist/components/render-edit-section-kinds.js +6 -4
  33. package/dist/components/render-edit-submit.js +18 -1
  34. package/dist/components/render-edit-titles.js +6 -6
  35. package/dist/components/render-edit-types.d.ts +6 -0
  36. package/dist/components/render-field-control.d.ts +2 -0
  37. package/dist/components/render-field-control.js +23 -1
  38. package/dist/components/render-field-write-only.d.ts +1 -1
  39. package/dist/components/render-field-write-only.js +12 -2
  40. package/dist/components/render-field.js +2 -1
  41. package/dist/components/use-render-edit-sections.js +4 -4
  42. package/dist/format-when.d.ts +1 -1
  43. package/dist/format-when.js +2 -2
  44. package/dist/headless/format/escape.js +3 -2
  45. package/dist/headless/view-model/edit.js +0 -2
  46. package/dist/headless/view-model/types.d.ts +0 -3
  47. package/dist/i18n-defaults.js +38 -0
  48. package/dist/index.d.ts +2 -1
  49. package/dist/index.js +1 -0
  50. package/dist/primitives.d.ts +30 -7
  51. package/dist/primitives.js +1 -51
  52. package/dist/status-tone.d.ts +6 -0
  53. package/dist/status-tone.js +51 -0
  54. package/dist/toggle-set-member.d.ts +1 -0
  55. package/dist/toggle-set-member.js +8 -0
  56. package/dist/web/app/dashboard-header.js +5 -1
  57. package/dist/web/app/dashboard-screen-tiles.js +19 -3
  58. package/dist/web/icons.d.ts +2 -0
  59. package/dist/web/icons.js +3 -1
  60. package/dist/web/index.d.ts +3 -2
  61. package/dist/web/index.js +2 -1
  62. package/dist/web/layout/default-app-shell.d.ts +4 -1
  63. package/dist/web/layout/default-app-shell.js +5 -2
  64. package/dist/web/layout/focus-aware-sidebar.d.ts +27 -0
  65. package/dist/web/layout/focus-aware-sidebar.js +23 -0
  66. package/dist/web/layout/focus-rail.d.ts +16 -0
  67. package/dist/web/layout/focus-rail.js +61 -0
  68. package/dist/web/layout/nav-tree.d.ts +2 -1
  69. package/dist/web/layout/nav-tree.js +3 -9
  70. package/dist/web/layout/shell-focus.d.ts +19 -0
  71. package/dist/web/layout/shell-focus.js +35 -0
  72. package/dist/web/layout/shell-header.d.ts +1 -1
  73. package/dist/web/layout/shell-header.js +12 -9
  74. package/dist/web/layout/sidebar-brand.js +1 -1
  75. package/dist/web/layout/workspace-shell.d.ts +4 -1
  76. package/dist/web/layout/workspace-shell.js +5 -2
  77. package/dist/web/primitives/banner.js +3 -1
  78. package/dist/web/primitives/data-table/toolbar.js +2 -2
  79. package/dist/web/primitives/default-form.js +12 -5
  80. package/dist/web/primitives/field.js +4 -1
  81. package/dist/web/primitives/input-text-kinds.js +8 -2
  82. package/dist/web/primitives/layout-elements.js +2 -4
  83. package/dist/web/primitives/tabs.d.ts +1 -1
  84. package/dist/web/primitives/tabs.js +21 -4
  85. package/dist/web/theme-plugin.d.ts +1 -1
  86. package/dist/web/theme-plugin.js +7 -0
  87. package/dist/web/ui/sidebar.js +5 -2
  88. package/dist/web/widgets/ai-text-end-action.d.ts +12 -0
  89. package/dist/web/widgets/ai-text-end-action.js +15 -0
  90. package/dist/web/widgets/ai-text-field.d.ts +3 -0
  91. package/dist/web/widgets/ai-text-field.js +4 -3
  92. package/dist/web/widgets/attachment-card.d.ts +6 -0
  93. package/dist/web/widgets/attachment-card.js +11 -0
  94. package/dist/web/widgets/attachment-chip.d.ts +8 -0
  95. package/dist/web/widgets/attachment-chip.js +21 -0
  96. package/dist/web/widgets/clamped-text.d.ts +11 -0
  97. package/dist/web/widgets/clamped-text.js +38 -0
  98. package/dist/web/widgets/html-mail-frame.d.ts +17 -0
  99. package/dist/web/widgets/html-mail-frame.js +56 -0
  100. package/dist/web/widgets/index.d.ts +10 -1
  101. package/dist/web/widgets/index.js +9 -1
  102. package/dist/web/widgets/infinity-list.d.ts +3 -1
  103. package/dist/web/widgets/infinity-list.js +2 -2
  104. package/dist/web/widgets/message-body-view.d.ts +10 -0
  105. package/dist/web/widgets/message-body-view.js +36 -0
  106. package/dist/web/widgets/message-reader.d.ts +4 -0
  107. package/dist/web/widgets/message-reader.js +31 -0
  108. package/dist/web/widgets/message-thread.d.ts +5 -0
  109. package/dist/web/widgets/message-thread.js +66 -0
  110. package/dist/web/widgets/message-types.d.ts +68 -0
  111. package/dist/web/widgets/message-types.js +1 -0
  112. package/dist/web/widgets/mobile-top-bar.d.ts +21 -0
  113. package/dist/web/widgets/mobile-top-bar.js +8 -0
  114. package/dist/web/widgets/pdf-document.d.ts +19 -0
  115. package/dist/web/widgets/pdf-document.js +70 -0
  116. package/dist/web/widgets/pdf-page.d.ts +35 -0
  117. package/dist/web/widgets/pdf-page.js +155 -0
  118. package/dist/web/widgets/pdf-preview.d.ts +27 -7
  119. package/dist/web/widgets/pdf-preview.js +21 -133
  120. package/dist/web/widgets/pdf-search.d.ts +43 -0
  121. package/dist/web/widgets/pdf-search.js +178 -0
  122. package/dist/web/widgets/pdf-thumbnails.d.ts +10 -0
  123. package/dist/web/widgets/pdf-thumbnails.js +35 -0
  124. package/dist/web/widgets/pdf-viewer-toolbar.d.ts +22 -0
  125. package/dist/web/widgets/pdf-viewer-toolbar.js +35 -0
  126. package/dist/web/widgets/pdf-viewer.d.ts +21 -0
  127. package/dist/web/widgets/pdf-viewer.js +176 -0
  128. package/dist/web/widgets/quoted-text.d.ts +16 -0
  129. package/dist/web/widgets/quoted-text.js +76 -0
  130. package/dist/web/widgets/status-badge.js +3 -1
  131. package/dist/web/widgets/step-list-fit.d.ts +25 -0
  132. package/dist/web/widgets/step-list-fit.js +79 -0
  133. package/dist/web/widgets/step-list-row.d.ts +50 -0
  134. package/dist/web/widgets/step-list-row.js +97 -0
  135. package/dist/web/widgets/step-list.d.ts +33 -0
  136. package/dist/web/widgets/step-list.js +36 -0
  137. package/dist/web/widgets/surfaces.d.ts +23 -0
  138. package/dist/web/widgets/surfaces.js +15 -0
  139. package/dist/web/widgets/use-in-view.d.ts +5 -0
  140. package/dist/web/widgets/use-in-view.js +18 -0
  141. package/package.json +5 -5
  142. package/src/changes.json +186 -0
  143. package/src/web/styles.css +22 -0
@@ -0,0 +1,155 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Suspense, use, useCallback, useEffect, useMemo, useRef, useState, } from "react";
3
+ import { useTranslation } from "../../i18n.js";
4
+ import { cn } from "../lib/cn.js";
5
+ import { pageFor } from "./pdf-document.js";
6
+ import { ACTIVE_HIT_CLASS, markTextLayer } from "./pdf-search.js";
7
+ import { useSeenInViewport } from "./use-in-view.js";
8
+ export const RENDER_SCALE = 96 / 72;
9
+ /** Natural size of page 1; unrendered placeholders and thumbnails use its aspect ratio. */
10
+ export function useFirstPageSize(document) {
11
+ const firstPage = use(pageFor(document, 1));
12
+ return useMemo(() => {
13
+ const { width, height } = firstPage.getViewport({ scale: 1 });
14
+ return { width, height };
15
+ }, [firstPage]);
16
+ }
17
+ // Fit only shrinks; a zoom above 100% is meant to overflow and scroll.
18
+ export function fitScaleFor(availableWidth, contentWidth, zoom, height) {
19
+ if (zoom > 1 || availableWidth === null || availableWidth <= 0)
20
+ return 1;
21
+ const widthScale = availableWidth / contentWidth;
22
+ const heightScale = height?.available !== undefined && height.available > 0 ? height.available / height.content : 1;
23
+ return Math.min(1, widthScale, heightScale);
24
+ }
25
+ function PageSheet({ document, pageNumber, availableWidth, layout, }) {
26
+ const page = use(pageFor(document, pageNumber));
27
+ // Stable identity: the mount callbacks below depend on it, and a new viewport per render re-mounts canvas and text layer.
28
+ const viewport = useMemo(() => page.getViewport({ scale: RENDER_SCALE * layout.zoom }), [page, layout.zoom]);
29
+ const fitScale = fitScaleFor(availableWidth, viewport.width, layout.zoom, {
30
+ available: layout.fitHeight,
31
+ content: viewport.height,
32
+ });
33
+ const textLayerRef = useRef(null);
34
+ const [textLayerReady, setTextLayerReady] = useState(false);
35
+ // The sheet keeps its natural pixel size and is scaled as a whole, so canvas and text layer stay aligned.
36
+ const mountCanvas = useCallback((canvas) => {
37
+ if (canvas === null)
38
+ return;
39
+ const pixelRatio = globalThis.devicePixelRatio || 1;
40
+ canvas.width = Math.floor(viewport.width * pixelRatio);
41
+ canvas.height = Math.floor(viewport.height * pixelRatio);
42
+ const task = page.render({
43
+ canvas,
44
+ viewport,
45
+ transform: pixelRatio === 1 ? undefined : [pixelRatio, 0, 0, pixelRatio, 0, 0],
46
+ });
47
+ task.promise.catch(() => undefined);
48
+ return () => task.cancel();
49
+ }, [page, viewport]);
50
+ const mountTextLayer = useCallback((container) => {
51
+ textLayerRef.current = container;
52
+ if (container === null)
53
+ return;
54
+ const scale = RENDER_SCALE * layout.zoom;
55
+ container.style.setProperty("--total-scale-factor", String(scale));
56
+ container.style.setProperty("--scale-factor", String(scale));
57
+ let layer = null;
58
+ let cancelled = false;
59
+ setTextLayerReady(false);
60
+ void import("pdfjs-dist").then(({ TextLayer }) => {
61
+ // skip: cleanup ran before pdfjs finished loading
62
+ if (cancelled)
63
+ return undefined;
64
+ // TextLayer.cancel() keeps rendered spans; a re-mount must not append a second layer.
65
+ container.replaceChildren();
66
+ const textLayer = new TextLayer({
67
+ textContentSource: page.streamTextContent(),
68
+ container,
69
+ viewport,
70
+ });
71
+ layer = textLayer;
72
+ return textLayer
73
+ .render()
74
+ .then(() => {
75
+ if (!cancelled)
76
+ setTextLayerReady(true);
77
+ })
78
+ .catch(() => undefined);
79
+ });
80
+ return () => {
81
+ cancelled = true;
82
+ layer?.cancel();
83
+ };
84
+ }, [page, viewport, layout.zoom]);
85
+ const highlightTerm = layout.highlight?.term ?? "";
86
+ const activeOrdinal = layout.highlight?.activeOrdinal ?? null;
87
+ const anchorTop = activeOrdinal === null && layout.anchorTop === true;
88
+ const sheetRef = useRef(null);
89
+ useEffect(() => {
90
+ const container = textLayerRef.current;
91
+ if (container === null || !textLayerReady)
92
+ return;
93
+ markTextLayer(container, highlightTerm, activeOrdinal);
94
+ // The page top first, so the hit reads in its page; then the hit itself, which can sit below the fold.
95
+ // Runs after render because pages above it change height once rendered.
96
+ if (activeOrdinal !== null) {
97
+ sheetRef.current?.scrollIntoView({ block: "start" });
98
+ container.querySelector(`.${ACTIVE_HIT_CLASS}`)?.scrollIntoView({ block: "nearest" });
99
+ }
100
+ else if (anchorTop) {
101
+ sheetRef.current?.scrollIntoView({ block: "start" });
102
+ }
103
+ }, [highlightTerm, activeOrdinal, anchorTop, textLayerReady]);
104
+ return (_jsx("div", { ref: sheetRef, className: "mx-auto", style: { width: viewport.width * fitScale, height: viewport.height * fitScale }, children: _jsxs("div", { className: cn("relative bg-white", layout.variant === "viewer"
105
+ ? "rounded-sheet shadow-sheet"
106
+ : "border border-border shadow-md"), style: {
107
+ width: viewport.width,
108
+ height: viewport.height,
109
+ transform: `scale(${fitScale})`,
110
+ transformOrigin: "top left",
111
+ }, children: [_jsx("canvas", { ref: mountCanvas, style: { width: viewport.width, height: viewport.height }, className: "block" }), _jsx("div", { ref: mountTextLayer, className: cn(
112
+ // pdf.js's own text-layer stylesheet is not loaded, so size, horizontal fit and rotation come from the per-span custom properties here; without them glyph positions follow the host app's font and inherited font-size.
113
+ "absolute inset-0 overflow-hidden leading-none tracking-normal [&_span]:absolute [&_span]:origin-top-left [&_span]:cursor-text [&_span]:whitespace-pre [&_span]:text-transparent [&_span]:[font-size:calc(var(--total-scale-factor)*var(--font-height))] [&_span]:[transform:rotate(var(--rotate,0deg))_scaleX(var(--scale-x,1))] [&_span::selection]:bg-primary/30",
114
+ // The sheet is always white, so the marker colors are theme-independent; multiply keeps the canvas glyphs readable. Marks stay unpainted (no padding: it would shift the text behind them); the bands carry the color.
115
+ "[&_mark]:bg-transparent [&_mark]:text-transparent [&_.pdf-hit-band]:rounded-[2px] [&_.pdf-hit-band]:mix-blend-multiply [&_.pdf-hit-band-active]:bg-search-hit-active", layout.highlight?.source === true
116
+ ? "[&_.pdf-hit-band:not(.pdf-hit-band-active)]:bg-source-mark"
117
+ : "[&_.pdf-hit-band:not(.pdf-hit-band-active)]:bg-search-hit") })] }) }));
118
+ }
119
+ /** One page: a sized placeholder until it nears the viewport, then the rendered sheet. */
120
+ export function PdfPageSlot({ document, pageNumber, firstPageSize, layout, }) {
121
+ const t = useTranslation();
122
+ const { seen, observe } = useSeenInViewport();
123
+ const [availableWidth, setAvailableWidth] = useState(null);
124
+ const slotRef = useRef(null);
125
+ const anchorTop = layout.anchorTop === true && layout.highlight?.activeOrdinal == null;
126
+ // A jump on mount lands on placeholders that only shrink to the pane width once it is measured; re-anchor then.
127
+ useEffect(() => {
128
+ if (anchorTop && availableWidth !== null)
129
+ slotRef.current?.scrollIntoView({ block: "start" });
130
+ }, [anchorTop, availableWidth]);
131
+ const mountFrame = useCallback((frame) => {
132
+ if (frame === null)
133
+ return undefined;
134
+ const resizeObserver = new ResizeObserver(() => setAvailableWidth(frame.clientWidth));
135
+ resizeObserver.observe(frame);
136
+ setAvailableWidth(frame.clientWidth);
137
+ const stopObservingView = observe(frame);
138
+ return () => {
139
+ resizeObserver.disconnect();
140
+ stopObservingView?.();
141
+ };
142
+ }, [observe]);
143
+ const scale = RENDER_SCALE * layout.zoom;
144
+ const placeholderWidth = firstPageSize.width * scale;
145
+ const placeholderHeight = firstPageSize.height * scale;
146
+ const placeholderFit = fitScaleFor(availableWidth, placeholderWidth, layout.zoom, {
147
+ available: layout.fitHeight,
148
+ content: placeholderHeight,
149
+ });
150
+ const placeholder = (_jsx("div", { className: "mx-auto", style: {
151
+ width: placeholderWidth * placeholderFit,
152
+ height: placeholderHeight * placeholderFit,
153
+ } }));
154
+ return (_jsxs("figure", { ref: slotRef, "data-pdf-page": pageNumber, "data-testid": `pdf-page-${pageNumber}`, className: cn("m-0 flex w-full flex-col items-center gap-2", layout.variant === "stacked" && "rounded-lg bg-muted p-4"), children: [_jsx("div", { ref: mountFrame, className: "w-full", children: seen ? (_jsx(Suspense, { fallback: placeholder, children: _jsx(PageSheet, { document: document, pageNumber: pageNumber, availableWidth: availableWidth, layout: layout }) })) : (placeholder) }), layout.variant === "stacked" && (_jsx("figcaption", { className: "text-xs text-muted-foreground", children: t("kumiko.widget.pdf-preview.pageOf", { page: pageNumber, pages: document.numPages }) }))] }));
155
+ }
@@ -1,10 +1,30 @@
1
1
  import { type ReactNode } from "react";
2
- export type PdfPreviewSource = {
3
- readonly base64: string;
4
- } | {
5
- readonly url: string;
6
- };
7
- export declare function PdfPreview({ source, testId, }: {
2
+ import { type PdfPreviewSource } from "./pdf-document.ts";
3
+ import type { PdfMatchInfo } from "./pdf-search.ts";
4
+ export type { PdfPreviewSource } from "./pdf-document.ts";
5
+ export type { PdfMatchInfo } from "./pdf-search.ts";
6
+ export type PdfPreviewProps = {
8
7
  readonly source: PdfPreviewSource;
9
8
  readonly testId?: string;
10
- }): ReactNode;
9
+ /** "stacked" = all pages under each other. "viewer" = thumbnail rail, page jump, zoom, search. */
10
+ readonly variant?: "stacked" | "viewer";
11
+ /** Highlights matches in the text layer; the viewer opens on the first hit and shows "Treffer n von m". */
12
+ readonly searchTerm?: string;
13
+ /** 1-based page to open on. */
14
+ readonly initialPage?: number;
15
+ readonly onPageChange?: (page: number) => void;
16
+ /** Viewer only: 0-based active match, controlled by the host (e.g. its own "Treffer 1 von 3" stepper). */
17
+ readonly matchIndex?: number;
18
+ /** Viewer only: reports the match count and active index whenever either changes. */
19
+ readonly onMatchesChange?: (info: PdfMatchInfo) => void;
20
+ /** Viewer only: hides the toolbar's own search controls. */
21
+ readonly hideSearchBar?: boolean;
22
+ /** Viewer only: marks a passage without opening the search, e.g. the clause a step was read from. */
23
+ readonly markTerm?: string;
24
+ /** Viewer only: take the container's height without the 480px floor, for hosts whose layout sizes the pane. */
25
+ readonly fill?: boolean;
26
+ /** Viewer only: just the pages on the frame, without thumbnail rail and toolbar. */
27
+ readonly pagesOnly?: boolean;
28
+ };
29
+ /** PDF pages rendered with pdf.js; pages render lazily as they scroll into view. */
30
+ export declare function PdfPreview({ source, testId, variant, searchTerm, initialPage, fill, ...viewerProps }: PdfPreviewProps): ReactNode;
@@ -1,133 +1,16 @@
1
- import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Suspense, use, useCallback, useEffect, useMemo, useState } from "react";
1
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
+ import { Suspense, use, useEffect } from "react";
3
3
  import { useTranslation } from "../../i18n.js";
4
- import { createBoundedLoadCache } from "./bounded-load-cache.js";
5
- // pdf.js runs in the main thread ("fake worker"): the worker module is bundled
6
- // with the app and handed over through globalThis.pdfjsWorker, so no worker or
7
- // CDN URL is ever fetched (self-hosting and CSP stay intact).
8
- const RENDER_SCALE = 96 / 72;
9
- const MAX_CACHED_DOCUMENTS = 4;
10
- const documentCache = createBoundedLoadCache(MAX_CACHED_DOCUMENTS, (loaded) => {
11
- if (loaded.ok)
12
- void loaded.loadingTask.destroy();
13
- }, (loaded) => loaded.ok);
14
- function decodeBase64(base64) {
15
- const binary = atob(base64);
16
- const bytes = new Uint8Array(binary.length);
17
- for (let index = 0; index < binary.length; index++)
18
- bytes[index] = binary.charCodeAt(index);
19
- return bytes;
20
- }
21
- async function loadBytes(source) {
22
- if ("base64" in source)
23
- return decodeBase64(source.base64);
24
- const res = await fetch(source.url, { credentials: "same-origin" });
25
- if (!res.ok)
26
- throw new Error(`pdf fetch failed (${res.status})`);
27
- return new Uint8Array(await res.arrayBuffer());
28
- }
29
- async function loadDocument(source) {
30
- try {
31
- const [pdfjs, worker, data] = await Promise.all([
32
- import("pdfjs-dist"),
33
- import("pdfjs-dist/build/pdf.worker.min.mjs"),
34
- loadBytes(source),
35
- ]);
36
- Object.assign(globalThis, { pdfjsWorker: worker });
37
- const loadingTask = pdfjs.getDocument({ data });
38
- return { ok: true, document: await loadingTask.promise, loadingTask };
39
- }
40
- catch {
41
- return { ok: false };
42
- }
43
- }
44
- // The promise must be stable across renders for use().
45
- function documentKey(source) {
46
- return "base64" in source ? `base64:${source.base64}` : `url:${source.url}`;
47
- }
48
- function documentFor(source) {
49
- return documentCache.load(documentKey(source), () => loadDocument(source));
50
- }
51
- function PageView({ document, pageNumber, }) {
52
- const t = useTranslation();
53
- const page = use(pageFor(document, pageNumber));
54
- // Stable identity: the mount callbacks below depend on it, and a new viewport per render re-mounts canvas and text layer.
55
- const viewport = useMemo(() => page.getViewport({ scale: RENDER_SCALE }), [page]);
56
- const [availableWidth, setAvailableWidth] = useState(null);
57
- const measureFrame = useCallback((frame) => {
58
- if (frame === null)
59
- return;
60
- const observer = new ResizeObserver(() => setAvailableWidth(frame.clientWidth));
61
- observer.observe(frame);
62
- setAvailableWidth(frame.clientWidth);
63
- return () => observer.disconnect();
64
- }, []);
65
- // The sheet keeps its natural pixel size and is scaled as a whole, so canvas and text layer stay aligned.
66
- const fitScale = availableWidth === null || availableWidth <= 0
67
- ? 1
68
- : Math.min(1, availableWidth / viewport.width);
69
- const mountCanvas = useCallback((canvas) => {
70
- if (canvas === null)
71
- return;
72
- const pixelRatio = globalThis.devicePixelRatio || 1;
73
- canvas.width = Math.floor(viewport.width * pixelRatio);
74
- canvas.height = Math.floor(viewport.height * pixelRatio);
75
- const task = page.render({
76
- canvas,
77
- viewport,
78
- transform: pixelRatio === 1 ? undefined : [pixelRatio, 0, 0, pixelRatio, 0, 0],
79
- });
80
- task.promise.catch(() => undefined);
81
- return () => task.cancel();
82
- }, [page, viewport]);
83
- const mountTextLayer = useCallback((container) => {
84
- if (container === null)
85
- return;
86
- container.style.setProperty("--total-scale-factor", String(RENDER_SCALE));
87
- container.style.setProperty("--scale-factor", String(RENDER_SCALE));
88
- let layer = null;
89
- let cancelled = false;
90
- void import("pdfjs-dist").then(({ TextLayer }) => {
91
- // skip: cleanup ran before pdfjs finished loading
92
- if (cancelled)
93
- return undefined;
94
- // TextLayer.cancel() keeps rendered spans; a re-mount must not append a second layer.
95
- container.replaceChildren();
96
- const textLayer = new TextLayer({
97
- textContentSource: page.streamTextContent(),
98
- container,
99
- viewport,
100
- });
101
- layer = textLayer;
102
- return textLayer.render().catch(() => undefined);
103
- });
104
- return () => {
105
- cancelled = true;
106
- layer?.cancel();
107
- };
108
- }, [page, viewport]);
109
- return (_jsxs("figure", { className: "m-0 flex w-full flex-col items-center gap-2 rounded-lg bg-muted p-4", "data-testid": `pdf-page-${pageNumber}`, children: [_jsx("div", { ref: measureFrame, className: "w-full", children: _jsx("div", { className: "mx-auto", style: { width: viewport.width * fitScale, height: viewport.height * fitScale }, children: _jsxs("div", { className: "relative border border-border bg-white shadow-md", style: {
110
- width: viewport.width,
111
- height: viewport.height,
112
- transform: `scale(${fitScale})`,
113
- transformOrigin: "top left",
114
- }, children: [_jsx("canvas", { ref: mountCanvas, style: { width: viewport.width, height: viewport.height }, className: "block" }), _jsx("div", { ref: mountTextLayer, className: "absolute inset-0 overflow-hidden leading-none [&_span]:absolute [&_span]:origin-top-left [&_span]:cursor-text [&_span]:whitespace-pre [&_span]:text-transparent [&_span::selection]:bg-primary/30" })] }) }) }), _jsx("figcaption", { className: "text-xs text-muted-foreground", children: t("kumiko.widget.pdf-preview.pageOf", { page: pageNumber, pages: document.numPages }) })] }));
115
- }
116
- const pageCache = new WeakMap();
117
- function pageFor(document, pageNumber) {
118
- let pages = pageCache.get(document);
119
- if (pages === undefined) {
120
- pages = new Map();
121
- pageCache.set(document, pages);
122
- }
123
- let page = pages.get(pageNumber);
124
- if (page === undefined) {
125
- page = document.getPage(pageNumber);
126
- pages.set(pageNumber, page);
127
- }
128
- return page;
129
- }
130
- function Pages({ source }) {
4
+ import { cn } from "../lib/cn.js";
5
+ import { documentCache, documentFor, documentKey } from "./pdf-document.js";
6
+ import { PdfPageSlot, useFirstPageSize } from "./pdf-page.js";
7
+ import { PdfViewer } from "./pdf-viewer.js";
8
+ function StackedPages({ document }) {
9
+ const firstPageSize = useFirstPageSize(document);
10
+ const layout = { variant: "stacked", zoom: 1, highlight: null };
11
+ return (_jsx(_Fragment, { children: Array.from({ length: document.numPages }, (_, index) => index + 1).map((pageNumber) => (_jsx(PdfPageSlot, { document: document, pageNumber: pageNumber, firstPageSize: firstPageSize, layout: layout }, pageNumber))) }));
12
+ }
13
+ function Pages({ source, variant, searchTerm, initialPage, ...viewerProps }) {
131
14
  const t = useTranslation();
132
15
  const loaded = use(documentFor(source));
133
16
  // A mounted preview keeps its document out of the eviction: destroying it blanks its pages.
@@ -136,10 +19,15 @@ function Pages({ source }) {
136
19
  if (!loaded.ok) {
137
20
  return _jsx("p", { className: "text-sm text-status-bad", children: t("kumiko.widget.pdf-preview.renderFailed") });
138
21
  }
139
- const pageNumbers = Array.from({ length: loaded.document.numPages }, (_, index) => index + 1);
140
- return (_jsx(_Fragment, { children: pageNumbers.map((pageNumber) => (_jsx(Suspense, { fallback: null, children: _jsx(PageView, { document: loaded.document, pageNumber: pageNumber }) }, pageNumber))) }));
22
+ if (variant === "viewer") {
23
+ return (_jsx(PdfViewer, { document: loaded.document, searchTerm: searchTerm, initialPage: initialPage, ...viewerProps }));
24
+ }
25
+ return _jsx(StackedPages, { document: loaded.document });
141
26
  }
142
- export function PdfPreview({ source, testId = "pdf-preview", }) {
27
+ /** PDF pages rendered with pdf.js; pages render lazily as they scroll into view. */
28
+ export function PdfPreview({ source, testId = "pdf-preview", variant = "stacked", searchTerm, initialPage, fill = false, ...viewerProps }) {
143
29
  const t = useTranslation();
144
- return (_jsx("div", { className: "flex flex-col items-stretch gap-4 overflow-auto", "data-testid": testId, children: _jsx(Suspense, { fallback: _jsx("p", { className: "text-sm text-muted-foreground", children: t("kumiko.widget.pdf-preview.loading") }), children: _jsx(Pages, { source: source }) }) }));
30
+ return (_jsx("div", { className: variant === "viewer"
31
+ ? cn("h-full", fill ? "min-h-0" : "min-h-[480px]")
32
+ : "flex flex-col items-stretch gap-4 overflow-auto", "data-testid": testId, children: _jsx(Suspense, { fallback: _jsx("p", { className: "text-sm text-muted-foreground", children: t("kumiko.widget.pdf-preview.loading") }), children: _jsx(Pages, { source: source, variant: variant, searchTerm: searchTerm, initialPage: initialPage, fill: fill, ...viewerProps }) }) }));
145
33
  }
@@ -0,0 +1,43 @@
1
+ export type PdfMatch = {
2
+ readonly page: number;
3
+ /** Position of the match among all matches on its page, in text-layer order. */
4
+ readonly ordinalOnPage: number;
5
+ };
6
+ export type PdfMatchInfo = {
7
+ readonly count: number;
8
+ /** 0-based index of the active match. */
9
+ readonly index: number;
10
+ };
11
+ export declare const HIT_CLASS = "pdf-hit";
12
+ export declare const ACTIVE_HIT_CLASS = "pdf-hit-active";
13
+ export declare const HIT_BAND_CLASS = "pdf-hit-band";
14
+ export declare const ACTIVE_HIT_BAND_CLASS = "pdf-hit-band-active";
15
+ export type HitRect = {
16
+ readonly left: number;
17
+ readonly top: number;
18
+ readonly right: number;
19
+ readonly bottom: number;
20
+ };
21
+ /**
22
+ * One rect per visual line: rects whose vertical extents overlap fuse from the leftmost left to the
23
+ * rightmost right, so a passage over table cells reads as one band instead of one chip per text span.
24
+ */
25
+ export declare function mergeLineRects(rects: readonly HitRect[]): readonly HitRect[];
26
+ /** The part of one match that lies inside one text item (a text-layer span). */
27
+ export type MatchSegment = {
28
+ readonly item: number;
29
+ readonly start: number;
30
+ readonly end: number;
31
+ };
32
+ /**
33
+ * Case-insensitive, non-overlapping occurrences of `term` across the concatenated items, so a
34
+ * phrase wrapping over several text-layer lines still matches. Whitespace is ignored on both
35
+ * sides because item boundaries and line breaks carry no reliable spaces.
36
+ */
37
+ export declare function findTextMatches(items: readonly string[], term: string): readonly (readonly MatchSegment[])[];
38
+ export declare function findMatches(pageItems: readonly (readonly string[])[], term: string): readonly PdfMatch[];
39
+ export declare function clampPage(page: number, pageCount: number): number;
40
+ /** Page with the largest visible share; ties go to the lower page. */
41
+ export declare function mostVisiblePage(ratios: ReadonlyMap<number, number>): number | null;
42
+ /** Wraps exactly the matched characters in <mark>; the active match also gets the stronger class. */
43
+ export declare function markTextLayer(container: HTMLElement, term: string, activeOrdinal: number | null): void;
@@ -0,0 +1,178 @@
1
+ export const HIT_CLASS = "pdf-hit";
2
+ export const ACTIVE_HIT_CLASS = "pdf-hit-active";
3
+ export const HIT_BAND_CLASS = "pdf-hit-band";
4
+ export const ACTIVE_HIT_BAND_CLASS = "pdf-hit-band-active";
5
+ /**
6
+ * One rect per visual line: rects whose vertical extents overlap fuse from the leftmost left to the
7
+ * rightmost right, so a passage over table cells reads as one band instead of one chip per text span.
8
+ */
9
+ export function mergeLineRects(rects) {
10
+ const lines = [];
11
+ for (const rect of [...rects].sort((a, b) => a.top - b.top || a.left - b.left)) {
12
+ const index = lines.findIndex((line) => rect.top < line.bottom && rect.bottom > line.top);
13
+ const line = lines[index];
14
+ if (line === undefined) {
15
+ lines.push(rect);
16
+ }
17
+ else {
18
+ lines[index] = {
19
+ left: Math.min(line.left, rect.left),
20
+ top: Math.min(line.top, rect.top),
21
+ right: Math.max(line.right, rect.right),
22
+ bottom: Math.max(line.bottom, rect.bottom),
23
+ };
24
+ }
25
+ }
26
+ return lines;
27
+ }
28
+ const WHITESPACE = /\s/;
29
+ /**
30
+ * Case-insensitive, non-overlapping occurrences of `term` across the concatenated items, so a
31
+ * phrase wrapping over several text-layer lines still matches. Whitespace is ignored on both
32
+ * sides because item boundaries and line breaks carry no reliable spaces.
33
+ */
34
+ export function findTextMatches(items, term) {
35
+ const needle = Array.from(term.toLowerCase())
36
+ .filter((char) => !WHITESPACE.test(char))
37
+ .join("");
38
+ if (needle === "")
39
+ return [];
40
+ let haystack = "";
41
+ const origins = [];
42
+ items.forEach((text, item) => {
43
+ for (let offset = 0; offset < text.length; offset++) {
44
+ const char = text.charAt(offset);
45
+ if (WHITESPACE.test(char))
46
+ continue;
47
+ for (const lowered of char.toLowerCase()) {
48
+ haystack += lowered;
49
+ origins.push({ item, offset });
50
+ }
51
+ }
52
+ });
53
+ const matches = [];
54
+ for (let from = haystack.indexOf(needle); from >= 0; from = haystack.indexOf(needle, from + needle.length)) {
55
+ const segments = [];
56
+ for (const origin of origins.slice(from, from + needle.length)) {
57
+ const last = segments.at(-1);
58
+ if (last !== undefined && last.item === origin.item) {
59
+ segments[segments.length - 1] = { ...last, end: origin.offset + 1 };
60
+ }
61
+ else {
62
+ segments.push({ item: origin.item, start: origin.offset, end: origin.offset + 1 });
63
+ }
64
+ }
65
+ matches.push(segments);
66
+ }
67
+ return matches;
68
+ }
69
+ export function findMatches(pageItems, term) {
70
+ return pageItems.flatMap((items, pageIndex) => findTextMatches(items, term).map((_, ordinalOnPage) => ({
71
+ page: pageIndex + 1,
72
+ ordinalOnPage,
73
+ })));
74
+ }
75
+ export function clampPage(page, pageCount) {
76
+ if (!Number.isFinite(page))
77
+ return 1;
78
+ return Math.min(Math.max(1, Math.round(page)), Math.max(1, pageCount));
79
+ }
80
+ /** Page with the largest visible share; ties go to the lower page. */
81
+ export function mostVisiblePage(ratios) {
82
+ let best = null;
83
+ let bestRatio = 0;
84
+ for (const page of [...ratios.keys()].sort((left, right) => left - right)) {
85
+ const ratio = ratios.get(page) ?? 0;
86
+ if (ratio > bestRatio) {
87
+ best = page;
88
+ bestRatio = ratio;
89
+ }
90
+ }
91
+ return best;
92
+ }
93
+ /** Text spans only; pdf.js nests them inside marked-content spans of tagged PDFs. */
94
+ function textLeafSpans(container) {
95
+ return [...container.querySelectorAll("span")].filter((span) => span.querySelector("span") === null);
96
+ }
97
+ function renderMarkedText(span, segments) {
98
+ const text = span.textContent ?? "";
99
+ const nodes = [];
100
+ let cursor = 0;
101
+ for (const { start, end, active, ordinal } of segments) {
102
+ if (start > cursor)
103
+ nodes.push(span.ownerDocument.createTextNode(text.slice(cursor, start)));
104
+ const mark = span.ownerDocument.createElement("mark");
105
+ mark.className = active ? `${HIT_CLASS} ${ACTIVE_HIT_CLASS}` : HIT_CLASS;
106
+ mark.setAttribute("data-hit-ordinal", String(ordinal));
107
+ mark.textContent = text.slice(start, end);
108
+ nodes.push(mark);
109
+ cursor = end;
110
+ }
111
+ if (cursor < text.length)
112
+ nodes.push(span.ownerDocument.createTextNode(text.slice(cursor)));
113
+ span.replaceChildren(...nodes);
114
+ }
115
+ /**
116
+ * Bands are positioned in percent of the layer so they follow the sheet's fit-to-width transform
117
+ * without re-measuring; a layer without layout (zero size) gets none.
118
+ */
119
+ function renderHitBands(container) {
120
+ for (const band of container.querySelectorAll(`.${HIT_BAND_CLASS}`))
121
+ band.remove();
122
+ const layer = container.getBoundingClientRect();
123
+ // skip: a layer without layout yet has nothing to place the bands on
124
+ if (layer.width === 0 || layer.height === 0)
125
+ return;
126
+ const rectsByOrdinal = new Map();
127
+ for (const mark of container.querySelectorAll("mark")) {
128
+ const ordinal = mark.getAttribute("data-hit-ordinal") ?? "";
129
+ const entry = rectsByOrdinal.get(ordinal) ?? { active: false, rects: [] };
130
+ entry.active ||= mark.classList.contains(ACTIVE_HIT_CLASS);
131
+ for (const rect of mark.getClientRects()) {
132
+ if (rect.width > 0)
133
+ entry.rects.push(rect);
134
+ }
135
+ rectsByOrdinal.set(ordinal, entry);
136
+ }
137
+ const bands = [];
138
+ for (const { active, rects } of rectsByOrdinal.values()) {
139
+ for (const line of mergeLineRects(rects)) {
140
+ const band = container.ownerDocument.createElement("div");
141
+ band.className = active ? `${HIT_BAND_CLASS} ${ACTIVE_HIT_BAND_CLASS}` : HIT_BAND_CLASS;
142
+ band.style.cssText = [
143
+ "position:absolute",
144
+ "pointer-events:none",
145
+ `left:${(100 * (line.left - layer.left)) / layer.width}%`,
146
+ `top:${(100 * (line.top - layer.top)) / layer.height}%`,
147
+ `width:${(100 * (line.right - line.left)) / layer.width}%`,
148
+ `height:${(100 * (line.bottom - line.top)) / layer.height}%`,
149
+ ].join(";");
150
+ bands.push(band);
151
+ }
152
+ }
153
+ container.prepend(...bands);
154
+ }
155
+ /** Wraps exactly the matched characters in <mark>; the active match also gets the stronger class. */
156
+ export function markTextLayer(container, term, activeOrdinal) {
157
+ for (const band of container.querySelectorAll(`.${HIT_BAND_CLASS}`))
158
+ band.remove();
159
+ const spans = textLeafSpans(container);
160
+ for (const span of spans) {
161
+ if (span.querySelector("mark") !== null)
162
+ span.replaceChildren(span.textContent ?? "");
163
+ }
164
+ const segmentsBySpan = new Map();
165
+ findTextMatches(spans.map((span) => span.textContent ?? ""), term).forEach((segments, ordinal) => {
166
+ for (const { item, start, end } of segments) {
167
+ const forSpan = segmentsBySpan.get(item) ?? [];
168
+ forSpan.push({ start, end, active: ordinal === activeOrdinal, ordinal });
169
+ segmentsBySpan.set(item, forSpan);
170
+ }
171
+ });
172
+ for (const [item, segments] of segmentsBySpan) {
173
+ const span = spans[item];
174
+ if (span !== undefined)
175
+ renderMarkedText(span, segments);
176
+ }
177
+ renderHitBands(container);
178
+ }
@@ -0,0 +1,10 @@
1
+ import type { PDFDocumentProxy } from "pdfjs-dist";
2
+ import { type ReactNode } from "react";
3
+ import type { PdfPageSize } from "./pdf-page.tsx";
4
+ /** Left rail of lazily rendered page thumbnails; the active page gets a primary border. */
5
+ export declare function PdfThumbnails({ document, firstPageSize, currentPage, onSelect, }: {
6
+ readonly document: PDFDocumentProxy;
7
+ readonly firstPageSize: PdfPageSize;
8
+ readonly currentPage: number;
9
+ readonly onSelect: (page: number) => void;
10
+ }): ReactNode;
@@ -0,0 +1,35 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Suspense, use, useCallback } from "react";
3
+ import { useTranslation } from "../../i18n.js";
4
+ import { cn } from "../lib/cn.js";
5
+ import { pageFor } from "./pdf-document.js";
6
+ import { useSeenInViewport } from "./use-in-view.js";
7
+ const THUMBNAIL_WIDTH = 64;
8
+ function ThumbnailCanvas({ document, pageNumber, }) {
9
+ const page = use(pageFor(document, pageNumber));
10
+ const naturalWidth = page.getViewport({ scale: 1 }).width;
11
+ const mountCanvas = useCallback((canvas) => {
12
+ if (canvas === null)
13
+ return undefined;
14
+ const viewport = page.getViewport({ scale: THUMBNAIL_WIDTH / naturalWidth });
15
+ canvas.width = Math.floor(viewport.width);
16
+ canvas.height = Math.floor(viewport.height);
17
+ const task = page.render({ canvas, viewport });
18
+ task.promise.catch(() => undefined);
19
+ return () => task.cancel();
20
+ }, [page, naturalWidth]);
21
+ return _jsx("canvas", { ref: mountCanvas, className: "block size-full" });
22
+ }
23
+ function Thumbnail({ document, pageNumber, firstPageSize, active, onSelect, }) {
24
+ const t = useTranslation();
25
+ const { seen, observe } = useSeenInViewport("200px 0px");
26
+ return (_jsxs("button", { type: "button", ref: observe, "aria-label": t("kumiko.widget.pdf-preview.thumbnail", { page: pageNumber }), "aria-current": active ? "page" : undefined, "data-testid": `pdf-thumbnail-${pageNumber}`, onClick: () => onSelect(pageNumber), className: "flex shrink-0 flex-col items-center gap-1 border-0 bg-transparent p-0 text-xs text-foreground-secondary", children: [_jsx("span", { className: cn("box-border block overflow-hidden rounded-sheet border-2 bg-white", active ? "border-primary" : "border-transparent"), style: {
27
+ width: THUMBNAIL_WIDTH,
28
+ height: Math.round((THUMBNAIL_WIDTH * firstPageSize.height) / firstPageSize.width),
29
+ }, children: seen && (_jsx(Suspense, { fallback: null, children: _jsx(ThumbnailCanvas, { document: document, pageNumber: pageNumber }) })) }), pageNumber] }));
30
+ }
31
+ /** Left rail of lazily rendered page thumbnails; the active page gets a primary border. */
32
+ export function PdfThumbnails({ document, firstPageSize, currentPage, onSelect, }) {
33
+ const t = useTranslation();
34
+ return (_jsx("nav", { "aria-label": t("kumiko.widget.pdf-preview.pages"), className: "flex w-28 shrink-0 flex-col items-center gap-3 overflow-y-auto border-r border-border bg-muted py-3", children: Array.from({ length: document.numPages }, (_, index) => index + 1).map((pageNumber) => (_jsx(Thumbnail, { document: document, pageNumber: pageNumber, firstPageSize: firstPageSize, active: pageNumber === currentPage, onSelect: onSelect }, pageNumber))) }));
35
+ }
@@ -0,0 +1,22 @@
1
+ import { type ReactNode } from "react";
2
+ export type PdfSearchState = {
3
+ readonly open: boolean;
4
+ readonly term: string;
5
+ readonly matchCount: number;
6
+ /** 0-based index of the active match. */
7
+ readonly matchIndex: number;
8
+ };
9
+ export type PdfViewerToolbarProps = {
10
+ readonly currentPage: number;
11
+ readonly pageCount: number;
12
+ readonly onGoToPage: (page: number) => void;
13
+ readonly zoom: number;
14
+ readonly onZoomOut: () => void;
15
+ readonly onZoomIn: () => void;
16
+ readonly search: PdfSearchState;
17
+ readonly onToggleSearch: () => void;
18
+ readonly onTermChange: (term: string) => void;
19
+ readonly onStepMatch: (direction: 1 | -1) => void;
20
+ readonly hideSearch?: boolean;
21
+ };
22
+ export declare function PdfViewerToolbar(props: PdfViewerToolbarProps): ReactNode;