@softure-ai/theme-notion 0.17.0 → 0.19.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.
@@ -0,0 +1,44 @@
1
+ // The PDF engine of `DocumentViewer`: pdf.js (Apache-2.0) loaded on first use, its worker code run on the page's main
2
+ // thread (no worker URL to configure, and the chunks are ordinary build files a service worker keeps). Behind a small
3
+ // interface, so a test or an app can pass another engine.
4
+ let loading = null;
5
+ /**
6
+ * pdf.js as a `PdfEngine`, loaded once. The legacy build, so an older phone browser reads it too. Call it ahead (e.g.
7
+ * when a page with documents opens) to fetch its chunks while online, so an installed app opens a PDF offline later.
8
+ */
9
+ export function loadPdfjsEngine() {
10
+ loading ??= importPdfjs().catch((error) => {
11
+ loading = null;
12
+ throw error;
13
+ });
14
+ return loading;
15
+ }
16
+ async function importPdfjs() {
17
+ const [pdfjs, worker] = await Promise.all([import("pdfjs-dist/legacy/build/pdf.mjs"), import("pdfjs-dist/legacy/build/pdf.worker.min.mjs")]);
18
+ const scope = globalThis;
19
+ scope.pdfjsWorker ??= worker;
20
+ return {
21
+ async open(data) {
22
+ const task = pdfjs.getDocument({ data: new Uint8Array(data.slice(0)), useSystemFonts: true });
23
+ const document = await task.promise;
24
+ return {
25
+ pageCount: document.numPages,
26
+ async renderPage(pageNumber, canvas, width) {
27
+ const page = await document.getPage(pageNumber);
28
+ const base = page.getViewport({ scale: 1 });
29
+ const ratio = globalThis.devicePixelRatio > 0 ? globalThis.devicePixelRatio : 1;
30
+ const viewport = page.getViewport({ scale: (width / base.width) * ratio });
31
+ canvas.width = Math.floor(viewport.width);
32
+ canvas.height = Math.floor(viewport.height);
33
+ canvas.style.width = `${String(width)}px`;
34
+ canvas.style.height = `${String(Math.floor(viewport.height / ratio))}px`;
35
+ await page.render({ canvas, viewport }).promise;
36
+ },
37
+ destroy() {
38
+ void task.destroy();
39
+ },
40
+ };
41
+ },
42
+ };
43
+ }
44
+ //# sourceMappingURL=pdf-engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pdf-engine.js","sourceRoot":"","sources":["../../src/notion/pdf-engine.ts"],"names":[],"mappings":"AAAA,sHAAsH;AACtH,sHAAsH;AACtH,0DAA0D;AAoB1D,IAAI,OAAO,GAA8B,IAAI,CAAC;AAE9C;;;GAGG;AACH,MAAM,UAAU,eAAe;IAC7B,OAAO,KAAK,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACjD,OAAO,GAAG,IAAI,CAAC;QACf,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,KAAK,UAAU,WAAW;IACxB,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,iCAAiC,CAAC,EAAE,MAAM,CAAC,4CAA4C,CAAC,CAAC,CAAC,CAAC;IAC7I,MAAM,KAAK,GAAG,UAAyB,CAAC;IACxC,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC;IAC7B,OAAO;QACL,KAAK,CAAC,IAAI,CAAC,IAAI;YACb,MAAM,IAAI,GAAG,KAAK,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,IAAI,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC;YAC9F,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC;YACpC,OAAO;gBACL,SAAS,EAAE,QAAQ,CAAC,QAAQ;gBAC5B,KAAK,CAAC,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK;oBACxC,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;oBAChD,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;oBAC5C,MAAM,KAAK,GAAG,UAAU,CAAC,gBAAgB,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC;oBAChF,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,EAAE,CAAC,CAAC;oBAC3E,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;oBAC1C,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;oBAC5C,MAAM,CAAC,KAAK,CAAC,KAAK,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC;oBAC1C,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC;oBACzE,MAAM,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,OAAO,CAAC;gBAClD,CAAC;gBACD,OAAO;oBACL,KAAK,IAAI,CAAC,OAAO,EAAE,CAAC;gBACtB,CAAC;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -1,44 +1,52 @@
1
1
  /*
2
- * The bridge from the `--sft-*` tokens of @softure-ai/ui to the Notion theme. Pages rendered by the SOFTURE packages
3
- * (sign-in, password, MCP access, OAuth consent) read `--sft-*`; inside a `PageFrame` (any `[data-page-frame]`
4
- * element) those tokens point at the Notion values, so the package pages take the theme's colours, type, radii and
5
- * shadows. Scoped to the frame, not `:root`: screens still on `--sft-*` keep their look until they move. The Notion
6
- * colours and shadows switch scheme by themselves, so the bridge needs no dark block. Spacing, text sizes and
7
- * durations stay the package's: the scales already match, and the theme has no motion tokens.
2
+ * The bridge from the `--sft-*` tokens of @softure-ai/ui to the Notion theme. Every ui component (fields, cards,
3
+ * modals, toasts, the chat primitives) and the pages of the SOFTURE packages (sign-in, password, MCP access, OAuth
4
+ * consent) paint with `--sft-*`; here those tokens point at the Notion values, so they take the theme's colours, type,
5
+ * radii and shadows wherever they sit: in the app shell, in a panel, or in a `PageFrame`.
6
+ *
7
+ * On every scheme scope, not `:root` alone: a custom property holding `var()` resolves on the element that declares
8
+ * it and children inherit the result, so an alias on `:root` alone would freeze the root's values inside a `.dark`
9
+ * band of a light page. `[data-page-frame]` stays in the list for a frame inside such a band. Unlayered, so it beats
10
+ * ui's defaults in `@layer softure` on the same element; an app's own `--sft-*` rule after this import still wins.
11
+ * Spacing, text sizes and durations stay the package's: the scales already match, and the theme has no motion tokens.
8
12
  *
9
13
  * Import it after `theme.css`, through the app's Tailwind (it reads the theme with `--theme()`).
10
14
  */
11
- @layer base {
12
- [data-page-frame] {
13
- --sft-font-sans: --theme(--font-sans);
14
- --sft-font-heading: --theme(--font-sans);
15
- --sft-font-mono: --theme(--font-mono);
15
+ :root,
16
+ .light,
17
+ .dark,
18
+ [data-theme],
19
+ [data-page-frame] {
20
+ --sft-font-sans: --theme(--font-sans);
21
+ --sft-font-heading: --theme(--font-sans);
22
+ --sft-font-mono: --theme(--font-mono);
16
23
 
17
- --sft-radius-control: --theme(--radius-md);
18
- --sft-radius-card: --theme(--radius-lg);
19
- --sft-radius-pill: --theme(--radius-full);
24
+ --sft-radius-control: --theme(--radius-md);
25
+ --sft-radius-card: --theme(--radius-lg);
26
+ --sft-radius-pill: --theme(--radius-full);
20
27
 
21
- --sft-color-background: var(--background);
22
- --sft-color-surface: var(--card);
23
- --sft-color-surface-raised: var(--popover);
24
- --sft-color-foreground: var(--foreground);
25
- --sft-color-muted: var(--muted-foreground);
26
- --sft-color-border: var(--border);
27
- --sft-color-border-strong: var(--control-off);
28
- --sft-color-accent: var(--primary);
29
- --sft-color-accent-fill: var(--primary);
30
- --sft-color-accent-fill-hover: var(--primary-hover);
31
- --sft-color-on-accent: var(--primary-foreground);
32
- --sft-color-danger: var(--red);
33
- --sft-color-success: var(--green);
34
- --sft-color-warning: var(--orange);
35
- --sft-color-focus: var(--ring);
36
- --sft-color-overlay: var(--overlay);
28
+ --sft-color-background: var(--background);
29
+ --sft-color-surface: var(--card);
30
+ --sft-color-surface-raised: var(--popover);
31
+ --sft-color-foreground: var(--foreground);
32
+ --sft-color-muted: var(--muted-foreground);
33
+ --sft-color-border: var(--border);
34
+ --sft-color-border-strong: var(--control-off);
35
+ --sft-color-accent: var(--primary);
36
+ --sft-color-accent-fill: var(--primary);
37
+ --sft-color-accent-fill-hover: var(--primary-hover);
38
+ --sft-color-on-accent: var(--primary-foreground);
39
+ --sft-color-danger: var(--red);
40
+ --sft-color-success: var(--green);
41
+ --sft-color-warning: var(--orange);
42
+ --sft-color-focus: var(--ring);
43
+ --sft-color-overlay: var(--overlay);
37
44
 
38
- --sft-shadow-1: var(--shadow-card);
39
- --sft-shadow-2: var(--shadow-dialog);
40
- }
45
+ --sft-shadow-1: var(--shadow-card);
46
+ --sft-shadow-2: var(--shadow-dialog);
47
+ }
41
48
 
49
+ @layer base {
42
50
  /* A page in a frame fills the window: no browser margin, the Notion background behind everything. */
43
51
  body:has([data-page-frame]) {
44
52
  margin: 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softure-ai/theme-notion",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "SOFTURE AI Notion theme: shadcn/ui components (new-york v4, Radix, Tailwind CSS v4, lucide) with the Notion design system's tokens and deltas, ready to import.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -65,6 +65,7 @@
65
65
  "class-variance-authority": "^0.7.1",
66
66
  "cmdk": "^1.1.1",
67
67
  "lucide-react": "^1.70.0",
68
+ "pdfjs-dist": "^6.5.438",
68
69
  "radix-ui": "^1.8.1",
69
70
  "sonner": "^2.0.8",
70
71
  "tw-animate-css": "^1.4.0"
package/src/index.ts CHANGED
@@ -105,6 +105,19 @@ export { Steps, type StepItem, type StepState, type StepsLayout, type StepsProps
105
105
  export { TabBar, type TabBarItem, type TabBarProps } from "./notion/TabBar.js";
106
106
  export { Timeline, type TimelineItem, type TimelineItemFold, type TimelineItemSize, type TimelineLine, type TimelineProps } from "./notion/Timeline.js";
107
107
  export { TopLoadingBar, type TopLoadingBarProps } from "./notion/TopLoadingBar.js";
108
+ export { DOCUMENT_ZOOM_STEPS, getDocumentKind, type DocumentKind } from "./notion/document-kind.js";
109
+ export {
110
+ DocumentList,
111
+ DocumentRow,
112
+ DocumentViewer,
113
+ type DocumentListProps,
114
+ type DocumentMessages,
115
+ type DocumentMessagesOverride,
116
+ type DocumentRowProps,
117
+ type DocumentSource,
118
+ type DocumentViewerProps,
119
+ } from "./notion/Document.js";
120
+ export { loadPdfjsEngine, type PdfDocumentHandle, type PdfEngine } from "./notion/pdf-engine.js";
108
121
  export {
109
122
  UploadField,
110
123
  UploadItem,
@@ -0,0 +1,4 @@
1
+ // The PDF engine's worker module, imported only to run its message handler on the page's main thread.
2
+ declare module "pdfjs-dist/legacy/build/pdf.worker.min.mjs" {
3
+ export const WorkerMessageHandler: unknown;
4
+ }
@@ -44,6 +44,20 @@ export const en = {
44
44
  done: "Done",
45
45
  failed: "Failed",
46
46
  },
47
+ document: {
48
+ close: "Close",
49
+ zoomIn: "Zoom in",
50
+ zoomOut: "Zoom out",
51
+ zoom: "{percent}%",
52
+ pageCount: "{count} pages",
53
+ pageCountOne: "1 page",
54
+ page: "Page {number} of {count}",
55
+ loading: "Opening the document",
56
+ failed: "This document cannot be shown.",
57
+ unsupported: "This type of document cannot be shown here.",
58
+ offline: "Available offline",
59
+ open: "Open",
60
+ },
47
61
  steps: { done: "Done", current: "Current", todo: "To do", failed: "Failed" },
48
62
  command: { title: "Command Palette", description: "Search for a command to run..." },
49
63
  } as const;
@@ -0,0 +1,347 @@
1
+ "use client";
2
+
3
+ import { CircleCheck, File as FileIcon, FileImage, FileText, LoaderCircle, Minus, Plus, X, type LucideIcon } from "lucide-react";
4
+ import { useEffect, useRef, useState, type ReactNode } from "react";
5
+
6
+ import { en } from "../messages/en.js";
7
+ import { cn } from "../lib/utils.js";
8
+ import { Button } from "../ui/button.js";
9
+ import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from "../ui/dialog.js";
10
+
11
+ import { DOCUMENT_ZOOM_STEPS, getDocumentKind, type DocumentKind } from "./document-kind.js";
12
+ import { formatFileSize } from "./format-file-size.js";
13
+ import { ICON_STROKE_WIDTH } from "./icon-stroke.js";
14
+ import { loadPdfjsEngine, type PdfDocumentHandle, type PdfEngine } from "./pdf-engine.js";
15
+ import { Status } from "./Status.js";
16
+
17
+ /** What the viewer shows: the bytes at hand (a kept copy, offline) or a URL it fetches. */
18
+ export type DocumentSource = { readonly blob: Blob } | { readonly url: string };
19
+
20
+ /** The texts of the document parts; `{count}`, `{number}` and `{percent}` are filled in. Built-in English: `notionMessages.en.document`. */
21
+ export interface DocumentMessages {
22
+ readonly close: string;
23
+ readonly zoomIn: string;
24
+ readonly zoomOut: string;
25
+ readonly zoom: string;
26
+ readonly pageCount: string;
27
+ readonly pageCountOne: string;
28
+ readonly page: string;
29
+ readonly loading: string;
30
+ readonly failed: string;
31
+ readonly unsupported: string;
32
+ readonly offline: string;
33
+ /** Read by a screen reader before a row's title. */
34
+ readonly open: string;
35
+ }
36
+
37
+ /** The app's wording for the document parts; each text left out keeps the built-in English one. */
38
+ export type DocumentMessagesOverride = Partial<DocumentMessages>;
39
+
40
+ function mergeMessages(override: DocumentMessagesOverride | undefined): DocumentMessages {
41
+ return { ...en.document, ...override };
42
+ }
43
+
44
+ function fill(template: string, values: Readonly<Record<string, string | number>>): string {
45
+ return template.replaceAll(/\{(\w+)\}/g, (match, key: string) => (key in values ? String(values[key]) : match));
46
+ }
47
+
48
+ const FIT_INDEX = 2;
49
+ /** The width a PDF page fits when the viewer cannot measure its area (a page rendered on the server, a test). */
50
+ const FALLBACK_WIDTH = 800;
51
+ /** The widest a page is drawn at 100 %: a printed page's width on a wide screen, so its lines stay readable. */
52
+ const MAX_FIT_WIDTH = 880;
53
+
54
+ /** Reads a URL's bytes as the signed-in user, the way the app's own page would. */
55
+ async function fetchDocument(url: string): Promise<Blob> {
56
+ const response = await fetch(url, { credentials: "same-origin" });
57
+ if (!response.ok) throw new Error(`DocumentViewer: fetching ${url} answered ${String(response.status)}`);
58
+ return response.blob();
59
+ }
60
+
61
+ type Loaded =
62
+ | { readonly state: "loading" }
63
+ | { readonly state: "failed" }
64
+ | { readonly state: "unsupported" }
65
+ | { readonly state: "pdf"; readonly document: PdfDocumentHandle }
66
+ | { readonly state: "image"; readonly url: string };
67
+
68
+ export interface DocumentViewerProps {
69
+ readonly open: boolean;
70
+ readonly onOpenChange: (open: boolean) => void;
71
+ /** The document's title, shown on top and as the dialog's name. */
72
+ readonly title: string;
73
+ /** The media type; it decides between PDF pages and an image. */
74
+ readonly contentType: string;
75
+ /** The bytes or the URL; nothing loads while it is `null`. */
76
+ readonly source: DocumentSource | null;
77
+ /** The PDF engine; pdf.js loaded on first use by default. */
78
+ readonly loadPdfEngine?: () => Promise<PdfEngine>;
79
+ /** Reads a URL source; `fetch` with the page's cookies by default. */
80
+ readonly fetchFile?: (url: string) => Promise<Blob>;
81
+ /** Something beside the zoom, e.g. a download link. */
82
+ readonly actions?: ReactNode;
83
+ readonly messages?: DocumentMessagesOverride;
84
+ readonly className?: string;
85
+ }
86
+
87
+ // A document inside the page, on the whole screen: a PDF's pages drawn one under the other, or an image, with the
88
+ // title, the page count, zoom and a close button. It never opens a new browser window, which an installed phone app
89
+ // cannot come back from offline; with a `Blob` source it needs no network at all.
90
+ export function DocumentViewer({ open, onOpenChange, title, contentType, source, loadPdfEngine = loadPdfjsEngine, fetchFile = fetchDocument, actions, messages, className }: DocumentViewerProps) {
91
+ const words = mergeMessages(messages);
92
+ const [loaded, setLoaded] = useState<Loaded>({ state: "loading" });
93
+ const [zoomIndex, setZoomIndex] = useState(FIT_INDEX);
94
+ const kind = getDocumentKind(contentType);
95
+
96
+ useEffect(() => {
97
+ if (!open || source === null) return undefined;
98
+ if (kind === "other") {
99
+ setLoaded({ state: "unsupported" });
100
+ return undefined;
101
+ }
102
+ let isCurrent = true;
103
+ let release = (): void => undefined;
104
+ setLoaded({ state: "loading" });
105
+ setZoomIndex(FIT_INDEX);
106
+ void (async () => {
107
+ try {
108
+ const blob = "blob" in source ? source.blob : await fetchFile(source.url);
109
+ if (kind === "image") {
110
+ const url = URL.createObjectURL(blob);
111
+ release = () => URL.revokeObjectURL(url);
112
+ if (isCurrent) setLoaded({ state: "image", url });
113
+ else release();
114
+ return;
115
+ }
116
+ const engine = await loadPdfEngine();
117
+ const document = await engine.open(await blob.arrayBuffer());
118
+ release = () => document.destroy();
119
+ if (isCurrent) setLoaded({ state: "pdf", document });
120
+ else release();
121
+ } catch {
122
+ if (isCurrent) setLoaded({ state: "failed" });
123
+ }
124
+ })();
125
+ return () => {
126
+ isCurrent = false;
127
+ release();
128
+ };
129
+ }, [open, source, kind, loadPdfEngine, fetchFile]);
130
+
131
+ const zoom = DOCUMENT_ZOOM_STEPS[zoomIndex] ?? 1;
132
+ const pageCount = loaded.state === "pdf" ? loaded.document.pageCount : null;
133
+ const canZoom = loaded.state === "pdf" || loaded.state === "image";
134
+
135
+ return (
136
+ <Dialog open={open} onOpenChange={onOpenChange}>
137
+ <DialogContent
138
+ data-slot="document-viewer"
139
+ showCloseButton={false}
140
+ className={cn(
141
+ "top-0 left-0 flex h-dvh max-w-none translate-x-0 translate-y-0 flex-col gap-0 rounded-none p-0 sm:max-w-none",
142
+ "pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",
143
+ className,
144
+ )}
145
+ >
146
+ <div data-slot="document-viewer-header" className="flex min-w-0 items-center gap-2 border-b border-border py-1 pr-2 pl-4">
147
+ <div className="flex min-w-0 flex-1 flex-col">
148
+ <DialogTitle className="truncate text-base" title={title}>
149
+ {title}
150
+ </DialogTitle>
151
+ <DialogDescription data-slot="document-viewer-pages" className="text-small">
152
+ {pageCount === null ? "" : pageCount === 1 ? words.pageCountOne : fill(words.pageCount, { count: pageCount })}
153
+ </DialogDescription>
154
+ </div>
155
+ {actions}
156
+ {canZoom ? (
157
+ <div data-slot="document-viewer-zoom" className="flex shrink-0 items-center gap-1">
158
+ <Button type="button" variant="ghost" size="icon-touch" className="md:size-7" aria-label={words.zoomOut} title={words.zoomOut} disabled={zoomIndex === 0} onClick={() => setZoomIndex((index) => Math.max(0, index - 1))}>
159
+ <Minus aria-hidden="true" strokeWidth={ICON_STROKE_WIDTH} />
160
+ </Button>
161
+ <span data-slot="document-viewer-zoom-level" aria-live="polite" className="w-12 text-center text-small text-muted-foreground tabular-nums">
162
+ {fill(words.zoom, { percent: Math.round(zoom * 100) })}
163
+ </span>
164
+ <Button
165
+ type="button"
166
+ variant="ghost"
167
+ size="icon-touch"
168
+ className="md:size-7"
169
+ aria-label={words.zoomIn}
170
+ title={words.zoomIn}
171
+ disabled={zoomIndex === DOCUMENT_ZOOM_STEPS.length - 1}
172
+ onClick={() => setZoomIndex((index) => Math.min(DOCUMENT_ZOOM_STEPS.length - 1, index + 1))}
173
+ >
174
+ <Plus aria-hidden="true" strokeWidth={ICON_STROKE_WIDTH} />
175
+ </Button>
176
+ </div>
177
+ ) : null}
178
+ {/* In the header, below the safe area, where the dialog's own corner button would sit under a phone's notch. */}
179
+ <DialogClose asChild>
180
+ <Button type="button" variant="ghost" size="icon-touch" data-slot="document-viewer-close" aria-label={words.close} title={words.close} className="shrink-0">
181
+ <X aria-hidden="true" strokeWidth={ICON_STROKE_WIDTH} />
182
+ </Button>
183
+ </DialogClose>
184
+ </div>
185
+ {/* Focusable, so the pages scroll with the keyboard too. */}
186
+ <div data-slot="document-viewer-body" role="region" aria-label={title} tabIndex={0} className="min-h-0 flex-1 overflow-auto bg-muted outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:ring-inset">
187
+ <DocumentBody loaded={loaded} zoom={zoom} title={title} words={words} />
188
+ </div>
189
+ </DialogContent>
190
+ </Dialog>
191
+ );
192
+ }
193
+
194
+ function DocumentBody({ loaded, zoom, title, words }: { readonly loaded: Loaded; readonly zoom: number; readonly title: string; readonly words: DocumentMessages }) {
195
+ if (loaded.state === "loading") {
196
+ return (
197
+ <p role="status" data-slot="document-viewer-loading" className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">
198
+ <LoaderCircle aria-hidden="true" strokeWidth={ICON_STROKE_WIDTH} className="size-4 animate-spin" />
199
+ {words.loading}
200
+ </p>
201
+ );
202
+ }
203
+ if (loaded.state === "failed" || loaded.state === "unsupported") {
204
+ return (
205
+ <p role="alert" data-slot="document-viewer-error" className="flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground">
206
+ {loaded.state === "failed" ? words.failed : words.unsupported}
207
+ </p>
208
+ );
209
+ }
210
+ if (loaded.state === "image") {
211
+ return (
212
+ <div className="flex min-h-full items-start justify-center p-4">
213
+ {/* An object URL of the bytes at hand: nothing for an image optimizer to fetch. */}
214
+ <img data-slot="document-viewer-image" src={loaded.url} alt={title} className="h-auto max-w-none" style={{ width: `${String(zoom * 100)}%` }} />
215
+ </div>
216
+ );
217
+ }
218
+ return <PdfPages document={loaded.document} zoom={zoom} words={words} />;
219
+ }
220
+
221
+ function PdfPages({ document, zoom, words }: { readonly document: PdfDocumentHandle; readonly zoom: number; readonly words: DocumentMessages }) {
222
+ const areaRef = useRef<HTMLDivElement>(null);
223
+ const [areaWidth, setAreaWidth] = useState<number | null>(null);
224
+
225
+ useEffect(() => {
226
+ const area = areaRef.current;
227
+ if (area === null) return undefined;
228
+ // The width inside the area's padding: at 100 % a page fits the screen with its margin on both sides.
229
+ const measure = (): void => {
230
+ const style = globalThis.getComputedStyle(area);
231
+ const inner = area.clientWidth - (Number.parseFloat(style.paddingLeft) || 0) - (Number.parseFloat(style.paddingRight) || 0);
232
+ setAreaWidth(inner > 0 ? Math.min(inner, MAX_FIT_WIDTH) : FALLBACK_WIDTH);
233
+ };
234
+ measure();
235
+ if (typeof ResizeObserver === "undefined") return undefined;
236
+ const observer = new ResizeObserver(measure);
237
+ observer.observe(area);
238
+ return () => observer.disconnect();
239
+ }, []);
240
+
241
+ const pages = Array.from({ length: document.pageCount }, (_, index) => index + 1);
242
+ return (
243
+ <div ref={areaRef} data-slot="document-viewer-pages-area" className="flex flex-col items-center gap-3 p-4">
244
+ {areaWidth === null
245
+ ? null
246
+ : pages.map((pageNumber) => (
247
+ <PdfPage key={pageNumber} document={document} pageNumber={pageNumber} width={Math.round(areaWidth * zoom)} label={fill(words.page, { number: pageNumber, count: document.pageCount })} />
248
+ ))}
249
+ </div>
250
+ );
251
+ }
252
+
253
+ function PdfPage({ document, pageNumber, width, label }: { readonly document: PdfDocumentHandle; readonly pageNumber: number; readonly width: number; readonly label: string }) {
254
+ const canvasRef = useRef<HTMLCanvasElement>(null);
255
+ const [hasFailed, setHasFailed] = useState(false);
256
+
257
+ useEffect(() => {
258
+ const canvas = canvasRef.current;
259
+ if (canvas === null) return;
260
+ document.renderPage(pageNumber, canvas, width).then(
261
+ () => setHasFailed(false),
262
+ () => setHasFailed(true),
263
+ );
264
+ }, [document, pageNumber, width]);
265
+
266
+ return (
267
+ <canvas
268
+ ref={canvasRef}
269
+ role="img"
270
+ aria-label={label}
271
+ data-slot="document-viewer-page"
272
+ data-page={pageNumber}
273
+ data-failed={hasFailed || undefined}
274
+ className="max-w-none bg-background shadow-dialog"
275
+ />
276
+ );
277
+ }
278
+
279
+ const KIND_ICONS: Readonly<Record<DocumentKind, LucideIcon>> = { pdf: FileText, image: FileImage, other: FileIcon };
280
+
281
+ export interface DocumentListProps {
282
+ /** The list's accessible name, e.g. "Documents". */
283
+ readonly label: string;
284
+ /** `DocumentRow` rows. */
285
+ readonly children: ReactNode;
286
+ readonly className?: string;
287
+ }
288
+
289
+ // The documents of an entry, one `DocumentRow` per row.
290
+ export function DocumentList({ label, children, className }: DocumentListProps) {
291
+ return (
292
+ <ul aria-label={label} data-slot="document-list" className={cn("flex flex-col gap-1", className)}>
293
+ {children}
294
+ </ul>
295
+ );
296
+ }
297
+
298
+ export interface DocumentRowProps {
299
+ readonly title: string;
300
+ readonly contentType: string;
301
+ /** In bytes. */
302
+ readonly size: number;
303
+ /** Whether a copy is kept on the device; draws the "available offline" mark. */
304
+ readonly isOffline?: boolean;
305
+ /** Opens the document, e.g. in `DocumentViewer`. */
306
+ readonly onOpen: () => void;
307
+ /** Buttons after the row, e.g. a menu to rename or remove. */
308
+ readonly actions?: ReactNode;
309
+ /** Formats the size, e.g. "de" writes "1,5 kB". */
310
+ readonly locale?: string;
311
+ readonly messages?: DocumentMessagesOverride;
312
+ readonly className?: string;
313
+ }
314
+
315
+ // One document: an icon by its type, the title as a touch-sized button that opens it, its size, and a mark when a copy
316
+ // is kept on the device.
317
+ export function DocumentRow({ title, contentType, size, isOffline = false, onOpen, actions, locale = "en", messages, className }: DocumentRowProps) {
318
+ const words = mergeMessages(messages);
319
+ const kind = getDocumentKind(contentType);
320
+ const Icon = KIND_ICONS[kind];
321
+ return (
322
+ <li data-slot="document-row" data-kind={kind} data-offline={isOffline || undefined} className={cn("flex min-w-0 items-center gap-2 rounded-md px-2 py-1", className)}>
323
+ <Icon aria-hidden="true" strokeWidth={ICON_STROKE_WIDTH} className="size-4 shrink-0 text-muted-foreground" />
324
+ <button
325
+ type="button"
326
+ data-slot="document-row-open"
327
+ onClick={onOpen}
328
+ className="flex min-h-touch-target min-w-0 flex-1 flex-wrap items-center gap-x-2 rounded-sm text-left outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 md:min-h-7"
329
+ >
330
+ {/* Read before the title, so the button's name is what it does and still holds every visible word. */}
331
+ <span className="sr-only">{words.open} </span>
332
+ <span data-slot="document-row-title" title={title} className="min-w-0 truncate text-sm font-medium">
333
+ {title}
334
+ </span>
335
+ <span data-slot="document-row-size" className="shrink-0 text-small text-muted-foreground tabular-nums">
336
+ {formatFileSize(size, locale)}
337
+ </span>
338
+ {isOffline ? (
339
+ <Status color="green" icon={CircleCheck} className="shrink-0 text-small">
340
+ {words.offline}
341
+ </Status>
342
+ ) : null}
343
+ </button>
344
+ {actions === undefined ? null : <div data-slot="document-row-actions" className="flex shrink-0 items-center gap-1">{actions}</div>}
345
+ </li>
346
+ );
347
+ }
@@ -0,0 +1,15 @@
1
+ // Plain helpers of the document parts, kept outside the client module so Server Components can use them.
2
+
3
+ /** How a document is shown: a PDF's pages, an image, or neither. */
4
+ export type DocumentKind = "pdf" | "image" | "other";
5
+
6
+ /** The kind of a document by its media type (`application/pdf`, `image/png`; parameters ignored). */
7
+ export function getDocumentKind(contentType: string): DocumentKind {
8
+ const essence = (contentType.split(";")[0] ?? "").trim().toLowerCase();
9
+ if (essence === "application/pdf") return "pdf";
10
+ if (essence.startsWith("image/")) return "image";
11
+ return "other";
12
+ }
13
+
14
+ /** The zoom steps, as a share of the fitted width. */
15
+ export const DOCUMENT_ZOOM_STEPS: readonly number[] = [0.5, 0.75, 1, 1.25, 1.5, 2, 3];
@@ -0,0 +1,64 @@
1
+ // The PDF engine of `DocumentViewer`: pdf.js (Apache-2.0) loaded on first use, its worker code run on the page's main
2
+ // thread (no worker URL to configure, and the chunks are ordinary build files a service worker keeps). Behind a small
3
+ // interface, so a test or an app can pass another engine.
4
+
5
+ /** An opened PDF: its page count, and each page drawn into a canvas at a CSS width. */
6
+ export interface PdfDocumentHandle {
7
+ readonly pageCount: number;
8
+ /** Draws page `pageNumber` (from 1) into `canvas`, `width` CSS pixels wide, sharp on the device's pixel ratio. */
9
+ renderPage(pageNumber: number, canvas: HTMLCanvasElement, width: number): Promise<void>;
10
+ /** Frees the document; a render after it fails. */
11
+ destroy(): void;
12
+ }
13
+
14
+ export interface PdfEngine {
15
+ /** Opens a PDF from its bytes; rejects for bytes that are not a PDF it can read. */
16
+ open(data: ArrayBuffer): Promise<PdfDocumentHandle>;
17
+ }
18
+
19
+ interface PdfjsGlobal {
20
+ pdfjsWorker?: unknown;
21
+ }
22
+
23
+ let loading: Promise<PdfEngine> | null = null;
24
+
25
+ /**
26
+ * pdf.js as a `PdfEngine`, loaded once. The legacy build, so an older phone browser reads it too. Call it ahead (e.g.
27
+ * when a page with documents opens) to fetch its chunks while online, so an installed app opens a PDF offline later.
28
+ */
29
+ export function loadPdfjsEngine(): Promise<PdfEngine> {
30
+ loading ??= importPdfjs().catch((error: unknown) => {
31
+ loading = null;
32
+ throw error;
33
+ });
34
+ return loading;
35
+ }
36
+
37
+ async function importPdfjs(): Promise<PdfEngine> {
38
+ const [pdfjs, worker] = await Promise.all([import("pdfjs-dist/legacy/build/pdf.mjs"), import("pdfjs-dist/legacy/build/pdf.worker.min.mjs")]);
39
+ const scope = globalThis as PdfjsGlobal;
40
+ scope.pdfjsWorker ??= worker;
41
+ return {
42
+ async open(data) {
43
+ const task = pdfjs.getDocument({ data: new Uint8Array(data.slice(0)), useSystemFonts: true });
44
+ const document = await task.promise;
45
+ return {
46
+ pageCount: document.numPages,
47
+ async renderPage(pageNumber, canvas, width) {
48
+ const page = await document.getPage(pageNumber);
49
+ const base = page.getViewport({ scale: 1 });
50
+ const ratio = globalThis.devicePixelRatio > 0 ? globalThis.devicePixelRatio : 1;
51
+ const viewport = page.getViewport({ scale: (width / base.width) * ratio });
52
+ canvas.width = Math.floor(viewport.width);
53
+ canvas.height = Math.floor(viewport.height);
54
+ canvas.style.width = `${String(width)}px`;
55
+ canvas.style.height = `${String(Math.floor(viewport.height / ratio))}px`;
56
+ await page.render({ canvas, viewport }).promise;
57
+ },
58
+ destroy() {
59
+ void task.destroy();
60
+ },
61
+ };
62
+ },
63
+ };
64
+ }