@hussmartinez/pdf-sdk 0.4.5 → 0.5.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.
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","names":["LETTER","join","join","join","_Fragment"],"sources":["../src/features/history/history-tools.ts","../src/features/open/open-tool.ts","../src/features/tool-types.ts","../src/features/pages/rotate-tools.ts","../src/features/pages/delete-tool.ts","../src/features/pages/insert-tool.ts","../src/features/pages/move-tools.ts","../src/features/save/download-tool.ts","../src/features/tools.ts","../src/react/context.ts","../src/messages/editor-en.ts","../src/react/editor-messages.ts","../src/react/hooks.ts","../src/react/PdfSessionProvider.tsx","../src/react/scrollbar.ts","../src/react/use-near-observer.ts","../src/react/use-page-drawing.ts","../src/react/viewer/geometry.ts","../src/react/viewer/render-queue.ts","../src/react/thumbnails/PdfThumbnails.tsx","../src/react/toolbar/icons.ts","../src/features/pages/thumbnail-keys.ts","../src/react/toolbar/PdfToolbar.tsx","../src/react/viewer/PdfViewerPage.tsx","../src/react/viewer/PdfViewer.tsx","../src/react/editor/PdfEditorStart.tsx","../src/features/save/download-name.ts","../src/react/editor/use-save.ts","../src/react/editor/PdfEditor.tsx"],"sourcesContent":["import { defineTool } from \"@hussmartinez/sdk-core\";\nimport type { PdfTool } from \"../tool-types.js\";\n\n/** Undoes the last edit (sdk-core ADR 0010). */\nexport const undoTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.undo\",\n label: \"tools.undo\",\n icon: \"undo\",\n group: \"history\",\n isEnabled: ({ snapshot }) => snapshot.canUndo,\n run: ({ session }) => {\n session.undo();\n },\n shortcuts: \"undo\",\n});\n\n/** Redoes the last undone edit. */\nexport const redoTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.redo\",\n label: \"tools.redo\",\n icon: \"redo\",\n group: \"history\",\n isEnabled: ({ snapshot }) => snapshot.canRedo,\n run: ({ session }) => {\n session.redo();\n },\n shortcuts: \"redo\",\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport type { PdfTool } from \"../tool-types.js\";\n\n/** Asks for a PDF and opens it. No shortcut: `Mod+O` is the browser's own. */\nexport const openTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.open\",\n label: \"tools.open\",\n icon: \"open\",\n group: \"file\",\n run: ({ chooseFile }) => chooseFile(),\n});\n","import type { Tool } from \"@hussmartinez/sdk-core\";\nimport type { PdfSession, PdfSessionSnapshot } from \"../core/session/session.js\";\n\n/**\n * What a tool reads to decide whether it's available, enabled or active.\n *\n * @public\n */\nexport interface PdfToolState {\n /** The session's current snapshot. */\n readonly snapshot: PdfSessionSnapshot;\n /** Whether the editor is saving the document. Absent outside the editor. */\n readonly saving?: boolean;\n /** Whether the editor is inserting another document. Absent outside the editor. */\n readonly inserting?: boolean;\n}\n\n/**\n * What a tool runs against.\n *\n * @public\n */\nexport interface PdfToolContext {\n /** The session the tool edits. */\n readonly session: PdfSession;\n /** Asks the user for a PDF and opens it, as the open tool does. */\n readonly chooseFile: () => void;\n /**\n * Builds the document and saves it, as the download tool does\n * (docs/adr/0009). Absent outside the editor.\n */\n readonly save?: () => void;\n /**\n * Asks the user for another PDF and inserts its pages after the current\n * page, as the insert tool does (docs/adr/0008). Absent outside the editor.\n */\n readonly chooseInsertFile?: () => void;\n}\n\n/**\n * One of the editor's tools (sdk-core ADR 0009 and ADR 0030): headless, so\n * the React editor and the custom element share it.\n *\n * @public\n */\nexport type PdfTool = Tool<PdfToolState, PdfToolContext, undefined>;\n\n/** Whether a document is open. */\nexport const hasDocument = ({ snapshot }: PdfToolState): boolean => snapshot.status === \"ready\";\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport type { PdfSessionSnapshot } from \"../../core/session/session.js\";\nimport { hasDocument, type PdfTool, type PdfToolContext } from \"../tool-types.js\";\n\n/**\n * The pages a page tool acts on: the selected pages, or the current page\n * when none is selected. Empty when no document is open.\n */\nexport function targetPages(snapshot: PdfSessionSnapshot): readonly string[] {\n if (snapshot.status !== \"ready\") return [];\n if (snapshot.selection.length > 0) return snapshot.selection;\n return snapshot.currentPage === undefined ? [] : [snapshot.currentPage];\n}\n\nfunction rotate({ session }: PdfToolContext, angle: -90 | 90): void {\n const pages = targetPages(session.getSnapshot());\n if (pages.length === 0) return;\n session.execute({ type: \"pdf.rotatePages\", pages, angle });\n}\n\nconst hasTargets = ({ snapshot }: { snapshot: PdfSessionSnapshot }) =>\n hasDocument({ snapshot }) && targetPages(snapshot).length > 0;\n\n/** Turns the selected pages, or the current one, a quarter turn anticlockwise. */\nexport const rotateLeftTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.rotate-left\",\n label: \"tools.rotate-left\",\n icon: \"rotate-left\",\n group: \"pages\",\n isEnabled: hasTargets,\n run: (context) => rotate(context, -90),\n shortcuts: [\"[\"],\n});\n\n/** Turns the selected pages, or the current one, a quarter turn clockwise. */\nexport const rotateRightTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.rotate-right\",\n label: \"tools.rotate-right\",\n icon: \"rotate-right\",\n group: \"pages\",\n isEnabled: hasTargets,\n run: (context) => rotate(context, 90),\n shortcuts: [\"]\"],\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport {\n hasDocument,\n type PdfTool,\n type PdfToolContext,\n type PdfToolState,\n} from \"../tool-types.js\";\nimport { targetPages } from \"./rotate-tools.js\";\n\n/** Whether deleting the targets would leave at least one page (docs/adr/0008). */\nconst canDelete = ({ snapshot }: PdfToolState): boolean => {\n const targets = targetPages(snapshot).length;\n return hasDocument({ snapshot }) && targets > 0 && targets < snapshot.plan.pages.length;\n};\n\n/**\n * Deletes the selected pages, or the current one, as one undoable step. The\n * page that takes the first deleted page's place, or the new last page,\n * becomes the selection and the current page (docs/adr/0008).\n */\nfunction deletePages({ session }: PdfToolContext): void {\n const before = session.getSnapshot();\n if (!canDelete({ snapshot: before })) return;\n const pages = targetPages(before);\n const removed = new Set(pages);\n const first = before.plan.pages.findIndex((page) => removed.has(page.key));\n session.execute({ type: \"pdf.deletePages\", pages });\n const remaining = session.getSnapshot().plan.pages;\n const next = remaining[Math.min(first, remaining.length - 1)];\n if (!next) return;\n session.select([next.key]);\n session.goToPage(next.key);\n}\n\n/**\n * Deletes the selected pages, or the current one. A document keeps at least\n * one page. Its keys, Delete and Backspace, work in the thumbnails, where\n * the selection is shown, never editor-wide (docs/adr/0008).\n */\nexport const deletePagesTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.delete-pages\",\n label: \"tools.delete-pages\",\n icon: \"delete\",\n group: \"pages\",\n isEnabled: canDelete,\n run: deletePages,\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport { hasDocument, type PdfTool } from \"../tool-types.js\";\n\n/**\n * Asks for another PDF and inserts all its pages after the current page,\n * as one undoable step: how two documents are merged (docs/adr/0008). The\n * file policy applies to the combined document, and a failed insert leaves\n * the document as it was. No shortcut: the picker needs a click or a key\n * press on the button anyway.\n */\nexport const insertPagesTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.insert-pages\",\n label: \"tools.insert-pages\",\n icon: \"page-add\",\n group: \"file\",\n isEnabled: (state) => hasDocument(state) && !state.inserting,\n run: ({ chooseInsertFile }) => chooseInsertFile?.(),\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport type { PdfSessionSnapshot } from \"../../core/session/session.js\";\nimport {\n hasDocument,\n type PdfTool,\n type PdfToolContext,\n type PdfToolState,\n} from \"../tool-types.js\";\nimport { targetPages } from \"./rotate-tools.js\";\n\n/** Which way the move tools move pages. */\nexport type MoveDirection = \"earlier\" | \"later\";\n\n/**\n * The move for the selected pages, or the current one, as `pdf.movePages`'s\n * `pages` and `to`, or `undefined` when there's nothing to move. Pages that\n * aren't next to each other are gathered into one block, in plan order:\n * \"earlier\" puts its first page one position before where it was, and\n * \"later\" puts its last page one position after (docs/adr/0008).\n */\nexport function moveOf(\n snapshot: PdfSessionSnapshot,\n direction: MoveDirection,\n): { readonly pages: readonly string[]; readonly to: number } | undefined {\n if (snapshot.status !== \"ready\") return undefined;\n const chosen = new Set(targetPages(snapshot));\n const order = snapshot.plan.pages.map((page) => page.key);\n const indexes = order.flatMap((key, index) => (chosen.has(key) ? [index] : []));\n const first = indexes[0];\n const last = indexes.at(-1);\n if (first === undefined || last === undefined) return undefined;\n const pages = indexes.map((index) => order[index] as string);\n const block = last - first + 1 === pages.length;\n const others = order.length - pages.length;\n if (direction === \"earlier\") {\n if (block && first === 0) return undefined;\n return { pages, to: Math.max(0, first - 1) };\n }\n if (block && last === order.length - 1) return undefined;\n return { pages, to: Math.min(others, last + 2 - pages.length) };\n}\n\nfunction move({ session }: PdfToolContext, direction: MoveDirection): void {\n const before = session.getSnapshot();\n const found = moveOf(before, direction);\n if (!found) return;\n session.execute({ type: \"pdf.movePages\", pages: found.pages, to: found.to });\n // The moved pages stay chosen, and the current page stays current if it\n // moved, so the user keeps their place (docs/adr/0008).\n session.select(found.pages);\n const current = before.currentPage;\n session.goToPage(\n current !== undefined && found.pages.includes(current) ? current : (found.pages[0] as string),\n );\n}\n\n/**\n * Whether the tool can move pages in `direction`. Tools call it from an arrow\n * of their own rather than being given a function it returns: a call in a\n * tool's definition would keep every tool in a bundle that imports none of\n * them (sdk-core ADR 0056).\n */\nconst canMove = (direction: MoveDirection, { snapshot }: PdfToolState): boolean =>\n hasDocument({ snapshot }) && moveOf(snapshot, direction) !== undefined;\n\n/**\n * Moves the selected pages, or the current one, one position earlier. Its\n * keys, Alt+↑ (Option+↑ on macOS), work in the thumbnails, never\n * editor-wide (docs/adr/0008).\n */\nexport const moveEarlierTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.move-earlier\",\n label: \"tools.move-earlier\",\n icon: \"move-up\",\n group: \"pages\",\n isEnabled: (state) => canMove(\"earlier\", state),\n run: (context) => move(context, \"earlier\"),\n});\n\n/** Moves the selected pages, or the current one, one position later: Alt+↓ in the thumbnails. */\nexport const moveLaterTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.move-later\",\n label: \"tools.move-later\",\n icon: \"move-down\",\n group: \"pages\",\n isEnabled: (state) => canMove(\"later\", state),\n run: (context) => move(context, \"later\"),\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport { hasDocument, type PdfTool } from \"../tool-types.js\";\n\n/**\n * Builds the document and saves it: through the browser as a download, or\n * through the host's `onExport` (docs/adr/0009). No shortcut: Ctrl or ⌘+S\n * stays the browser's. It's disabled while a save runs, so it can't run\n * twice.\n */\nexport const downloadTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.download\",\n label: \"tools.download\",\n icon: \"download\",\n group: \"save\",\n isEnabled: (state) => hasDocument(state) && !state.saving,\n run: ({ save }) => save?.(),\n});\n","import { redoTool, undoTool } from \"./history/history-tools.js\";\nimport { openTool } from \"./open/open-tool.js\";\nimport { deletePagesTool } from \"./pages/delete-tool.js\";\nimport { insertPagesTool } from \"./pages/insert-tool.js\";\nimport { moveEarlierTool, moveLaterTool } from \"./pages/move-tools.js\";\nimport { rotateLeftTool, rotateRightTool } from \"./pages/rotate-tools.js\";\nimport { downloadTool } from \"./save/download-tool.js\";\nimport type { PdfTool } from \"./tool-types.js\";\n\n/**\n * Every tool the editor knows, in their default order (sdk-core ADR 0030).\n *\n * @public\n */\nexport const pdfTools: readonly PdfTool[] = [\n openTool,\n insertPagesTool,\n undoTool,\n redoTool,\n rotateLeftTool,\n rotateRightTool,\n moveEarlierTool,\n moveLaterTool,\n deletePagesTool,\n downloadTool,\n];\n\n/** The toolbar's default groups. */\nexport const DEFAULT_TOOLBAR: readonly (readonly string[])[] = [\n [\"pdf.open\", \"pdf.insert-pages\"],\n [\"pdf.undo\", \"pdf.redo\"],\n [\"pdf.rotate-left\", \"pdf.rotate-right\", \"pdf.move-earlier\", \"pdf.move-later\", \"pdf.delete-pages\"],\n [\"pdf.download\"],\n];\n","import type { Messages } from \"@hussmartinez/sdk-core\";\nimport { createContext } from \"react\";\nimport type { PdfSession } from \"../core/session/session.js\";\nimport type { PdfEditorMessageCatalogue } from \"./editor-messages.js\";\n\n/** What the provider shares with every PDF component below it. */\nexport interface PdfContextValue {\n readonly session: PdfSession;\n readonly messages: Messages<PdfEditorMessageCatalogue>;\n}\n\nexport const PdfContext = /* @__PURE__ */ createContext<PdfContextValue | undefined>(undefined);\n","import { defineMessages, plural } from \"@hussmartinez/sdk-core\";\n\n/**\n * The text of the SDK's interface: the editor, its toolbar and tools, the\n * viewer and the thumbnails. Only the React entry loads it, through\n * `pdfEditorMessages`, so the server-safe entry carries no interface text\n * (docs/adr/0010). Keys use the components' prefixes, never one of ui's\n * (sdk-core ADR 0046).\n */\nexport const pdfEditorText = /* @__PURE__ */ defineMessages({\n \"viewer.label\": \"Document\",\n \"viewer.empty\": \"No document is open.\",\n \"viewer.page\": \"Page {page} of {count}\",\n \"viewer.webLink\": \"Link to {destination}, opens in a new tab\",\n \"viewer.emailLink\": \"Email {destination}\",\n \"thumbnails.label\": \"Pages\",\n \"thumbnails.page\": \"Page {page} of {count}\",\n \"thumbnails.number\": \"{page}\",\n \"editor.label\": \"PDF editor\",\n \"editor.start.title\": \"Open a PDF to get started\",\n \"editor.start.retryTitle\": \"Try another PDF\",\n \"editor.start.choose\": \"Choose a PDF\",\n \"editor.start.retry\": \"Choose another PDF\",\n \"editor.start.hint\": \"Or drop one here. Your file stays on this device and is never uploaded.\",\n \"editor.opening\": \"Opening the PDF…\",\n \"editor.opened\": /* @__PURE__ */ plural(\"count\", {\n one: \"Opened a PDF with {count} page.\",\n other: \"Opened a PDF with {count} pages.\",\n }),\n \"editor.closed\": \"The PDF was closed.\",\n \"editor.undone\": \"Undone.\",\n \"editor.redone\": \"Redone.\",\n \"editor.rotated\": /* @__PURE__ */ plural(\"count\", {\n one: \"Rotated {count} page.\",\n other: \"Rotated {count} pages.\",\n }),\n \"editor.deleted\": /* @__PURE__ */ plural(\"count\", {\n one: \"Deleted {count} page.\",\n other: \"Deleted {count} pages.\",\n }),\n \"editor.moved\": /* @__PURE__ */ plural(\"count\", {\n one: \"Moved {count} page to position {position}.\",\n other: \"Moved {count} pages to position {position}.\",\n }),\n \"editor.inserted\": /* @__PURE__ */ plural(\"count\", {\n one: \"Inserted {count} page after page {page}.\",\n other: \"Inserted {count} pages after page {page}.\",\n }),\n \"editor.historyTrimmed\":\n \"To make room for the inserted document, your earliest edits can no longer be undone.\",\n \"editor.saving\": \"Preparing the PDF…\",\n \"editor.cancelSave\": \"Cancel\",\n \"editor.saved\": \"Saved {name}.\",\n \"editor.ready\": \"The PDF is ready.\",\n \"editor.saveFailed\": \"The PDF couldn't be saved. Please try again.\",\n \"toolbar.label\": \"PDF tools\",\n \"toolbar.groups.file\": \"File\",\n \"toolbar.groups.history\": \"History\",\n \"toolbar.groups.pages\": \"Pages\",\n \"toolbar.groups.save\": \"Save\",\n \"toolbar.groups.other\": \"More tools\",\n \"tools.open\": \"Open a PDF\",\n \"tools.undo\": \"Undo\",\n \"tools.redo\": \"Redo\",\n \"tools.rotate-left\": \"Rotate left\",\n \"tools.rotate-right\": \"Rotate right\",\n \"tools.delete-pages\": \"Delete pages\",\n \"tools.download\": \"Download\",\n \"tools.insert-pages\": \"Insert pages\",\n \"tools.move-earlier\": \"Move earlier\",\n \"tools.move-later\": \"Move later\",\n});\n","import { defineMessages } from \"@hussmartinez/sdk-core\";\nimport { uiMessages } from \"@hussmartinez/ui\";\nimport { pdfEditorText } from \"../messages/editor-en.js\";\nimport { pdfMessages } from \"../messages/en.js\";\n\n/**\n * The English message catalogue of the SDK's components: `pdfMessages`,\n * with sdk-core's text, errors and warnings; `@hussmartinez/ui`'s, for the\n * ui components the editor renders (sdk-core ADR 0046); and the text of the\n * editor, its toolbar and tools, the viewer and the thumbnails.\n *\n * `PdfEditor` and `PdfSessionProvider` each build one `Messages` object from\n * it, with the host's locale and overrides, and the editor gives the same\n * object to its own components and to ui's. Override any of its keys through\n * their `messages` prop, typed with `PdfEditorMessageCatalogue`.\n *\n * It's defined in the React entry, so the server-safe `.` entry and its\n * `pdfMessages` carry no interface text (docs/adr/0010).\n *\n * @public\n */\nexport const pdfEditorMessages = /* @__PURE__ */ defineMessages({\n ...pdfMessages,\n ...uiMessages,\n ...pdfEditorText,\n});\n\n/**\n * The type of {@link pdfEditorMessages}, for typing the editor's `messages`\n * overrides with `MessageOverrides<PdfEditorMessageCatalogue>`.\n *\n * @public\n */\nexport type PdfEditorMessageCatalogue = typeof pdfEditorMessages;\n","import type { Messages } from \"@hussmartinez/sdk-core\";\nimport { useContext, useSyncExternalStore } from \"react\";\nimport type { PdfSession, PdfSessionSnapshot } from \"../core/session/session.js\";\nimport { PdfContext, type PdfContextValue } from \"./context.js\";\nimport type { PdfEditorMessageCatalogue } from \"./editor-messages.js\";\n\nfunction usePdfContext(hook: string): PdfContextValue {\n const value = useContext(PdfContext);\n if (!value) {\n throw new Error(`${hook} must be used inside a PdfSessionProvider.`);\n }\n return value;\n}\n\n/**\n * The session of the nearest `PdfSessionProvider`, to open documents, run\n * commands, undo and export.\n *\n * @public\n */\nexport function usePdfSession(): PdfSession {\n return usePdfContext(\"usePdfSession\").session;\n}\n\n/**\n * The session's current snapshot, re-rendering whenever it changes, through\n * `useSyncExternalStore`, so it's safe with concurrent rendering and server\n * rendering (ADR 0008).\n *\n * @public\n */\nexport function usePdfDocument(): PdfSessionSnapshot {\n const { session } = usePdfContext(\"usePdfDocument\");\n return useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot);\n}\n\n/**\n * The SDK's text for the provider's locale and overrides (ADR 0019).\n *\n * @public\n */\nexport function usePdfMessages(): Messages<PdfEditorMessageCatalogue> {\n return usePdfContext(\"usePdfMessages\").messages;\n}\n","import { createMessages, type MessageOverrides } from \"@hussmartinez/sdk-core\";\nimport { type ReactNode, useEffect, useMemo, useState } from \"react\";\nimport { createPdfJsEngine } from \"../adapters/pdfjs/pdfjs-engine.js\";\nimport { createPdfProcessor } from \"../adapters/qpdf/qpdf-processor.js\";\nimport type { PdfFilePolicyOverrides } from \"../core/errors/pdf-limits.js\";\nimport type { PdfEngine } from \"../core/ports/pdf-engine.js\";\nimport type { PdfProcessor } from \"../core/ports/pdf-processor.js\";\nimport type { PdfSession, PdfSessionEvent } from \"../core/session/session.js\";\nimport { createPdfSession } from \"../core/session/session.js\";\nimport { PdfContext } from \"./context.js\";\nimport { type PdfEditorMessageCatalogue, pdfEditorMessages } from \"./editor-messages.js\";\n\n/**\n * Props for {@link PdfSessionProvider}.\n *\n * @public\n */\nexport interface PdfSessionProviderProps {\n /**\n * A session you created and own. Without it, the provider creates one,\n * with the options below, and closes it when it unmounts. The options are\n * read once, when the provider first renders.\n */\n readonly session?: PdfSession;\n /** The engine for a session the provider creates. Defaults to pdf.js. */\n readonly engine?: PdfEngine;\n /** The processor for a session the provider creates. Defaults to qpdf. */\n readonly processor?: PdfProcessor;\n /**\n * Where your application serves the package's `dist/assets/`, for the\n * default engine and processor (docs/adr/0007). By default, they're inlined.\n */\n readonly assetsUrl?: string | URL;\n /** File limits for a session the provider creates (docs/adr/0004). */\n readonly filePolicy?: PdfFilePolicyOverrides;\n /** Anonymous usage events from a session the provider creates. */\n readonly onEvent?: (event: PdfSessionEvent) => void;\n /** Text overrides, typed against the English catalogue (ADR 0019). */\n readonly messages?: MessageOverrides<PdfEditorMessageCatalogue>;\n /** The locale for numbers, sizes and plurals. Defaults to `\"en\"`. */\n readonly locale?: string;\n /** The components that use the session, such as `PdfViewer`. */\n readonly children?: ReactNode;\n}\n\ninterface Owned {\n readonly session: PdfSession;\n dispose(): void;\n}\n\n/**\n * Creates what the provider owns. Nothing touches the DOM until a document\n * opens, so this is safe during server rendering (ADR 0007).\n */\nfunction own(props: PdfSessionSource): Owned {\n const assets = props.assetsUrl === undefined ? {} : { assetsUrl: props.assetsUrl };\n // A relative assetsUrl, such as \"/pdf-sdk/\", is resolved when a worker\n // starts, in the browser, so this is safe on a server too (sdk-core ADR\n // 0038). A query or fragment throws TypeError as the provider renders.\n const engine = props.engine ?? createPdfJsEngine(assets);\n const processor = props.processor ?? createPdfProcessor(assets);\n const session = createPdfSession({\n engine,\n processor,\n ...(props.filePolicy ? { filePolicy: props.filePolicy } : {}),\n ...(props.onEvent ? { onEvent: props.onEvent } : {}),\n });\n return {\n session,\n dispose() {\n void session.close();\n // Only what the provider created itself is destroyed.\n if (!props.engine) void engine.destroy();\n if (!props.processor) void processor.destroy();\n },\n };\n}\n\n/** What {@link useProvidedSession} reads: the provider's session props. */\nexport type PdfSessionSource = Omit<PdfSessionProviderProps, \"messages\" | \"locale\" | \"children\">;\n\n/**\n * The session a provider gives its components: the one passed in, or one it\n * creates from the options and releases when it unmounts. Shared by\n * `PdfSessionProvider` and `PdfEditor`, which builds its own messages.\n */\nexport function useProvidedSession(props: PdfSessionSource): PdfSession {\n const given = props.session;\n const [owned] = useState(() => (given ? undefined : own(props)));\n\n useEffect(() => {\n if (!owned) return;\n // React's development mode unmounts and mounts again at once, so the\n // disposal waits a tick, and a remount cancels it.\n const pending = (owned as Owned & { pending?: ReturnType<typeof setTimeout> }).pending;\n if (pending !== undefined) clearTimeout(pending);\n return () => {\n (owned as Owned & { pending?: ReturnType<typeof setTimeout> }).pending = setTimeout(\n () => owned.dispose(),\n 0,\n );\n };\n }, [owned]);\n\n return given ?? (owned as Owned).session;\n}\n\n/**\n * Makes a PDF session and the SDK's text available to the components and\n * hooks below it, such as `PdfViewer` and `usePdfDocument` (ADR 0008).\n *\n * @example\n * ```tsx\n * <PdfSessionProvider locale=\"de\" messages={{ \"viewer.empty\": \"Kein Dokument geöffnet.\" }}>\n * <PdfViewer />\n * </PdfSessionProvider>\n * ```\n *\n * @public\n */\nexport function PdfSessionProvider(props: PdfSessionProviderProps): ReactNode {\n const { messages: overrides, locale = \"en\", children } = props;\n const session = useProvidedSession(props);\n const messages = useMemo(\n () =>\n createMessages(pdfEditorMessages, {\n locale,\n ...(overrides ? { overrides } : {}),\n }),\n [locale, overrides],\n );\n const value = useMemo(() => ({ session, messages }), [session, messages]);\n return <PdfContext.Provider value={value}>{children}</PdfContext.Provider>;\n}\n","/**\n * How wide a vertical scrollbar of `container` is, in pixels, measured with a\n * hidden probe inside it, so the page's scrollbar styles and the container's\n * `scrollbar-width` apply. 0 with overlay scrollbars, which take no space.\n */\nexport function scrollbarThickness(container: HTMLElement): number {\n const probe = document.createElement(\"div\");\n probe.style.cssText =\n \"position: absolute; top: 0; left: 0; width: 100px; height: 100px; overflow: scroll; visibility: hidden; pointer-events: none;\";\n probe.style.setProperty(\n \"scrollbar-width\",\n getComputedStyle(container).getPropertyValue(\"scrollbar-width\") || \"auto\",\n );\n container.append(probe);\n const thickness = probe.offsetWidth - probe.clientWidth;\n probe.remove();\n return thickness;\n}\n\n/**\n * The width to lay content out at inside `container`, a scroll container\n * whose content is `measured` pixels wide right now: as if its scrollbar\n * were always shown. Pages sized to a container's width get shorter when a\n * scrollbar that takes space appears; if that makes them fit, it goes, they\n * grow, and it comes back, every frame. Sizing them as if it were always\n * there keeps their width, whether it shows or not.\n */\nexport function steadyWidth(container: HTMLElement, measured: number, thickness: number): number {\n const style = getComputedStyle(container);\n const borders =\n Number.parseFloat(style.borderLeftWidth) + Number.parseFloat(style.borderRightWidth);\n const shown = container.offsetWidth - container.clientWidth - borders;\n return Math.max(0, measured - Math.max(0, thickness - shown));\n}\n","import { type RefObject, useCallback, useEffect, useRef, useState } from \"react\";\n\n/**\n * One `IntersectionObserver` for every page of a scrolling container: a\n * page counts as near within one container height above or below it, so it\n * can be drawn before it scrolls into view. Returns the function pages\n * register with.\n */\nexport function useNearObserver(\n root: RefObject<Element | null>,\n): (element: Element, onNear: (near: boolean) => void) => () => void {\n const observer = useRef<IntersectionObserver>(undefined);\n const callbacks = useRef(new Map<Element, (near: boolean) => void>());\n\n useEffect(() => {\n const created = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) callbacks.current.get(entry.target)?.(entry.isIntersecting);\n },\n { root: root.current, rootMargin: \"100% 0px\" },\n );\n observer.current = created;\n for (const element of callbacks.current.keys()) created.observe(element);\n return () => created.disconnect();\n }, [root]);\n\n return useCallback((element: Element, onNear: (near: boolean) => void) => {\n callbacks.current.set(element, onNear);\n observer.current?.observe(element);\n return () => {\n callbacks.current.delete(element);\n observer.current?.unobserve(element);\n };\n }, []);\n}\n\n/**\n * Whether an element registered with a near observer is near the viewport.\n * It's observed only once `sized` is true, meaning the page placeholders\n * have their real size: before the container's width is known every\n * placeholder is empty, so every page would count as near and start reading\n * and drawing at once. It stops being near when it stops being sized, such\n * as when its container is hidden.\n */\nexport function useNear(\n observe: (element: Element, onNear: (near: boolean) => void) => () => void,\n element: RefObject<Element | null>,\n sized: boolean,\n): boolean {\n const [near, setNear] = useState(false);\n useEffect(() => {\n const target = element.current;\n if (!sized || !target) return;\n const stop = observe(target, setNear);\n return () => {\n stop();\n setNear(false);\n };\n }, [observe, element, sized]);\n return near;\n}\n","import { type RefObject, useEffect, useRef, useState } from \"react\";\nimport type { PdfPageInfo } from \"../core/model/document.js\";\nimport type { PdfSession } from \"../core/session/session.js\";\nimport type { RenderQueue } from \"./viewer/render-queue.js\";\n\n/** What {@link usePageDrawing} needs. */\nexport interface PageDrawingOptions {\n readonly session: PdfSession;\n readonly pageKey: string;\n /** The plan's rotation of the page, so a change re-reads its size. */\n readonly rotation: number;\n /** Whether the page is near the viewport, and should be drawn. */\n readonly near: boolean;\n /** The page's CSS width on screen. */\n readonly displayWidth: number;\n readonly queue: RenderQueue;\n /** Called with the page's size and rotation once they're read. */\n readonly onMeasured?: (info: PdfPageInfo) => void;\n}\n\n/**\n * Shows a finished drawing: the visible canvas takes the buffer's size and\n * pixels in one task, so the browser never paints it cleared.\n */\nfunction present(buffer: HTMLCanvasElement, target: HTMLCanvasElement): void {\n target.width = buffer.width;\n target.height = buffer.height;\n target.style.width = buffer.style.width;\n target.style.height = buffer.style.height;\n target.getContext(\"2d\")?.drawImage(buffer, 0, 0);\n}\n\n/** A page's drawing state. */\nexport interface PageDrawing {\n readonly canvas: RefObject<HTMLCanvasElement | null>;\n readonly info: PdfPageInfo | undefined;\n readonly drawn: boolean;\n readonly failure: unknown;\n}\n\n/**\n * Draws one plan page into a canvas while it's near the viewport (docs/adr/0003):\n * reads its size when it first comes near and when its rotation changes,\n * queues the drawing with the component's other pages, redraws when its\n * size changes, cancels when it leaves, and gives the canvas's pixels back.\n * Shared by the viewer and the thumbnails.\n */\nexport function usePageDrawing(options: PageDrawingOptions): PageDrawing {\n const { session, pageKey, rotation, near, displayWidth, queue, onMeasured } = options;\n const canvas = useRef<HTMLCanvasElement>(null);\n const [info, setInfo] = useState<PdfPageInfo>();\n const [drawn, setDrawn] = useState(false);\n const [failure, setFailure] = useState<unknown>();\n const measured = useRef(onMeasured);\n measured.current = onMeasured;\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: a new rotation must re-read the page\n useEffect(() => {\n if (!near) return;\n const controller = new AbortController();\n session.getPage(pageKey, { signal: controller.signal }).then(\n (read) => {\n setInfo(read);\n measured.current?.(read);\n },\n (reason: unknown) => {\n if (!controller.signal.aborted) setFailure(reason);\n },\n );\n return () => controller.abort();\n }, [near, session, pageKey, rotation]);\n\n useEffect(() => {\n const target = canvas.current;\n if (!near || !info || !target || displayWidth <= 0) return;\n const turned = info.rotation === 90 || info.rotation === 270;\n const scale = displayWidth / (turned ? info.height : info.width);\n const render = queue.schedule(async (signal) => {\n // Drawn off screen, then copied in at once: an engine sizes its canvas\n // when it starts, which clears it, so drawing on screen would show a\n // blank page until the redraw finishes, as when the width settles.\n const buffer = document.createElement(\"canvas\");\n try {\n await session.renderPage(pageKey, buffer, {\n scale,\n pixelRatio: globalThis.devicePixelRatio || 1,\n signal,\n });\n if (!signal.aborted) {\n present(buffer, target);\n setDrawn(true);\n setFailure(undefined);\n }\n } catch (reason) {\n if (!signal.aborted) setFailure(reason);\n } finally {\n // Its pixels are copied or not needed; give them back now.\n buffer.width = 0;\n buffer.height = 0;\n }\n });\n return () => render.cancel();\n }, [near, info, displayWidth, session, pageKey, queue]);\n\n // A page that scrolls away gives its pixels back.\n useEffect(() => {\n if (near) return;\n const target = canvas.current;\n if (target) {\n target.width = 0;\n target.height = 0;\n }\n setDrawn(false);\n }, [near]);\n\n return { canvas, info, drawn, failure };\n}\n","import type { PdfRotation } from \"../../core/model/geometry.js\";\n\n/** A page's box on screen, and how to lay the unrotated page over it. */\nexport interface PageGeometry {\n /** The page's width and height on screen, after rotation, in CSS pixels. */\n readonly width: number;\n readonly height: number;\n /** The unrotated page's width and height, in CSS pixels. */\n readonly pageWidth: number;\n readonly pageHeight: number;\n /**\n * The CSS transform that puts a layer of the unrotated page's size, with\n * its origin at its top-left corner, over the rotated page, so overlays\n * positioned in unrotated page fractions land where the page shows them.\n */\n readonly transform: string;\n}\n\n/**\n * Lays out a page of `width` × `height` points, shown with `rotation`, at a\n * given CSS width.\n */\nexport function pageGeometry(\n size: { readonly width: number; readonly height: number },\n rotation: PdfRotation,\n displayWidth: number,\n): PageGeometry {\n const turned = rotation === 90 || rotation === 270;\n const scale = displayWidth / (turned ? size.height : size.width);\n const pageWidth = size.width * scale;\n const pageHeight = size.height * scale;\n const width = turned ? pageHeight : pageWidth;\n const height = turned ? pageWidth : pageHeight;\n const transform = {\n 0: \"none\",\n 90: `translate(${width}px, 0) rotate(90deg)`,\n 180: `translate(${width}px, ${height}px) rotate(180deg)`,\n 270: `translate(0, ${height}px) rotate(270deg)`,\n }[rotation];\n return { width, height, pageWidth, pageHeight, transform };\n}\n","/** A queued render; cancelling it stops it, whether it's waiting or running. */\nexport interface QueuedRender {\n cancel(): void;\n}\n\ntype Task = (signal: AbortSignal) => Promise<void>;\n\n/**\n * Runs at most `limit` page renders at once. The page asked for last starts\n * first, because it's usually the one the user just scrolled to, and a page\n * that scrolls away is cancelled, whether it's waiting or running.\n */\nexport class RenderQueue {\n readonly #limit: number;\n #running = 0;\n readonly #waiting: { task: Task; controller: AbortController }[] = [];\n\n constructor(limit = 2) {\n this.#limit = Math.max(1, limit);\n }\n\n schedule(task: Task): QueuedRender {\n const entry = { task, controller: new AbortController() };\n this.#waiting.push(entry);\n this.#next();\n return {\n cancel: () => {\n const index = this.#waiting.indexOf(entry);\n if (index >= 0) this.#waiting.splice(index, 1);\n entry.controller.abort();\n },\n };\n }\n\n #next(): void {\n while (this.#running < this.#limit && this.#waiting.length > 0) {\n const entry = this.#waiting.pop() as { task: Task; controller: AbortController };\n this.#running += 1;\n void entry\n .task(entry.controller.signal)\n .catch(() => {})\n .finally(() => {\n this.#running -= 1;\n this.#next();\n });\n }\n }\n}\n","import {\n Component,\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type RefObject,\n useCallback,\n useEffect,\n useId,\n useRef,\n useState,\n} from \"react\";\nimport type { PdfPageInfo } from \"../../core/model/document.js\";\nimport type { PdfPlanPage } from \"../../core/model/plan.js\";\nimport type { PdfSession } from \"../../core/session/session.js\";\nimport { usePdfDocument, usePdfMessages, usePdfSession } from \"../hooks.js\";\nimport { scrollbarThickness, steadyWidth } from \"../scrollbar.js\";\nimport { useNear, useNearObserver } from \"../use-near-observer.js\";\nimport { usePageDrawing } from \"../use-page-drawing.js\";\nimport { pageGeometry } from \"../viewer/geometry.js\";\nimport { RenderQueue } from \"../viewer/render-queue.js\";\n\n/**\n * The parts of `PdfThumbnails` that take extra classes through `classNames`.\n *\n * @public\n */\nexport type PdfThumbnailsPart = \"root\" | \"thumbnail\" | \"frame\" | \"canvas\" | \"number\";\n\n/**\n * Props for {@link PdfThumbnails}.\n *\n * @public\n */\nexport interface PdfThumbnailsProps {\n /** Extra classes on the root. */\n readonly className?: string;\n /** Extra classes on each part. */\n readonly classNames?: Readonly<Partial<Record<PdfThumbnailsPart, string>>>;\n /** Drop the visual styles, keeping layout and accessibility. */\n readonly unstyled?: boolean;\n /** How many thumbnails are drawn at once. Defaults to 2. */\n readonly concurrency?: number;\n /**\n * Runs when the user presses Delete or Backspace in the list, such as the\n * editor's delete tool. Without it, those keys do nothing here.\n */\n readonly onDelete?: () => void;\n /**\n * Runs when the user presses Alt+↑ or Alt+↓ (Option on macOS) in the list,\n * such as the editor's move tools. Without it, those keys do nothing here.\n */\n readonly onMove?: (direction: \"earlier\" | \"later\") => void;\n}\n\nconst LETTER = { width: 612, height: 792 };\n\n/** The key of the thumbnail in `root` that has focus, if one has. */\nfunction focusedThumbnail(root: HTMLElement | null): string | undefined {\n if (!root) return undefined;\n const active = document.activeElement;\n if (!(active instanceof HTMLElement) || !root.contains(active)) return undefined;\n return active.dataset[\"hmPageKey\"];\n}\n\ninterface FocusKeeperProps {\n readonly root: RefObject<HTMLDivElement | null>;\n readonly keys: readonly string[];\n /** Where focus goes if the focused thumbnail left the plan. */\n readonly fallback: string | undefined;\n}\n\n/**\n * Keeps focus in the list when the thumbnail that has it is moved, which\n * takes focus from it in some browsers, or leaves the plan: deleted, or\n * undone (docs/adr/0008). Focus goes back to it, or to the current page's\n * thumbnail, never to the page's body.\n *\n * A class, for `getSnapshotBeforeUpdate`: React calls it for the whole tree\n * before a commit changes the DOM, so it reads which thumbnail had focus\n * without reading the DOM or writing a ref during render. It covers every\n * way a thumbnail can move or go: keys, the toolbar, undo and the host's\n * own calls. If focus was elsewhere, such as on the host's page, nothing\n * was recorded and nothing is taken back. It renders nothing.\n */\nclass FocusKeeper extends Component<FocusKeeperProps> {\n override getSnapshotBeforeUpdate(): string | null {\n return focusedThumbnail(this.props.root.current) ?? null;\n }\n\n override componentDidUpdate(\n _props: FocusKeeperProps,\n _state: unknown,\n focused: string | null,\n ): void {\n const element = this.props.root.current;\n if (!focused || !element) return;\n const now = document.activeElement;\n if (now !== null && now !== document.body) return;\n const target = this.props.keys.includes(focused) ? focused : this.props.fallback;\n if (!target) return;\n element.querySelector<HTMLElement>(`[data-hm-page-key=\"${CSS.escape(target)}\"]`)?.focus();\n }\n\n override render(): null {\n return null;\n }\n}\nconst join = (...names: (string | undefined)[]) => names.filter(Boolean).join(\" \");\n\ninterface ThumbnailProps {\n readonly page: PdfPlanPage;\n readonly index: number;\n readonly count: number;\n readonly id: string;\n readonly selected: boolean;\n readonly current: boolean;\n readonly active: boolean;\n readonly displayWidth: number;\n readonly estimate: { readonly width: number; readonly height: number };\n readonly observe: (element: Element, onNear: (near: boolean) => void) => () => void;\n readonly queue: RenderQueue;\n readonly session: PdfSession;\n readonly onMeasured: (info: PdfPageInfo) => void;\n readonly onPointer: (index: number, event: MouseEvent) => void;\n readonly classNames: Readonly<Partial<Record<PdfThumbnailsPart, string>>>;\n}\n\nfunction Thumbnail(props: ThumbnailProps): ReactNode {\n const { page, index, count, id, selected, current, active, displayWidth, classNames } = props;\n const messages = usePdfMessages();\n const element = useRef<HTMLDivElement>(null);\n const near = useNear(props.observe, element, displayWidth > 0);\n const { canvas, info, drawn } = usePageDrawing({\n session: props.session,\n pageKey: page.key,\n rotation: page.rotation,\n near,\n displayWidth,\n queue: props.queue,\n onMeasured: props.onMeasured,\n });\n const geometry = pageGeometry(info ?? { ...props.estimate }, info?.rotation ?? 0, displayWidth);\n\n return (\n // The listbox handles the keyboard for every option (ADR 0014), as the\n // WAI-ARIA listbox pattern does with roving focus.\n // biome-ignore lint/a11y/useKeyWithClickEvents: the parent listbox handles keys for its options\n <div\n ref={element}\n id={id}\n role=\"option\"\n aria-selected={selected}\n aria-current={current ? \"true\" : undefined}\n aria-label={messages.t(\"thumbnails.page\", { page: index + 1, count })}\n aria-busy={near && !drawn}\n tabIndex={active ? 0 : -1}\n className={join(\"hm-pdf-thumbnail\", classNames.thumbnail)}\n data-hm-page-key={page.key}\n onClick={(event) => props.onPointer(index, event)}\n >\n <div\n className={join(\"hm-pdf-thumbnail-frame\", classNames.frame)}\n style={{ width: `${geometry.width}px`, height: `${geometry.height}px` }}\n >\n {/* biome-ignore lint/a11y/noAriaHiddenOnFocusable: the canvas is pixels only and never focusable */}\n <canvas\n ref={canvas}\n aria-hidden=\"true\"\n className={join(\"hm-pdf-thumbnail-canvas\", classNames.canvas)}\n />\n </div>\n <span aria-hidden=\"true\" className={join(\"hm-pdf-thumbnail-number\", classNames.number)}>\n {messages.t(\"thumbnails.number\", { page: index + 1 })}\n </span>\n </div>\n );\n}\n\n/**\n * A column of page thumbnails to see the whole document and choose pages\n * (ADR 0014): a listbox with several pages selectable, where the selection\n * follows focus and the chosen page is brought into view in `PdfViewer`.\n * Like the viewer, it only draws the thumbnails near its viewport.\n *\n * Keyboard: the arrow keys, Home and End move to a page, select it and show\n * it; with Shift they extend the selection; with Ctrl or ⌘ they move without\n * selecting, and Space then adds or removes the page. Ctrl or ⌘ + A selects\n * every page, and Escape keeps only the focused one. Delete and Backspace,\n * and Alt or Option with ↑ and ↓, run `onDelete` and `onMove` when given.\n * With a pointer: click,\n * Ctrl or ⌘ + click, and Shift + click.\n *\n * @public\n */\nexport function PdfThumbnails(props: PdfThumbnailsProps): ReactNode {\n const { className, classNames = {}, unstyled = false, concurrency = 2, onDelete, onMove } = props;\n const session = usePdfSession();\n const snapshot = usePdfDocument();\n const messages = usePdfMessages();\n const root = useRef<HTMLDivElement>(null);\n const prefix = useId();\n const observe = useNearObserver(root);\n const [queue] = useState(() => new RenderQueue(concurrency));\n const [width, setWidth] = useState(0);\n const [estimate, setEstimate] = useState(LETTER);\n const [activeKey, setActiveKey] = useState<string>();\n const anchor = useRef<string | undefined>(undefined);\n const { plan, selection, currentPage } = snapshot;\n const keys = plan.pages.map((page) => page.key);\n const active = activeKey && keys.includes(activeKey) ? activeKey : (currentPage ?? keys[0]);\n const activeIndex = active ? keys.indexOf(active) : -1;\n\n useEffect(() => {\n const element = root.current;\n if (!element) return;\n // Sized as if a scrollbar were shown, so one coming and going doesn't\n // resize the thumbnails, and with them the list, every frame.\n const thickness = scrollbarThickness(element);\n const observer = new ResizeObserver(([entry]) => {\n if (entry) setWidth(steadyWidth(element, entry.contentRect.width, thickness));\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n\n // Follows the viewer: the current page's thumbnail scrolls into view,\n // unless the user is working in this list.\n useEffect(() => {\n const element = root.current;\n if (!element || !currentPage || element.contains(document.activeElement)) return;\n element\n .querySelector<HTMLElement>(`[data-hm-page-key=\"${CSS.escape(currentPage)}\"]`)\n ?.scrollIntoView({ block: \"nearest\" });\n }, [currentPage]);\n\n const onMeasured = useCallback((info: PdfPageInfo) => {\n setEstimate((current) =>\n current === LETTER ? { width: info.width, height: info.height } : current,\n );\n }, []);\n\n const focus = (index: number) => {\n const key = keys[index];\n if (!key) return;\n setActiveKey(key);\n root.current?.querySelector<HTMLElement>(`[data-hm-page-key=\"${CSS.escape(key)}\"]`)?.focus();\n };\n\n /** Selects from the anchor to `index`, or `index` alone, and shows the page. */\n const choose = (index: number, mode: \"only\" | \"range\" | \"toggle\" | \"focus\") => {\n const key = keys[index];\n if (!key) return;\n focus(index);\n if (mode === \"focus\") return;\n if (mode === \"toggle\") {\n session.select(\n selection.includes(key) ? selection.filter((k) => k !== key) : [...selection, key],\n );\n anchor.current = key;\n return;\n }\n if (mode === \"range\" && anchor.current && keys.includes(anchor.current)) {\n const from = keys.indexOf(anchor.current);\n const [start, end] = from < index ? [from, index] : [index, from];\n session.select(keys.slice(start, end + 1));\n } else {\n session.select([key]);\n anchor.current = key;\n }\n session.goToPage(key);\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n if (keys.length === 0) return;\n const modifier = event.ctrlKey || event.metaKey;\n // Alt or Option with ↑ or ↓ moves pages, and never moves focus.\n if (event.altKey && (event.key === \"ArrowUp\" || event.key === \"ArrowDown\")) {\n if (onMove && !modifier && !event.shiftKey) {\n event.preventDefault();\n onMove(event.key === \"ArrowUp\" ? \"earlier\" : \"later\");\n }\n return;\n }\n const move = (index: number) => {\n event.preventDefault();\n const target = Math.max(0, Math.min(keys.length - 1, index));\n choose(target, event.shiftKey ? \"range\" : modifier ? \"focus\" : \"only\");\n };\n switch (event.key) {\n case \"ArrowDown\":\n case \"ArrowRight\":\n move(activeIndex + 1);\n break;\n case \"ArrowUp\":\n case \"ArrowLeft\":\n move(activeIndex - 1);\n break;\n case \"Home\":\n move(0);\n break;\n case \"End\":\n move(keys.length - 1);\n break;\n case \" \":\n event.preventDefault();\n if (activeIndex >= 0) choose(activeIndex, \"toggle\");\n break;\n case \"Escape\":\n if (active) session.select([active]);\n break;\n case \"Delete\":\n case \"Backspace\":\n if (onDelete && !event.altKey && !modifier && !event.shiftKey) {\n event.preventDefault();\n onDelete();\n }\n break;\n case \"a\":\n case \"A\":\n if (modifier) {\n event.preventDefault();\n session.select(keys);\n }\n break;\n }\n };\n\n const onPointer = (index: number, event: MouseEvent) => {\n choose(index, event.shiftKey ? \"range\" : event.ctrlKey || event.metaKey ? \"toggle\" : \"only\");\n };\n\n return (\n <div\n ref={root}\n role=\"listbox\"\n aria-label={messages.t(\"thumbnails.label\")}\n aria-multiselectable=\"true\"\n aria-orientation=\"vertical\"\n tabIndex={keys.length === 0 ? 0 : -1}\n onKeyDown={onKeyDown}\n className={join(\"hm-pdf-thumbnails\", className, classNames.root)}\n {...(unstyled ? { \"data-hm-unstyled\": \"\" } : {})}\n >\n {plan.pages.map((page, index) => (\n <Thumbnail\n key={page.key}\n page={page}\n index={index}\n count={keys.length}\n id={`${prefix}-${page.key}`}\n selected={selection.includes(page.key)}\n current={page.key === currentPage}\n active={page.key === active}\n displayWidth={width}\n estimate={estimate}\n observe={observe}\n queue={queue}\n session={session}\n onMeasured={onMeasured}\n onPointer={onPointer}\n classNames={classNames}\n />\n ))}\n <FocusKeeper root={root} keys={keys} fallback={active} />\n </div>\n );\n}\n","import {\n DeleteIcon,\n DownloadIcon,\n type IconComponent,\n MoveDownIcon,\n MoveUpIcon,\n OpenIcon,\n PageAddIcon,\n RedoIcon,\n RotateLeftIcon,\n RotateRightIcon,\n UndoIcon,\n} from \"@hussmartinez/ui/react\";\n\n/**\n * The components of the icons the editor's tools name, from ui's set\n * (sdk-core ADR 0030). A host's `icons` prop overrides any of them.\n *\n * @public\n */\nexport const pdfIcons: Readonly<Record<string, IconComponent>> = {\n open: OpenIcon,\n undo: UndoIcon,\n redo: RedoIcon,\n \"rotate-left\": RotateLeftIcon,\n \"rotate-right\": RotateRightIcon,\n delete: DeleteIcon,\n download: DownloadIcon,\n \"page-add\": PageAddIcon,\n \"move-up\": MoveUpIcon,\n \"move-down\": MoveDownIcon,\n};\n","/**\n * Keys that run a tool only while focus is in the thumbnails, where the\n * selection is shown, by tool ID, as `aria-keyshortcuts` gives them. The\n * toolbar advertises them on the tools' buttons; the tools register no\n * editor-wide shortcut (docs/adr/0008).\n */\nexport const THUMBNAIL_KEYS: Readonly<Record<string, string>> = {\n \"pdf.delete-pages\": \"Delete Backspace\",\n \"pdf.move-earlier\": \"Alt+ArrowUp\",\n \"pdf.move-later\": \"Alt+ArrowDown\",\n};\n","import type { ShortcutRegistry, ToolRegistry } from \"@hussmartinez/sdk-core\";\nimport { IconButton, type IconComponent, Toolbar, ToolbarGroup } from \"@hussmartinez/ui/react\";\nimport type { ReactNode } from \"react\";\nimport { THUMBNAIL_KEYS } from \"../../features/pages/thumbnail-keys.js\";\nimport type { PdfTool, PdfToolContext } from \"../../features/tool-types.js\";\nimport { usePdfDocument, usePdfMessages } from \"../hooks.js\";\n\n/**\n * Props for {@link PdfToolbar}.\n *\n * @public\n */\nexport interface PdfToolbarProps {\n /** The editor's tools, from `createToolRegistry`. */\n readonly registry: ToolRegistry<PdfTool>;\n /** The editor's shortcuts, for each button's `aria-keyshortcuts`. */\n readonly shortcuts?: ShortcutRegistry;\n /** What the tools run against. */\n readonly context: PdfToolContext;\n /** Icon components by name. */\n readonly icons: Readonly<Record<string, IconComponent>>;\n /** Whether the editor is saving, which tools read as `saving`. */\n readonly saving?: boolean;\n /** Whether the editor is inserting a document, which tools read as `inserting`. */\n readonly inserting?: boolean;\n /** Runs a tool. Defaults to running it against `context`. */\n readonly onRun?: (tool: PdfTool) => void;\n /** Extra classes on the root. */\n readonly className?: string;\n}\n\n/**\n * The editor's toolbar: ui's `Toolbar`, one labelled group per toolbar group\n * of the registry and one button per tool, disabled when the tool can't\n * run, with the tool's shortcuts as `aria-keyshortcuts`. Arrow keys move\n * between the buttons, as ui's toolbar does, so it's one tab stop.\n *\n * @public\n */\nexport function PdfToolbar(props: PdfToolbarProps): ReactNode {\n const {\n registry,\n shortcuts,\n context,\n icons,\n onRun,\n className,\n saving = false,\n inserting = false,\n } = props;\n const messages = usePdfMessages();\n const snapshot = usePdfDocument();\n const state = { snapshot, saving, inserting };\n // Tool labels and group names are keys of the catalogue, checked when the\n // tool is defined; custom keys a host adds fall back to the key itself.\n const t = messages.t as (key: string) => string;\n const run = onRun ?? ((tool: PdfTool) => void tool.run(context));\n if (registry.toolbar.length === 0) return null;\n return (\n <Toolbar label={messages.t(\"toolbar.label\")} {...(className ? { className } : {})}>\n {registry.toolbar.map((group) => (\n <ToolbarGroup\n key={group.map((tool) => tool.id).join(\" \")}\n label={t(`toolbar.groups.${group[0]?.group ?? \"other\"}`)}\n >\n {group\n .filter((tool) => tool.isAvailable?.(state) ?? true)\n .map((tool) => {\n const Icon = icons[tool.icon];\n const keys = shortcuts?.ariaKeyShortcuts(tool.id) ?? THUMBNAIL_KEYS[tool.id];\n return (\n <IconButton\n key={tool.id}\n data-hm-tool={tool.id}\n label={t(tool.label)}\n icon={Icon ? <Icon /> : null}\n disabled={!(tool.isEnabled?.(state) ?? true)}\n // A button that becomes disabled keeps focus, so keyboard\n // users stay in the toolbar (docs/adr/0008).\n focusableWhenDisabled\n {...(keys ? { \"aria-keyshortcuts\": keys } : {})}\n onClick={() => run(tool)}\n />\n );\n })}\n </ToolbarGroup>\n ))}\n </Toolbar>\n );\n}\n","import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport type { PdfLink, PdfPageInfo, PdfTextContent } from \"../../core/model/document.js\";\nimport { linkDestination, safeLinkUrl } from \"../../core/model/links.js\";\nimport type { PdfPlanPage } from \"../../core/model/plan.js\";\nimport { usePdfMessages, usePdfSession } from \"../hooks.js\";\nimport { useNear } from \"../use-near-observer.js\";\nimport { usePageDrawing } from \"../use-page-drawing.js\";\nimport { pageGeometry } from \"./geometry.js\";\nimport type { RenderQueue } from \"./render-queue.js\";\nimport type { PdfViewerClassNames } from \"./types.js\";\n\nexport interface PageProps {\n readonly page: PdfPlanPage;\n readonly number: number;\n readonly count: number;\n /** The page's CSS width on screen. */\n readonly displayWidth: number;\n /** A page size to lay out with until this page's own is known. */\n readonly estimate: { readonly width: number; readonly height: number };\n readonly observe: (element: Element, onNear: (near: boolean) => void) => () => void;\n readonly queue: RenderQueue;\n readonly onMeasured: (info: PdfPageInfo) => void;\n readonly classNames: PdfViewerClassNames;\n}\n\nconst join = (...names: (string | undefined)[]) => names.filter(Boolean).join(\" \");\n\n/** One page: a placeholder of the right size, drawn only while near the viewport. */\nexport function PdfViewerPage(props: PageProps): ReactNode {\n const { page, number, count, displayWidth, estimate, observe, queue, onMeasured, classNames } =\n props;\n const session = usePdfSession();\n const messages = usePdfMessages();\n const element = useRef<HTMLDivElement>(null);\n const textLayer = useRef<HTMLDivElement>(null);\n const near = useNear(observe, element, displayWidth > 0);\n const [text, setText] = useState<PdfTextContent>();\n const [links, setLinks] = useState<readonly PdfLink[]>([]);\n const { canvas, info, drawn, failure } = usePageDrawing({\n session,\n pageKey: page.key,\n rotation: page.rotation,\n near,\n displayWidth,\n queue,\n onMeasured,\n });\n\n // The text and links, which don't depend on the zoom, read once.\n useEffect(() => {\n if (!near || text) return;\n const controller = new AbortController();\n const signal = controller.signal;\n Promise.all([\n session.getTextContent(page.key, { signal }),\n session.getLinks(page.key, { signal }),\n ]).then(\n ([content, found]) => {\n setText(content);\n setLinks(found);\n },\n () => {},\n );\n return () => controller.abort();\n }, [near, session, page.key, text]);\n\n const size = info ?? { ...estimate, rotation: 0 };\n const geometry = pageGeometry(size, info?.rotation ?? 0, displayWidth);\n\n // Each run of text is stretched to the width the document gives it, so\n // selections line up with the drawn glyphs.\n useLayoutEffect(() => {\n const layer = textLayer.current;\n if (!layer || !text) return;\n for (const span of layer.querySelectorAll<HTMLElement>(\"[data-hm-width]\")) {\n span.style.transform = \"\";\n const natural = span.getBoundingClientRect().width;\n const wanted = Number(span.dataset[\"hmWidth\"]) * geometry.pageWidth;\n if (natural > 0 && wanted > 0) span.style.transform = `scaleX(${wanted / natural})`;\n }\n }, [text, geometry.pageWidth]);\n\n const overlay = {\n width: `${geometry.pageWidth}px`,\n height: `${geometry.pageHeight}px`,\n transform: geometry.transform,\n };\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a page is a labelled group, not a form fieldset\n <div\n ref={element}\n role=\"group\"\n aria-label={messages.t(\"viewer.page\", { page: number, count })}\n aria-busy={near && !drawn && !failure}\n className={join(\"hm-pdf-page\", classNames.page)}\n data-hm-page-key={page.key}\n style={{ width: `${geometry.width}px`, height: `${geometry.height}px` }}\n >\n {/* biome-ignore lint/a11y/noAriaHiddenOnFocusable: the canvas is pixels only and never focusable; the text layer carries the words */}\n <canvas\n ref={canvas}\n aria-hidden=\"true\"\n className={join(\"hm-pdf-page-canvas\", classNames.canvas)}\n />\n {failure !== undefined ? (\n <p role=\"alert\" className={join(\"hm-pdf-page-error\", classNames.error)}>\n {messages.error(failure)}\n </p>\n ) : null}\n {near && text ? (\n <div\n ref={textLayer}\n className={join(\"hm-pdf-text-layer\", classNames.textLayer)}\n style={overlay}\n >\n {text.items.map((item, index) => (\n <span\n // The items of a page never change order.\n // biome-ignore lint/suspicious/noArrayIndexKey: the index is the item's identity\n key={index}\n data-hm-width={item.rect.width}\n style={{\n left: `${item.rect.x * 100}%`,\n top: `${item.rect.y * 100}%`,\n fontSize: `${item.rect.height * geometry.pageHeight}px`,\n lineHeight: 1,\n }}\n >\n {item.text}\n {item.endOfLine ? \"\\n\" : \"\"}\n </span>\n ))}\n </div>\n ) : null}\n {near && links.length > 0 ? (\n <div className={join(\"hm-pdf-link-layer\", classNames.linkLayer)} style={overlay}>\n {links.map((link, index) => {\n // Checked again here, whatever the engine is (ADR 0012).\n const href = safeLinkUrl(link.url);\n const destination = href && linkDestination(href);\n if (!href || !destination) return null;\n const email = href.startsWith(\"mailto:\");\n const label = email\n ? messages.t(\"viewer.emailLink\", { destination })\n : messages.t(\"viewer.webLink\", { destination });\n return (\n <a\n // biome-ignore lint/suspicious/noArrayIndexKey: links of a page never change order\n key={index}\n className={join(\"hm-pdf-link\", classNames.link)}\n href={href}\n target={email ? undefined : \"_blank\"}\n rel=\"noopener noreferrer\"\n referrerPolicy=\"no-referrer\"\n title={label}\n style={{\n left: `${link.rect.x * 100}%`,\n top: `${link.rect.y * 100}%`,\n width: `${link.rect.width * 100}%`,\n height: `${link.rect.height * 100}%`,\n }}\n >\n {/* The name says where the link really goes, whatever the page shows. */}\n <span className=\"hm-pdf-link-label\">{label}</span>\n </a>\n );\n })}\n </div>\n ) : null}\n </div>\n );\n}\n","import { type ReactNode, useCallback, useEffect, useRef, useState } from \"react\";\nimport type { PdfPageInfo } from \"../../core/model/document.js\";\nimport { usePdfDocument, usePdfMessages, usePdfSession } from \"../hooks.js\";\nimport { scrollbarThickness, steadyWidth } from \"../scrollbar.js\";\nimport { useNearObserver } from \"../use-near-observer.js\";\nimport { PdfViewerPage } from \"./PdfViewerPage.js\";\nimport { RenderQueue } from \"./render-queue.js\";\nimport type { PdfViewerClassNames } from \"./types.js\";\n\n/**\n * Props for {@link PdfViewer}.\n *\n * @public\n */\nexport interface PdfViewerProps {\n /** Extra classes on the root. */\n readonly className?: string;\n /** Extra classes on each part. */\n readonly classNames?: PdfViewerClassNames;\n /** Drop the visual styles, keeping layout and accessibility. */\n readonly unstyled?: boolean;\n /** Page width relative to the viewer's width. Defaults to 1, fitting the width. */\n readonly zoom?: number;\n /** How many page renders run at once. Defaults to 2. */\n readonly concurrency?: number;\n}\n\n/** US Letter, until the first page's size is known. */\nconst LETTER = { width: 612, height: 792 };\n\nconst join = (...names: (string | undefined)[]) => names.filter(Boolean).join(\" \");\n\n/**\n * Shows the session's pages in a scrolling column (docs/adr/0003): each page\n * keeps its place at the right size, and only pages near the viewport are\n * drawn, a few at a time. Pages that scroll away are cancelled or give their\n * pixels back. The text is selectable, for copying and for screen readers,\n * and links are real links, limited to safe URLs and labelled with where\n * they lead (ADR 0012, ADR 0014).\n *\n * The viewer is a focusable region, so keyboard users scroll it with the\n * arrow, Page Up, Page Down, Home and End keys.\n *\n * @public\n */\nexport function PdfViewer(props: PdfViewerProps): ReactNode {\n const { className, classNames = {}, unstyled = false, zoom = 1, concurrency = 2 } = props;\n const snapshot = usePdfDocument();\n const messages = usePdfMessages();\n const root = useRef<HTMLElement>(null);\n const pages = useRef<HTMLDivElement>(null);\n const [width, setWidth] = useState(0);\n const [estimate, setEstimate] = useState(LETTER);\n const [queue] = useState(() => new RenderQueue(concurrency));\n const observe = useNearObserver(root);\n const session = usePdfSession();\n\n // Scroll anchoring, the same in every engine (WebKit has none of its own):\n // the page at the top of the viewer stays where it is on screen while\n // sizes above it change, as placeholders take their real size and the\n // first page measured replaces the estimate. A navigation sets the anchor\n // to its page, so it lands on that page however late sizes arrive.\n const anchor = useRef<{ key: string; offset: number }>(undefined);\n // The scroll position the viewer set itself, so its own scrolls don't\n // move the anchor; only the user's do.\n const own = useRef<number>(undefined);\n // The scroll position the anchor was taken at. A different one means the\n // user scrolled since, and the anchor is out of date until it's measured.\n const anchoredAt = useRef<number>(undefined);\n\n const findPage = useCallback(\n (key: string) =>\n root.current?.querySelector<HTMLElement>(`[data-hm-page-key=\"${CSS.escape(key)}\"]`) ??\n undefined,\n [],\n );\n\n const scrollOwn = useCallback((element: HTMLElement, top: number) => {\n element.scrollTop = top;\n own.current = element.scrollTop;\n anchoredAt.current = element.scrollTop;\n }, []);\n\n useEffect(() => {\n const element = pages.current;\n if (!element) return;\n // Runs after layout and before paint, so a restored position never shows\n // the shifted one first.\n // Pages are sized as if the viewer's scrollbar were shown, so one coming\n // and going doesn't resize them, and with them the pages, every frame.\n const viewerElement = root.current;\n const thickness = viewerElement ? scrollbarThickness(viewerElement) : 0;\n const observer = new ResizeObserver(([entry]) => {\n if (entry) {\n setWidth(\n viewerElement\n ? steadyWidth(viewerElement, entry.contentRect.width, thickness)\n : entry.contentRect.width,\n );\n }\n const viewer = root.current;\n const held = anchor.current;\n if (!viewer || !held) return;\n // A scroll since the anchor was taken, not yet measured, is the user's:\n // restoring the anchor would undo it. Scrolling is measured once per\n // frame, and a resize can be reported before that frame. A position the browser clamped because the pages got\n // shorter isn't the user's, so the anchor still applies then.\n const at = anchoredAt.current;\n const bottom = viewer.scrollHeight - viewer.clientHeight;\n const clamped = at !== undefined && at > bottom && Math.abs(viewer.scrollTop - bottom) < 1;\n if (at !== undefined && Math.abs(viewer.scrollTop - at) >= 1 && !clamped) return;\n const page = findPage(held.key);\n if (!page) {\n anchor.current = undefined;\n return;\n }\n const top = page.offsetTop - held.offset;\n if (Math.abs(viewer.scrollTop - top) >= 1) scrollOwn(viewer, top);\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, [findPage, scrollOwn]);\n\n // The current page follows scrolling: the last page whose top has passed a\n // third of the way down the viewer. The anchor follows the user's\n // scrolling: the last page whose top is at or above the viewer's top.\n // Measured once per animation frame.\n useEffect(() => {\n const element = root.current;\n if (!element) return;\n let frame = 0;\n const measure = () => {\n frame = 0;\n const { scrollTop } = element;\n const line = scrollTop + element.clientHeight / 3;\n const user = own.current === undefined || Math.abs(scrollTop - own.current) >= 1;\n let current: HTMLElement | undefined;\n let top: HTMLElement | undefined;\n for (const page of element.querySelectorAll<HTMLElement>(\"[data-hm-page-key]\")) {\n if (page.offsetTop > line) break;\n current = page;\n if (page.offsetTop <= scrollTop || !top) top = page;\n }\n if (user) {\n own.current = undefined;\n anchor.current = top && {\n key: top.dataset[\"hmPageKey\"] as string,\n offset: top.offsetTop - scrollTop,\n };\n anchoredAt.current = scrollTop;\n }\n const key = current?.dataset[\"hmPageKey\"];\n if (key) session.setCurrentPage(key);\n };\n const onScroll = () => {\n frame ||= requestAnimationFrame(measure);\n };\n element.addEventListener(\"scroll\", onScroll, { passive: true });\n return () => {\n element.removeEventListener(\"scroll\", onScroll);\n cancelAnimationFrame(frame);\n };\n }, [session]);\n\n // A navigation request scrolls its page to the top, at once, which also\n // suits reduced motion, and anchors it there. Only a new request scrolls:\n // every snapshot has a new navigation object, but the same sequence number.\n const sequence = snapshot.navigation?.sequence;\n const target = snapshot.navigation?.page;\n useEffect(() => {\n const element = root.current;\n if (!element || sequence === undefined || target === undefined) return;\n const page = findPage(target);\n if (!page) return;\n const inset = Number.parseFloat(getComputedStyle(pages.current as Element).paddingTop) || 0;\n anchor.current = { key: target, offset: inset };\n scrollOwn(element, page.offsetTop - inset);\n }, [sequence, target, findPage, scrollOwn]);\n\n const onMeasured = useCallback((info: PdfPageInfo) => {\n setEstimate((current) =>\n current === LETTER ? { width: info.width, height: info.height } : current,\n );\n }, []);\n\n const { plan } = snapshot;\n const displayWidth = Math.max(0, width * zoom);\n\n return (\n <section\n ref={root}\n // A scrollable region keyboard users can focus (ADR 0014).\n // biome-ignore lint/a11y/noNoninteractiveTabindex: the region scrolls, so it must take focus\n tabIndex={0}\n aria-label={messages.t(\"viewer.label\")}\n className={join(\"hm-pdf-viewer\", className, classNames.root)}\n {...(unstyled ? { \"data-hm-unstyled\": \"\" } : {})}\n >\n <div ref={pages} className={join(\"hm-pdf-viewer-pages\", classNames.pages)}>\n {plan.pages.length === 0 ? (\n <p className={join(\"hm-pdf-viewer-empty\", classNames.empty)}>\n {messages.t(\"viewer.empty\")}\n </p>\n ) : (\n plan.pages.map((page, index) => (\n <PdfViewerPage\n key={page.key}\n page={page}\n number={index + 1}\n count={plan.pages.length}\n displayWidth={displayWidth}\n estimate={estimate}\n observe={observe}\n queue={queue}\n onMeasured={onMeasured}\n classNames={classNames}\n />\n ))\n )}\n </div>\n </section>\n );\n}\n","import {\n type ChangeEvent,\n type DragEvent,\n type ReactNode,\n type RefObject,\n useId,\n useRef,\n useState,\n} from \"react\";\nimport type { PdfError } from \"../../core/errors/pdf-error.js\";\nimport { usePdfMessages } from \"../hooks.js\";\n\ninterface StartProps {\n readonly error: PdfError | undefined;\n readonly onFile: (file: File) => void;\n readonly button: RefObject<HTMLButtonElement | null>;\n readonly className: string;\n readonly alertClassName: string;\n}\n\nconst hasFiles = (event: DragEvent) => event.dataTransfer.types.includes(\"Files\");\n\n/**\n * What the editor shows with no document open: a button that opens the\n * system's file picker, a drop zone around it, and the reason the last open\n * failed, if it did. The button is the keyboard and screen reader path; the\n * drop zone is a shortcut for pointer users, so it isn't focusable itself.\n */\nexport function PdfEditorStart(props: StartProps): ReactNode {\n const { error, onFile, button, className, alertClassName } = props;\n const messages = usePdfMessages();\n const input = useRef<HTMLInputElement>(null);\n const [dragging, setDragging] = useState(false);\n const titleId = useId();\n const hintId = useId();\n\n const choose = (event: ChangeEvent<HTMLInputElement>) => {\n const [file] = event.target.files ?? [];\n // Cleared so choosing the same file again still opens it.\n event.target.value = \"\";\n if (file) onFile(file);\n };\n\n const onDragOver = (event: DragEvent) => {\n if (!hasFiles(event)) return;\n event.preventDefault();\n event.dataTransfer.dropEffect = \"copy\";\n setDragging(true);\n };\n\n const onDragLeave = (event: DragEvent) => {\n // Leaving for a child isn't leaving the zone.\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;\n setDragging(false);\n };\n\n const onDrop = (event: DragEvent) => {\n if (!hasFiles(event)) return;\n event.preventDefault();\n setDragging(false);\n const [file] = event.dataTransfer.files;\n if (file) onFile(file);\n };\n\n return (\n // The zone is a pointer shortcut only: the button opens the same picker.\n // biome-ignore lint/a11y/noStaticElementInteractions: drop targets have no keyboard role; the button is the accessible path\n <div\n className={className}\n data-hm-dragging={dragging ? \"\" : undefined}\n onDragEnter={onDragOver}\n onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\n >\n <p id={titleId} className=\"hm-pdf-editor-start-title\">\n {messages.t(error ? \"editor.start.retryTitle\" : \"editor.start.title\")}\n </p>\n {error ? (\n <p role=\"alert\" className={alertClassName}>\n {messages.error(error)}\n </p>\n ) : null}\n <button\n ref={button}\n type=\"button\"\n className=\"hm-pdf-editor-button\"\n aria-describedby={hintId}\n onClick={() => input.current?.click()}\n >\n {messages.t(error ? \"editor.start.retry\" : \"editor.start.choose\")}\n </button>\n <p id={hintId} className=\"hm-pdf-editor-start-hint\">\n {messages.t(\"editor.start.hint\")}\n </p>\n <input\n ref={input}\n type=\"file\"\n accept=\"application/pdf,.pdf\"\n // The button above is the control; this input only opens the picker.\n tabIndex={-1}\n aria-hidden=\"true\"\n hidden\n onChange={choose}\n />\n </div>\n );\n}\n","import { cleanFileName, MAX_FILE_NAME_LENGTH } from \"@hussmartinez/sdk-core\";\n\n/** The download's name when there's no usable one (docs/adr/0009). */\nexport const DEFAULT_DOWNLOAD_NAME = \"document.pdf\";\n\nconst EXTENSION = \".pdf\";\n\n/**\n * A safe name for the saved document, from the source's name or a host's\n * `downloadName`, which are both cleaned as file names (docs/adr/0009). It\n * ends in `.pdf`, in any case, stays within the name limit, and falls back\n * to {@link DEFAULT_DOWNLOAD_NAME}.\n */\nexport function downloadFileName(name: unknown): string {\n const clean = cleanFileName(name);\n if (clean === undefined) return DEFAULT_DOWNLOAD_NAME;\n if (clean.toLowerCase().endsWith(EXTENSION)) return clean;\n const base = Array.from(clean)\n .slice(0, MAX_FILE_NAME_LENGTH - EXTENSION.length)\n .join(\"\")\n .trimEnd();\n return base === \"\" ? DEFAULT_DOWNLOAD_NAME : `${base}${EXTENSION}`;\n}\n\n/**\n * Saves bytes through the browser, as a download named `name`: a `blob:`\n * URL on a detached `<a download>`. It makes no request, and needs no\n * Content Security Policy beyond the README's (docs/adr/0009).\n */\nexport function saveFile(bytes: Uint8Array, name: string): void {\n const url = URL.createObjectURL(\n new Blob([bytes as Uint8Array<ArrayBuffer>], { type: \"application/pdf\" }),\n );\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name;\n link.rel = \"noopener\";\n link.click();\n // Some browsers read the URL after the click returns, so it's revoked\n // later rather than at once.\n setTimeout(() => URL.revokeObjectURL(url), REVOKE_AFTER);\n}\n\n/** How long a download's URL stays valid, in milliseconds. */\nexport const REVOKE_AFTER = 40_000;\n","import type { Announce } from \"@hussmartinez/ui/react\";\nimport { type RefObject, useCallback, useEffect, useRef, useState } from \"react\";\nimport { isPdfError } from \"../../core/errors/pdf-error.js\";\nimport type { PdfSession } from \"../../core/session/session.js\";\nimport { downloadFileName, saveFile } from \"../../features/save/download-name.js\";\nimport type { usePdfMessages } from \"../hooks.js\";\nimport type { PdfDownloadNameInfo, PdfEditorProps } from \"./types.js\";\n\n/** How long a save runs before its Cancel button appears, in milliseconds. */\nexport const CANCEL_AFTER = 1_000;\n\n/** Where a save is, for the editor's header and its tools. */\nexport interface SaveState {\n readonly saving: boolean;\n /** Whether the Cancel button shows: only once a save takes a while. */\n readonly cancellable: boolean;\n /** The text of the last save's failure, for the header's alert. */\n readonly failure: string | undefined;\n}\n\nconst IDLE: SaveState = { saving: false, cancellable: false, failure: undefined };\n\n/**\n * The download tool's work (docs/adr/0009): builds the document in the\n * worker, then saves it through the browser or hands it to `onExport`.\n * One save runs at a time. Cancel, or opening or closing a document,\n * aborts it quietly; a failure is described by its code, or by the\n * catalogue's save failure when the host's own code fails.\n */\nexport function useSave(options: {\n readonly session: PdfSession;\n readonly messages: ReturnType<typeof usePdfMessages>;\n readonly announce: Announce;\n readonly props: RefObject<Pick<PdfEditorProps, \"onExport\" | \"downloadName\">>;\n}): SaveState & { readonly save: () => void; readonly cancel: () => void } {\n const { session, messages, announce, props } = options;\n const [state, setState] = useState<SaveState>(IDLE);\n const running = useRef<AbortController | undefined>(undefined);\n\n const cancel = useCallback(() => running.current?.abort(), []);\n\n const save = useCallback(() => {\n if (running.current) return;\n const controller = new AbortController();\n running.current = controller;\n setState({ saving: true, cancellable: false, failure: undefined });\n const timer = setTimeout(\n () => setState((current) => (current.saving ? { ...current, cancellable: true } : current)),\n CANCEL_AFTER,\n );\n let failure: string | undefined;\n const finish = () => {\n clearTimeout(timer);\n if (running.current === controller) running.current = undefined;\n setState({ saving: false, cancellable: false, failure });\n };\n void (async () => {\n const snapshot = session.getSnapshot();\n const info: PdfDownloadNameInfo = {\n pageCount: snapshot.plan.pages.length,\n ...(snapshot.sources[0]?.name ? { sourceName: snapshot.sources[0].name } : {}),\n };\n let bytes: Uint8Array;\n try {\n bytes = await session.export({ signal: controller.signal });\n } catch (error) {\n if (!controller.signal.aborted && !isPdfError(error, \"ABORTED\")) {\n failure = messages.error(error);\n }\n return;\n }\n if (controller.signal.aborted) return;\n const { onExport, downloadName } = props.current;\n try {\n const name = downloadFileName(downloadName ? downloadName(info) : info.sourceName);\n if (onExport) {\n await onExport(bytes, { fileName: name, pageCount: info.pageCount });\n announce(messages.t(\"editor.ready\"));\n } else {\n saveFile(bytes, name);\n announce(messages.t(\"editor.saved\", { name }));\n }\n } catch {\n // The host's code failed; its error is its own to log (docs/adr/0009).\n failure = messages.t(\"editor.saveFailed\");\n }\n })().finally(finish);\n }, [session, messages, announce, props]);\n\n // Opening or closing a document cancels a save, and the last failure no\n // longer applies; so does leaving the page.\n const opened = session.getSnapshot().sources[0]?.id;\n useEffect(() => {\n void opened;\n running.current?.abort();\n setState((current) => (current.failure ? { ...current, failure: undefined } : current));\n }, [opened]);\n useEffect(() => () => running.current?.abort(), []);\n\n return { ...state, save, cancel };\n}\n","import {\n createMessages,\n createShortcutRegistry,\n createToolRegistry,\n type Messages,\n} from \"@hussmartinez/sdk-core\";\nimport {\n type Announce,\n AnnouncerProvider,\n Button,\n UiMessagesProvider,\n useAnnounce,\n usePlatform,\n} from \"@hussmartinez/ui/react\";\nimport {\n type ForwardedRef,\n forwardRef,\n type KeyboardEvent,\n type ReactNode,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { PdfLimitName } from \"../../core/errors/pdf-limits.js\";\nimport type { PdfSessionSnapshot, PdfWarning } from \"../../core/session/session.js\";\nimport { targetPages } from \"../../features/pages/rotate-tools.js\";\nimport type { PdfTool, PdfToolContext } from \"../../features/tool-types.js\";\nimport { DEFAULT_TOOLBAR, pdfTools } from \"../../features/tools.js\";\nimport { PdfContext } from \"../context.js\";\nimport { type PdfEditorMessageCatalogue, pdfEditorMessages } from \"../editor-messages.js\";\nimport { usePdfDocument, usePdfMessages, usePdfSession } from \"../hooks.js\";\nimport { useProvidedSession } from \"../PdfSessionProvider.js\";\nimport { PdfThumbnails } from \"../thumbnails/PdfThumbnails.js\";\nimport { pdfIcons } from \"../toolbar/icons.js\";\nimport { PdfToolbar } from \"../toolbar/PdfToolbar.js\";\nimport { PdfViewer } from \"../viewer/PdfViewer.js\";\nimport { PdfEditorStart } from \"./PdfEditorStart.js\";\nimport type { PdfEditorChange, PdfEditorHandle, PdfEditorProps } from \"./types.js\";\nimport { useSave } from \"./use-save.js\";\n\n/**\n * A warning's text. Each one is passed `actual`; texts that don't show it\n * ignore it, which the catalogue's per-key types can't express for a union.\n */\nfunction warningText(messages: Messages<PdfEditorMessageCatalogue>, warning: PdfWarning): string {\n const t = messages.t as (key: `warnings.${PdfLimitName}`, params: { actual: number }) => string;\n return t(`warnings.${warning.limit}`, { actual: warning.actual });\n}\n\nconst join = (...names: (string | undefined)[]) => names.filter(Boolean).join(\" \");\n\n/**\n * What to announce after a tool ran from the toolbar or a shortcut, so a\n * change that has no focus of its own still reaches screen readers. Tools\n * whose result is already announced, such as opening, or visible where\n * focus is, have none.\n */\nfunction resultOf(\n tool: PdfTool,\n messages: Messages<PdfEditorMessageCatalogue>,\n before: PdfSessionSnapshot,\n after: PdfSessionSnapshot,\n): string | undefined {\n switch (tool.id) {\n case \"pdf.undo\":\n return messages.t(\"editor.undone\");\n case \"pdf.redo\":\n return messages.t(\"editor.redone\");\n case \"pdf.rotate-left\":\n case \"pdf.rotate-right\":\n return messages.t(\"editor.rotated\", { count: targetPages(before).length });\n case \"pdf.delete-pages\":\n return messages.t(\"editor.deleted\", { count: targetPages(before).length });\n case \"pdf.move-earlier\":\n case \"pdf.move-later\": {\n // The move selects the moved pages; it says where the first one went.\n if (after.plan === before.plan) return undefined;\n const [first] = after.selection;\n const position = after.plan.pages.findIndex((page) => page.key === first) + 1;\n return messages.t(\"editor.moved\", { count: after.selection.length, position });\n }\n default:\n return undefined;\n }\n}\n\n/** What changed between two snapshots, if the host should hear about it. */\nfunction changeBetween(\n before: PdfSessionSnapshot,\n after: PdfSessionSnapshot,\n): PdfEditorChange | undefined {\n const pageCount = after.plan.pages.length;\n const opened = after.sources[0];\n if (after.status === \"ready\" && opened?.id !== before.sources[0]?.id) {\n return { reason: \"open\", pageCount, ...(opened?.name ? { fileName: opened.name } : {}) };\n }\n if (before.sources.length > 0 && after.sources.length === 0) {\n return { reason: \"close\", pageCount: 0 };\n }\n if (after.status === \"ready\" && after.plan !== before.plan) {\n return { reason: \"edit\", pageCount };\n }\n return undefined;\n}\n\n/**\n * Hands ui's `announce` to the editor's body, which renders the provider\n * inside its own root: ui's live regions follow the provider's children,\n * and inside the root they never land in the host's layout.\n */\nfunction AnnounceBridge({ target }: { target: { current: Announce } }): null {\n const announce = useAnnounce();\n useEffect(() => {\n target.current = announce;\n }, [target, announce]);\n return null;\n}\n\ninterface BodyProps\n extends Pick<\n PdfEditorProps,\n | \"file\"\n | \"onChange\"\n | \"onExport\"\n | \"downloadName\"\n | \"className\"\n | \"classNames\"\n | \"unstyled\"\n | \"tools\"\n | \"toolbar\"\n | \"icons\"\n > {\n readonly handle: ForwardedRef<PdfEditorHandle>;\n}\n\nfunction PdfEditorBody(props: BodyProps): ReactNode {\n const { file, onChange, className, classNames = {}, unstyled = false, handle } = props;\n const session = usePdfSession();\n const snapshot = usePdfDocument();\n const messages = usePdfMessages();\n // ui's announcer lives inside the root, below this component.\n const announceTo = useRef<Announce>(() => {});\n const announce = useCallback<Announce>(\n (message, options) => announceTo.current(message, options),\n [],\n );\n const platform = usePlatform();\n const root = useRef<HTMLDivElement>(null);\n const startButton = useRef<HTMLButtonElement>(null);\n const input = useRef<HTMLInputElement>(null);\n const insertInput = useRef<HTMLInputElement>(null);\n const [inserting, setInserting] = useState(false);\n const latestOnChange = useRef(onChange);\n latestOnChange.current = onChange;\n const saveProps = useRef(props);\n saveProps.current = props;\n const saving = useSave({ session, messages, announce, props: saveProps });\n\n // Mistakes in `tools` or `toolbar`, such as an unknown id, throw here, when\n // the editor renders, rather than leaving a tool silently missing.\n const registry = useMemo(\n () =>\n createToolRegistry(pdfTools, {\n ...(props.tools ? { tools: props.tools } : {}),\n toolbar:\n props.toolbar ??\n DEFAULT_TOOLBAR.map((group) =>\n group.filter((id) => !props.tools || props.tools.includes(id)),\n ).filter((group) => group.length > 0),\n }),\n [props.tools, props.toolbar],\n );\n const shortcuts = useMemo(\n () => createShortcutRegistry({ platform, tools: registry.tools }),\n [platform, registry],\n );\n const context: PdfToolContext = useMemo(\n () => ({\n session,\n chooseFile: () => input.current?.click(),\n chooseInsertFile: () => insertInput.current?.click(),\n save: saving.save,\n }),\n [session, saving.save],\n );\n const icons = useMemo(() => ({ ...pdfIcons, ...props.icons }), [props.icons]);\n\n // Keys that only work in the thumbnails, for tools the host kept (docs/adr/0008).\n const deleteTool = registry.get(\"pdf.delete-pages\");\n const moveTools = {\n earlier: registry.get(\"pdf.move-earlier\"),\n later: registry.get(\"pdf.move-later\"),\n };\n\n const runTool = (tool: PdfTool) => {\n const before = session.getSnapshot();\n const state = { snapshot: before, saving: saving.saving, inserting };\n if (!(tool.isEnabled?.(state) ?? true)) return;\n void Promise.resolve(tool.run(context)).then(() => {\n const result = resultOf(tool, messages, before, session.getSnapshot());\n if (result) announce(result);\n });\n };\n\n // Shortcuts work while focus is inside the editor, never on the whole page\n // (WCAG 2.1.4, sdk-core ADR 0030).\n const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {\n const id = shortcuts.match(event.nativeEvent);\n const tool = id ? registry.get(id) : undefined;\n if (!tool) return;\n event.preventDefault();\n runTool(tool);\n };\n\n useImperativeHandle(\n handle,\n () => ({\n session,\n open: (next, options) => session.open(next, options),\n export: (options) => session.export(options),\n undo: () => session.undo(),\n redo: () => session.redo(),\n close: () => session.close(),\n }),\n [session],\n );\n\n // The host's file opens when its identity changes; a newer one cancels it.\n useEffect(() => {\n if (file === undefined) return;\n if (file === null) {\n void session.close();\n return;\n }\n const controller = new AbortController();\n // A failure is in the snapshot, which the editor shows.\n session.open(file, { signal: controller.signal }).catch(() => {});\n return () => controller.abort();\n }, [session, file]);\n\n // Changes reach the host, and opening and closing reach screen readers.\n useEffect(() => {\n let before = session.getSnapshot();\n return session.subscribe(() => {\n const after = session.getSnapshot();\n const change = changeBetween(before, after);\n before = after;\n if (!change) return;\n if (change.reason === \"open\") {\n announce(messages.t(\"editor.opened\", { count: change.pageCount }));\n } else if (change.reason === \"close\") {\n announce(messages.t(\"editor.closed\"));\n }\n latestOnChange.current?.(change);\n });\n }, [session, messages, announce]);\n\n // Focus follows the content that replaced what had it: the document once\n // it opens, or the button to try again after a failure. Focus elsewhere on\n // the host's page is left alone.\n const { status } = snapshot;\n const previous = useRef(status);\n useEffect(() => {\n if (previous.current === status) return;\n previous.current = status;\n const active = document.activeElement;\n const ours = active === null || active === document.body || root.current?.contains(active);\n if (!ours) return;\n if (status === \"ready\") root.current?.querySelector<HTMLElement>(\".hm-pdf-viewer\")?.focus();\n if (status === \"error\") startButton.current?.focus();\n }, [status]);\n\n const open = (chosen: File) => {\n // A failure is in the snapshot, which the editor shows.\n session.open(chosen).catch(() => {});\n };\n\n /**\n * Inserts every page of another file after the current page, then selects\n * the inserted pages and shows the first (docs/adr/0008). A failure is in\n * the snapshot, which the header's alert shows, and changes nothing.\n */\n const insert = async (chosen: File) => {\n const before = session.getSnapshot();\n const current = before.plan.pages.findIndex((page) => page.key === before.currentPage);\n const at = current >= 0 ? current + 1 : before.plan.pages.length;\n setInserting(true);\n try {\n await session.insert(chosen, { at });\n } catch {\n return;\n } finally {\n setInserting(false);\n }\n const had = new Set(before.plan.pages.map((page) => page.key));\n const added = session\n .getSnapshot()\n .plan.pages.filter((page) => !had.has(page.key))\n .map((page) => page.key);\n const [first] = added;\n if (!first) return;\n session.select(added);\n session.goToPage(first);\n announce(messages.t(\"editor.inserted\", { count: added.length, page: at }));\n };\n\n const { error, warnings } = snapshot;\n const showError = error !== undefined && error.code !== \"ABORTED\";\n let content: ReactNode;\n if (status === \"ready\") {\n content = (\n <>\n <PdfThumbnails\n className={join(\"hm-pdf-editor-sidebar\", classNames.sidebar)}\n unstyled={unstyled}\n {...(deleteTool ? { onDelete: () => runTool(deleteTool) } : {})}\n {...(moveTools.earlier || moveTools.later\n ? {\n onMove: (direction: \"earlier\" | \"later\") => {\n const tool = moveTools[direction];\n if (tool) runTool(tool);\n },\n }\n : {})}\n />\n <PdfViewer unstyled={unstyled} />\n </>\n );\n } else if (status === \"opening\") {\n content = (\n <div role=\"status\" className={join(\"hm-pdf-editor-loading\", classNames.status)}>\n {/* Indeterminate: the engine reports no progress while it opens. */}\n <progress className=\"hm-pdf-editor-progress\" aria-hidden=\"true\" />\n <p>{messages.t(\"editor.opening\")}</p>\n </div>\n );\n } else {\n content = (\n <PdfEditorStart\n error={showError ? error : undefined}\n onFile={open}\n button={startButton}\n className={join(\"hm-pdf-editor-start\", classNames.start)}\n alertClassName={join(\"hm-pdf-editor-alert\", classNames.alert)}\n />\n );\n }\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a labelled group of the editor's regions, not a fieldset\n <div\n ref={root}\n role=\"group\"\n aria-label={messages.t(\"editor.label\")}\n aria-busy={status === \"opening\" || snapshot.busy || saving.saving}\n // ui's text root (ui ADR 0010), unless the host styles the editor itself.\n className={join(\n unstyled ? undefined : \"hm-text\",\n \"hm-pdf-editor\",\n className,\n classNames.root,\n )}\n data-hm-status={status}\n onKeyDown={onKeyDown}\n {...(unstyled ? { \"data-hm-unstyled\": \"\" } : {})}\n >\n <input\n ref={input}\n type=\"file\"\n accept=\"application/pdf,.pdf\"\n // The open tool is the control; this input only opens the picker.\n tabIndex={-1}\n aria-hidden=\"true\"\n hidden\n onChange={(event) => {\n const [chosen] = event.target.files ?? [];\n event.target.value = \"\";\n if (chosen) open(chosen);\n }}\n />\n <input\n ref={insertInput}\n type=\"file\"\n accept=\"application/pdf,.pdf\"\n // The insert tool is the control; this input only opens the picker.\n tabIndex={-1}\n aria-hidden=\"true\"\n hidden\n data-hm-insert=\"\"\n onChange={(event) => {\n const [chosen] = event.target.files ?? [];\n event.target.value = \"\";\n if (chosen) void insert(chosen);\n }}\n />\n <div className={join(\"hm-pdf-editor-header\", classNames.header)}>\n <PdfToolbar\n registry={registry}\n shortcuts={shortcuts}\n context={context}\n icons={icons}\n onRun={runTool}\n saving={saving.saving}\n inserting={inserting}\n className={join(\"hm-pdf-editor-toolbar\", classNames.toolbar)}\n />\n {saving.saving ? (\n <div className={join(\"hm-pdf-editor-saving\", classNames.status)}>\n <p role=\"status\">{messages.t(\"editor.saving\")}</p>\n {saving.cancellable ? (\n <Button size=\"small\" onClick={saving.cancel}>\n {messages.t(\"editor.cancelSave\")}\n </Button>\n ) : null}\n </div>\n ) : null}\n {saving.failure ? (\n <p role=\"alert\" className={join(\"hm-pdf-editor-alert\", classNames.alert)}>\n {saving.failure}\n </p>\n ) : null}\n {status === \"ready\" && showError ? (\n <p role=\"alert\" className={join(\"hm-pdf-editor-alert\", classNames.alert)}>\n {messages.error(error)}\n </p>\n ) : null}\n {status === \"ready\" && (warnings.length > 0 || snapshot.historyTrimmed) ? (\n <div role=\"status\" className={join(\"hm-pdf-editor-warnings\", classNames.status)}>\n <ul>\n {warnings.map((warning) => (\n <li key={warning.limit}>{warningText(messages, warning)}</li>\n ))}\n {snapshot.historyTrimmed ? <li>{messages.t(\"editor.historyTrimmed\")}</li> : null}\n </ul>\n </div>\n ) : null}\n </div>\n <div className={join(\"hm-pdf-editor-body\", classNames.body)}>{content}</div>\n <AnnouncerProvider>\n <AnnounceBridge target={announceTo} />\n </AnnouncerProvider>\n </div>\n );\n}\n\n/**\n * The complete editor: a document's pages beside it as thumbnails, with\n * designed states for no document, opening and a failed open (ADR 0014).\n * It creates its own session, through `PdfSessionProvider`, unless one is\n * passed, and releases what it created when it unmounts.\n *\n * Users open a PDF with the button, which keyboard and screen reader users\n * reach like any other, or by dropping it on the editor. Opening and\n * closing are announced, and focus moves to the document once it opens, or\n * to the button to try again if it couldn't.\n *\n * Its toolbar is built from {@link pdfTools}: choose them with `tools` and\n * arrange them with `toolbar`. Each tool's shortcut works while focus is in\n * the editor, and undoing, redoing and rotating are announced.\n *\n * Load `@hussmartinez/ui/styles.css` once, before the SDK's stylesheet: the\n * toolbar's focus rings and target sizes are in it (sdk-core ADR 0036).\n *\n * Give the editor a bounded height, such as a grid row or a fixed height:\n * its viewer and thumbnails scroll within it.\n *\n * @example\n * ```tsx\n * const editor = useRef<PdfEditorHandle>(null);\n * <PdfEditor ref={editor} file={file} onChange={({ reason }) => setDirty(reason === \"edit\")} />;\n * const bytes = await editor.current?.export();\n * ```\n *\n * @public\n */\nexport const PdfEditor = /* @__PURE__ */ forwardRef(function PdfEditor(\n props: PdfEditorProps,\n handle: ForwardedRef<PdfEditorHandle>,\n): ReactNode {\n const {\n file,\n onChange,\n onExport,\n downloadName,\n className,\n classNames,\n unstyled,\n tools,\n toolbar,\n icons,\n messages: overrides,\n locale = \"en\",\n ...source\n } = props;\n const session = useProvidedSession(source);\n // One Messages object, with the host's locale and overrides, for the\n // editor's components and for ui's (sdk-core ADR 0046).\n const messages = useMemo(\n () =>\n createMessages(pdfEditorMessages, {\n locale,\n ...(overrides ? { overrides } : {}),\n }),\n [locale, overrides],\n );\n const value = useMemo(() => ({ session, messages }), [session, messages]);\n return (\n <PdfContext.Provider value={value}>\n <UiMessagesProvider messages={messages}>\n <PdfEditorBody\n handle={handle}\n {...(file !== undefined ? { file } : {})}\n {...(onChange ? { onChange } : {})}\n {...(onExport ? { onExport } : {})}\n {...(downloadName ? { downloadName } : {})}\n {...(className !== undefined ? { className } : {})}\n {...(classNames ? { classNames } : {})}\n {...(unstyled !== undefined ? { unstyled } : {})}\n {...(tools ? { tools } : {})}\n {...(toolbar ? { toolbar } : {})}\n {...(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AAD,EAAA,UACE,oBAAC,gBAAD,EAAgB,QAAQ,WAAa,CAAA,EACpB,CAAA;EAChB;;AAET;AAgCA,IAAa,YAA4B,2BAAW,SAAS,UAC3D,OACA,QACW;CACX,MAAM,EACJ,MACA,UACA,UACA,cACA,WACA,YACA,UACA,OACA,SACA,OACA,UAAU,WACV,SAAS,MACT,GAAG,WACD;CACJ,MAAM,UAAU,mBAAmB,MAAM;CAGzC,MAAM,WAAW,cAEb,eAAe,mBAAmB;EAChC;EACA,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;CACnC,CAAC,GACH,CAAC,QAAQ,SAAS,CACpB;CACA,MAAM,QAAQ,eAAe;EAAE;EAAS;CAAS,IAAI,CAAC,SAAS,QAAQ,CAAC;CACxE,OACE,oBAAC,WAAW,UAAZ;EAA4B;EAC1B,UAAA,oBAAC,oBAAD;GAA8B;GAC5B,UAAA,oBAAC,eAAD;IACU;IACR,GAAK,SAAS,KAAA,IAAY,EAAE,KAAK,IAAI,CAAC;IACtC,GAAK,WAAW,EAAE,SAAS,IAAI,CAAC;IAChC,GAAK,WAAW,EAAE,SAAS,IAAI,CAAC;IAChC,GAAK,eAAe,EAAE,aAAa,IAAI,CAAC;IACxC,GAAK,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC;IAChD,GAAK,aAAa,EAAE,WAAW,IAAI,CAAC;IACpC,GAAK,aAAa,KAAA,IAAY,EAAE,SAAS,IAAI,CAAC;IAC9C,GAAK,QAAQ,EAAE,MAAM,IAAI,CAAC;IAC1B,GAAK,UAAU,EAAE,QAAQ,IAAI,CAAC;IAC9B,GAAK,QAAQ,EAAE,MAAM,IAAI,CAAC;GAC3B,CAAA;EACiB,CAAA;CACD,CAAA;AAEzB,CAAC"}
1
+ {"version":3,"file":"react.js","names":["LETTER","join","join","join","_Fragment"],"sources":["../src/features/history/history-tools.ts","../src/features/open/open-tool.ts","../src/features/tool-types.ts","../src/features/pages/rotate-tools.ts","../src/features/pages/delete-tool.ts","../src/features/pages/insert-tool.ts","../src/features/pages/move-tools.ts","../src/features/save/download-tool.ts","../src/features/tools.ts","../src/react/context.ts","../src/messages/editor-en.ts","../src/react/editor-messages.ts","../src/react/hooks.ts","../src/react/PdfSessionProvider.tsx","../src/react/scrollbar.ts","../src/react/use-near-observer.ts","../src/react/use-page-drawing.ts","../src/react/viewer/geometry.ts","../src/react/viewer/render-queue.ts","../src/react/thumbnails/PdfThumbnails.tsx","../src/react/toolbar/icons.ts","../src/features/pages/thumbnail-keys.ts","../src/react/toolbar/PdfToolbar.tsx","../src/react/viewer/PdfViewerPage.tsx","../src/react/viewer/PdfViewer.tsx","../src/react/editor/PdfEditorStart.tsx","../src/features/save/download-name.ts","../src/react/editor/use-save.ts","../src/react/editor/PdfEditor.tsx"],"sourcesContent":["import { defineTool } from \"@hussmartinez/sdk-core\";\nimport type { PdfTool } from \"../tool-types.js\";\n\n/** Undoes the last edit (sdk-core ADR 0010). */\nexport const undoTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.undo\",\n label: \"tools.undo\",\n icon: \"undo\",\n group: \"history\",\n isEnabled: ({ snapshot }) => snapshot.canUndo,\n run: ({ session }) => {\n session.undo();\n },\n shortcuts: \"undo\",\n});\n\n/** Redoes the last undone edit. */\nexport const redoTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.redo\",\n label: \"tools.redo\",\n icon: \"redo\",\n group: \"history\",\n isEnabled: ({ snapshot }) => snapshot.canRedo,\n run: ({ session }) => {\n session.redo();\n },\n shortcuts: \"redo\",\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport type { PdfTool } from \"../tool-types.js\";\n\n/** Asks for a PDF and opens it. No shortcut: `Mod+O` is the browser's own. */\nexport const openTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.open\",\n label: \"tools.open\",\n icon: \"open\",\n group: \"file\",\n run: ({ chooseFile }) => chooseFile(),\n});\n","import type { Tool } from \"@hussmartinez/sdk-core\";\nimport type { PdfSession, PdfSessionSnapshot } from \"../core/session/session.js\";\n\n/**\n * What a tool reads to decide whether it's available, enabled or active.\n *\n * @public\n */\nexport interface PdfToolState {\n /** The session's current snapshot. */\n readonly snapshot: PdfSessionSnapshot;\n /** Whether the editor is saving the document. Absent outside the editor. */\n readonly saving?: boolean;\n /** Whether the editor is inserting another document. Absent outside the editor. */\n readonly inserting?: boolean;\n}\n\n/**\n * What a tool runs against.\n *\n * @public\n */\nexport interface PdfToolContext {\n /** The session the tool edits. */\n readonly session: PdfSession;\n /** Asks the user for a PDF and opens it, as the open tool does. */\n readonly chooseFile: () => void;\n /**\n * Builds the document and saves it, as the download tool does\n * (docs/adr/0009). Absent outside the editor.\n */\n readonly save?: () => void;\n /**\n * Asks the user for another PDF and inserts its pages after the current\n * page, as the insert tool does (docs/adr/0008). Absent outside the editor.\n */\n readonly chooseInsertFile?: () => void;\n}\n\n/**\n * One of the editor's tools (sdk-core ADR 0009 and ADR 0030): headless, so\n * the React editor and the custom element share it.\n *\n * @public\n */\nexport type PdfTool = Tool<PdfToolState, PdfToolContext, undefined>;\n\n/** Whether a document is open. */\nexport const hasDocument = ({ snapshot }: PdfToolState): boolean => snapshot.status === \"ready\";\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport type { PdfSessionSnapshot } from \"../../core/session/session.js\";\nimport { hasDocument, type PdfTool, type PdfToolContext } from \"../tool-types.js\";\n\n/**\n * The pages a page tool acts on: the selected pages, or the current page\n * when none is selected. Empty when no document is open.\n */\nexport function targetPages(snapshot: PdfSessionSnapshot): readonly string[] {\n if (snapshot.status !== \"ready\") return [];\n if (snapshot.selection.length > 0) return snapshot.selection;\n return snapshot.currentPage === undefined ? [] : [snapshot.currentPage];\n}\n\nfunction rotate({ session }: PdfToolContext, angle: -90 | 90): void {\n const pages = targetPages(session.getSnapshot());\n if (pages.length === 0) return;\n session.execute({ type: \"pdf.rotatePages\", pages, angle });\n}\n\nconst hasTargets = ({ snapshot }: { snapshot: PdfSessionSnapshot }) =>\n hasDocument({ snapshot }) && targetPages(snapshot).length > 0;\n\n/** Turns the selected pages, or the current one, a quarter turn anticlockwise. */\nexport const rotateLeftTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.rotate-left\",\n label: \"tools.rotate-left\",\n icon: \"rotate-left\",\n group: \"pages\",\n isEnabled: hasTargets,\n run: (context) => rotate(context, -90),\n shortcuts: [\"[\"],\n});\n\n/** Turns the selected pages, or the current one, a quarter turn clockwise. */\nexport const rotateRightTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.rotate-right\",\n label: \"tools.rotate-right\",\n icon: \"rotate-right\",\n group: \"pages\",\n isEnabled: hasTargets,\n run: (context) => rotate(context, 90),\n shortcuts: [\"]\"],\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport {\n hasDocument,\n type PdfTool,\n type PdfToolContext,\n type PdfToolState,\n} from \"../tool-types.js\";\nimport { targetPages } from \"./rotate-tools.js\";\n\n/** Whether deleting the targets would leave at least one page (docs/adr/0008). */\nconst canDelete = ({ snapshot }: PdfToolState): boolean => {\n const targets = targetPages(snapshot).length;\n return hasDocument({ snapshot }) && targets > 0 && targets < snapshot.plan.pages.length;\n};\n\n/**\n * Deletes the selected pages, or the current one, as one undoable step. The\n * page that takes the first deleted page's place, or the new last page,\n * becomes the selection and the current page (docs/adr/0008).\n */\nfunction deletePages({ session }: PdfToolContext): void {\n const before = session.getSnapshot();\n if (!canDelete({ snapshot: before })) return;\n const pages = targetPages(before);\n const removed = new Set(pages);\n const first = before.plan.pages.findIndex((page) => removed.has(page.key));\n session.execute({ type: \"pdf.deletePages\", pages });\n const remaining = session.getSnapshot().plan.pages;\n const next = remaining[Math.min(first, remaining.length - 1)];\n if (!next) return;\n session.select([next.key]);\n session.goToPage(next.key);\n}\n\n/**\n * Deletes the selected pages, or the current one. A document keeps at least\n * one page. Its keys, Delete and Backspace, work in the thumbnails, where\n * the selection is shown, never editor-wide (docs/adr/0008).\n */\nexport const deletePagesTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.delete-pages\",\n label: \"tools.delete-pages\",\n icon: \"delete\",\n group: \"pages\",\n isEnabled: canDelete,\n run: deletePages,\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport { hasDocument, type PdfTool } from \"../tool-types.js\";\n\n/**\n * Asks for another PDF and inserts all its pages after the current page,\n * as one undoable step: how two documents are merged (docs/adr/0008). The\n * file policy applies to the combined document, and a failed insert leaves\n * the document as it was. No shortcut: the picker needs a click or a key\n * press on the button anyway.\n */\nexport const insertPagesTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.insert-pages\",\n label: \"tools.insert-pages\",\n icon: \"page-add\",\n group: \"file\",\n isEnabled: (state) => hasDocument(state) && !state.inserting,\n run: ({ chooseInsertFile }) => chooseInsertFile?.(),\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport type { PdfSessionSnapshot } from \"../../core/session/session.js\";\nimport {\n hasDocument,\n type PdfTool,\n type PdfToolContext,\n type PdfToolState,\n} from \"../tool-types.js\";\nimport { targetPages } from \"./rotate-tools.js\";\n\n/** Which way the move tools move pages. */\nexport type MoveDirection = \"earlier\" | \"later\";\n\n/**\n * The move for the selected pages, or the current one, as `pdf.movePages`'s\n * `pages` and `to`, or `undefined` when there's nothing to move. Pages that\n * aren't next to each other are gathered into one block, in plan order:\n * \"earlier\" puts its first page one position before where it was, and\n * \"later\" puts its last page one position after (docs/adr/0008).\n */\nexport function moveOf(\n snapshot: PdfSessionSnapshot,\n direction: MoveDirection,\n): { readonly pages: readonly string[]; readonly to: number } | undefined {\n if (snapshot.status !== \"ready\") return undefined;\n const chosen = new Set(targetPages(snapshot));\n const order = snapshot.plan.pages.map((page) => page.key);\n const indexes = order.flatMap((key, index) => (chosen.has(key) ? [index] : []));\n const first = indexes[0];\n const last = indexes.at(-1);\n if (first === undefined || last === undefined) return undefined;\n const pages = indexes.map((index) => order[index] as string);\n const block = last - first + 1 === pages.length;\n const others = order.length - pages.length;\n if (direction === \"earlier\") {\n if (block && first === 0) return undefined;\n return { pages, to: Math.max(0, first - 1) };\n }\n if (block && last === order.length - 1) return undefined;\n return { pages, to: Math.min(others, last + 2 - pages.length) };\n}\n\nfunction move({ session }: PdfToolContext, direction: MoveDirection): void {\n const before = session.getSnapshot();\n const found = moveOf(before, direction);\n if (!found) return;\n session.execute({ type: \"pdf.movePages\", pages: found.pages, to: found.to });\n // The moved pages stay chosen, and the current page stays current if it\n // moved, so the user keeps their place (docs/adr/0008).\n session.select(found.pages);\n const current = before.currentPage;\n session.goToPage(\n current !== undefined && found.pages.includes(current) ? current : (found.pages[0] as string),\n );\n}\n\n/**\n * Whether the tool can move pages in `direction`. Tools call it from an arrow\n * of their own rather than being given a function it returns: a call in a\n * tool's definition would keep every tool in a bundle that imports none of\n * them (sdk-core ADR 0056).\n */\nconst canMove = (direction: MoveDirection, { snapshot }: PdfToolState): boolean =>\n hasDocument({ snapshot }) && moveOf(snapshot, direction) !== undefined;\n\n/**\n * Moves the selected pages, or the current one, one position earlier. Its\n * keys, Alt+↑ (Option+↑ on macOS), work in the thumbnails, never\n * editor-wide (docs/adr/0008).\n */\nexport const moveEarlierTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.move-earlier\",\n label: \"tools.move-earlier\",\n icon: \"move-up\",\n group: \"pages\",\n isEnabled: (state) => canMove(\"earlier\", state),\n run: (context) => move(context, \"earlier\"),\n});\n\n/** Moves the selected pages, or the current one, one position later: Alt+↓ in the thumbnails. */\nexport const moveLaterTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.move-later\",\n label: \"tools.move-later\",\n icon: \"move-down\",\n group: \"pages\",\n isEnabled: (state) => canMove(\"later\", state),\n run: (context) => move(context, \"later\"),\n});\n","import { defineTool } from \"@hussmartinez/sdk-core\";\nimport { hasDocument, type PdfTool } from \"../tool-types.js\";\n\n/**\n * Builds the document and saves it: through the browser as a download, or\n * through the host's `onExport` (docs/adr/0009). No shortcut: Ctrl or ⌘+S\n * stays the browser's. It's disabled while a save runs, so it can't run\n * twice.\n */\nexport const downloadTool: PdfTool = /* @__PURE__ */ defineTool({\n id: \"pdf.download\",\n label: \"tools.download\",\n icon: \"download\",\n group: \"save\",\n isEnabled: (state) => hasDocument(state) && !state.saving,\n run: ({ save }) => save?.(),\n});\n","import { redoTool, undoTool } from \"./history/history-tools.js\";\nimport { openTool } from \"./open/open-tool.js\";\nimport { deletePagesTool } from \"./pages/delete-tool.js\";\nimport { insertPagesTool } from \"./pages/insert-tool.js\";\nimport { moveEarlierTool, moveLaterTool } from \"./pages/move-tools.js\";\nimport { rotateLeftTool, rotateRightTool } from \"./pages/rotate-tools.js\";\nimport { downloadTool } from \"./save/download-tool.js\";\nimport type { PdfTool } from \"./tool-types.js\";\n\n/**\n * Every tool the editor knows, in their default order (sdk-core ADR 0030).\n *\n * @public\n */\nexport const pdfTools: readonly PdfTool[] = [\n openTool,\n insertPagesTool,\n undoTool,\n redoTool,\n rotateLeftTool,\n rotateRightTool,\n moveEarlierTool,\n moveLaterTool,\n deletePagesTool,\n downloadTool,\n];\n\n/** The toolbar's default groups. */\nexport const DEFAULT_TOOLBAR: readonly (readonly string[])[] = [\n [\"pdf.open\", \"pdf.insert-pages\"],\n [\"pdf.undo\", \"pdf.redo\"],\n [\"pdf.rotate-left\", \"pdf.rotate-right\", \"pdf.move-earlier\", \"pdf.move-later\", \"pdf.delete-pages\"],\n [\"pdf.download\"],\n];\n","import type { Messages } from \"@hussmartinez/sdk-core\";\nimport { createContext } from \"react\";\nimport type { PdfSession } from \"../core/session/session.js\";\nimport type { PdfEditorMessageCatalogue } from \"./editor-messages.js\";\n\n/** What the provider shares with every PDF component below it. */\nexport interface PdfContextValue {\n readonly session: PdfSession;\n readonly messages: Messages<PdfEditorMessageCatalogue>;\n}\n\nexport const PdfContext = /* @__PURE__ */ createContext<PdfContextValue | undefined>(undefined);\n","import { defineMessages, plural } from \"@hussmartinez/sdk-core\";\n\n/**\n * The text of the SDK's interface: the editor, its toolbar and tools, the\n * viewer and the thumbnails. Only the React entry loads it, through\n * `pdfEditorMessages`, so the server-safe entry carries no interface text\n * (docs/adr/0010). Keys use the components' prefixes, never one of ui's\n * (sdk-core ADR 0046).\n */\nexport const pdfEditorText = /* @__PURE__ */ defineMessages({\n \"viewer.label\": \"Document\",\n \"viewer.empty\": \"No document is open.\",\n \"viewer.page\": \"Page {page} of {count}\",\n \"viewer.webLink\": \"Link to {destination}, opens in a new tab\",\n \"viewer.emailLink\": \"Email {destination}\",\n \"thumbnails.label\": \"Pages\",\n \"thumbnails.page\": \"Page {page} of {count}\",\n \"thumbnails.number\": \"{page}\",\n \"editor.label\": \"PDF editor\",\n \"editor.start.title\": \"Open a PDF to get started\",\n \"editor.start.retryTitle\": \"Try another PDF\",\n \"editor.start.choose\": \"Choose a PDF\",\n \"editor.start.retry\": \"Choose another PDF\",\n \"editor.start.hint\": \"Or drop one here. Your file stays on this device and is never uploaded.\",\n \"editor.opening\": \"Opening the PDF…\",\n \"editor.opened\": /* @__PURE__ */ plural(\"count\", {\n one: \"Opened a PDF with {count} page.\",\n other: \"Opened a PDF with {count} pages.\",\n }),\n \"editor.closed\": \"The PDF was closed.\",\n \"editor.undone\": \"Undone.\",\n \"editor.redone\": \"Redone.\",\n \"editor.rotated\": /* @__PURE__ */ plural(\"count\", {\n one: \"Rotated {count} page.\",\n other: \"Rotated {count} pages.\",\n }),\n \"editor.deleted\": /* @__PURE__ */ plural(\"count\", {\n one: \"Deleted {count} page.\",\n other: \"Deleted {count} pages.\",\n }),\n \"editor.moved\": /* @__PURE__ */ plural(\"count\", {\n one: \"Moved {count} page to position {position}.\",\n other: \"Moved {count} pages to position {position}.\",\n }),\n \"editor.inserted\": /* @__PURE__ */ plural(\"count\", {\n one: \"Inserted {count} page after page {page}.\",\n other: \"Inserted {count} pages after page {page}.\",\n }),\n \"editor.historyTrimmed\":\n \"To make room for the inserted document, your earliest edits can no longer be undone.\",\n \"editor.saving\": \"Preparing the PDF…\",\n \"editor.cancelSave\": \"Cancel\",\n \"editor.saved\": \"Saved {name}.\",\n \"editor.ready\": \"The PDF is ready.\",\n \"editor.saveFailed\": \"The PDF couldn't be saved. Please try again.\",\n \"toolbar.label\": \"PDF tools\",\n \"toolbar.groups.file\": \"File\",\n \"toolbar.groups.history\": \"History\",\n \"toolbar.groups.pages\": \"Pages\",\n \"toolbar.groups.save\": \"Save\",\n \"toolbar.groups.other\": \"More tools\",\n \"tools.open\": \"Open a PDF\",\n \"tools.undo\": \"Undo\",\n \"tools.redo\": \"Redo\",\n \"tools.rotate-left\": \"Rotate left\",\n \"tools.rotate-right\": \"Rotate right\",\n \"tools.delete-pages\": \"Delete pages\",\n \"tools.download\": \"Download\",\n \"tools.insert-pages\": \"Insert pages\",\n \"tools.move-earlier\": \"Move earlier\",\n \"tools.move-later\": \"Move later\",\n});\n","import { defineMessages } from \"@hussmartinez/sdk-core\";\nimport { uiMessages } from \"@hussmartinez/ui\";\nimport { pdfEditorText } from \"../messages/editor-en.js\";\nimport { pdfMessages } from \"../messages/en.js\";\n\n/**\n * The English message catalogue of the SDK's components: `pdfMessages`,\n * with sdk-core's text, errors and warnings; `@hussmartinez/ui`'s, for the\n * ui components the editor renders (sdk-core ADR 0046); and the text of the\n * editor, its toolbar and tools, the viewer and the thumbnails.\n *\n * `PdfEditor` and `PdfSessionProvider` each build one `Messages` object from\n * it, with the host's locale and overrides, and the editor gives the same\n * object to its own components and to ui's. Override any of its keys through\n * their `messages` prop, typed with `PdfEditorMessageCatalogue`.\n *\n * It's defined in the React entry, so the server-safe `.` entry and its\n * `pdfMessages` carry no interface text (docs/adr/0010).\n *\n * @public\n */\nexport const pdfEditorMessages = /* @__PURE__ */ defineMessages({\n ...pdfMessages,\n ...uiMessages,\n ...pdfEditorText,\n});\n\n/**\n * The type of {@link pdfEditorMessages}, for typing the editor's `messages`\n * overrides with `MessageOverrides<PdfEditorMessageCatalogue>`.\n *\n * @public\n */\nexport type PdfEditorMessageCatalogue = typeof pdfEditorMessages;\n","import type { Messages } from \"@hussmartinez/sdk-core\";\nimport { useContext, useSyncExternalStore } from \"react\";\nimport type { PdfSession, PdfSessionSnapshot } from \"../core/session/session.js\";\nimport { PdfContext, type PdfContextValue } from \"./context.js\";\nimport type { PdfEditorMessageCatalogue } from \"./editor-messages.js\";\n\nfunction usePdfContext(hook: string): PdfContextValue {\n const value = useContext(PdfContext);\n if (!value) {\n throw new Error(`${hook} must be used inside a PdfSessionProvider.`);\n }\n return value;\n}\n\n/**\n * The session of the nearest `PdfSessionProvider`, to open documents, run\n * commands, undo and export.\n *\n * @public\n */\nexport function usePdfSession(): PdfSession {\n return usePdfContext(\"usePdfSession\").session;\n}\n\n/**\n * The session's current snapshot, re-rendering whenever it changes, through\n * `useSyncExternalStore`, so it's safe with concurrent rendering and server\n * rendering (ADR 0008).\n *\n * @public\n */\nexport function usePdfDocument(): PdfSessionSnapshot {\n const { session } = usePdfContext(\"usePdfDocument\");\n return useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot);\n}\n\n/**\n * The SDK's text for the provider's locale and overrides (ADR 0019).\n *\n * @public\n */\nexport function usePdfMessages(): Messages<PdfEditorMessageCatalogue> {\n return usePdfContext(\"usePdfMessages\").messages;\n}\n","import { createMessages, type MessageOverrides } from \"@hussmartinez/sdk-core\";\nimport { type ReactNode, useEffect, useMemo, useState } from \"react\";\nimport { createPdfJsEngine } from \"../adapters/pdfjs/pdfjs-engine.js\";\nimport { createPdfProcessor } from \"../adapters/qpdf/qpdf-processor.js\";\nimport type { PdfFilePolicyOverrides } from \"../core/errors/pdf-limits.js\";\nimport type { PdfEngine } from \"../core/ports/pdf-engine.js\";\nimport type { PdfProcessor } from \"../core/ports/pdf-processor.js\";\nimport type { PdfSession, PdfSessionEvent } from \"../core/session/session.js\";\nimport { createPdfSession } from \"../core/session/session.js\";\nimport { PdfContext } from \"./context.js\";\nimport { type PdfEditorMessageCatalogue, pdfEditorMessages } from \"./editor-messages.js\";\n\n/**\n * Props for {@link PdfSessionProvider}.\n *\n * @public\n */\nexport interface PdfSessionProviderProps {\n /**\n * A session you created and own. Without it, the provider creates one,\n * with the options below, and closes it when it unmounts. The options are\n * read once, when the provider first renders.\n */\n readonly session?: PdfSession;\n /** The engine for a session the provider creates. Defaults to pdf.js. */\n readonly engine?: PdfEngine;\n /** The processor for a session the provider creates. Defaults to qpdf. */\n readonly processor?: PdfProcessor;\n /**\n * Where your application serves the package's `dist/assets/`, for the\n * default engine and processor (docs/adr/0007). By default, they're inlined.\n */\n readonly assetsUrl?: string | URL;\n /** File limits for a session the provider creates (docs/adr/0004). */\n readonly filePolicy?: PdfFilePolicyOverrides;\n /** Anonymous usage events from a session the provider creates. */\n readonly onEvent?: (event: PdfSessionEvent) => void;\n /** Text overrides, typed against the English catalogue (ADR 0019). */\n readonly messages?: MessageOverrides<PdfEditorMessageCatalogue>;\n /** The locale for numbers, sizes and plurals. Defaults to `\"en\"`. */\n readonly locale?: string;\n /** The components that use the session, such as `PdfViewer`. */\n readonly children?: ReactNode;\n}\n\ninterface Owned {\n readonly session: PdfSession;\n dispose(): void;\n}\n\n/**\n * Creates what the provider owns. Nothing touches the DOM until a document\n * opens, so this is safe during server rendering (ADR 0007).\n */\nfunction own(props: PdfSessionSource): Owned {\n const assets = props.assetsUrl === undefined ? {} : { assetsUrl: props.assetsUrl };\n // A relative assetsUrl, such as \"/pdf-sdk/\", is resolved when a worker\n // starts, in the browser, so this is safe on a server too (sdk-core ADR\n // 0038). A query or fragment throws TypeError as the provider renders.\n const engine = props.engine ?? createPdfJsEngine(assets);\n const processor = props.processor ?? createPdfProcessor(assets);\n const session = createPdfSession({\n engine,\n processor,\n ...(props.filePolicy ? { filePolicy: props.filePolicy } : {}),\n ...(props.onEvent ? { onEvent: props.onEvent } : {}),\n });\n return {\n session,\n dispose() {\n void session.close();\n // Only what the provider created itself is destroyed.\n if (!props.engine) void engine.destroy();\n if (!props.processor) void processor.destroy();\n },\n };\n}\n\n/** What {@link useProvidedSession} reads: the provider's session props. */\nexport type PdfSessionSource = Omit<PdfSessionProviderProps, \"messages\" | \"locale\" | \"children\">;\n\n/**\n * The session a provider gives its components: the one passed in, or one it\n * creates from the options and releases when it unmounts. Shared by\n * `PdfSessionProvider` and `PdfEditor`, which builds its own messages.\n */\nexport function useProvidedSession(props: PdfSessionSource): PdfSession {\n const given = props.session;\n const [owned] = useState(() => (given ? undefined : own(props)));\n\n useEffect(() => {\n if (!owned) return;\n // React's development mode unmounts and mounts again at once, so the\n // disposal waits a tick, and a remount cancels it.\n const pending = (owned as Owned & { pending?: ReturnType<typeof setTimeout> }).pending;\n if (pending !== undefined) clearTimeout(pending);\n return () => {\n (owned as Owned & { pending?: ReturnType<typeof setTimeout> }).pending = setTimeout(\n () => owned.dispose(),\n 0,\n );\n };\n }, [owned]);\n\n return given ?? (owned as Owned).session;\n}\n\n/**\n * Makes a PDF session and the SDK's text available to the components and\n * hooks below it, such as `PdfViewer` and `usePdfDocument` (ADR 0008).\n *\n * @example\n * ```tsx\n * <PdfSessionProvider locale=\"de\" messages={{ \"viewer.empty\": \"Kein Dokument geöffnet.\" }}>\n * <PdfViewer />\n * </PdfSessionProvider>\n * ```\n *\n * @public\n */\nexport function PdfSessionProvider(props: PdfSessionProviderProps): ReactNode {\n const { messages: overrides, locale = \"en\", children } = props;\n const session = useProvidedSession(props);\n const messages = useMemo(\n () =>\n createMessages(pdfEditorMessages, {\n locale,\n ...(overrides ? { overrides } : {}),\n }),\n [locale, overrides],\n );\n const value = useMemo(() => ({ session, messages }), [session, messages]);\n return <PdfContext.Provider value={value}>{children}</PdfContext.Provider>;\n}\n","/**\n * How wide a vertical scrollbar of `container` is, in pixels, measured with a\n * hidden probe inside it, so the page's scrollbar styles and the container's\n * `scrollbar-width` apply. 0 with overlay scrollbars, which take no space.\n */\nexport function scrollbarThickness(container: HTMLElement): number {\n const probe = document.createElement(\"div\");\n probe.style.cssText =\n \"position: absolute; top: 0; left: 0; width: 100px; height: 100px; overflow: scroll; visibility: hidden; pointer-events: none;\";\n probe.style.setProperty(\n \"scrollbar-width\",\n getComputedStyle(container).getPropertyValue(\"scrollbar-width\") || \"auto\",\n );\n container.append(probe);\n const thickness = probe.offsetWidth - probe.clientWidth;\n probe.remove();\n return thickness;\n}\n\n/**\n * The width to lay content out at inside `container`, a scroll container\n * whose content is `measured` pixels wide right now: as if its scrollbar\n * were always shown. Pages sized to a container's width get shorter when a\n * scrollbar that takes space appears; if that makes them fit, it goes, they\n * grow, and it comes back, every frame. Sizing them as if it were always\n * there keeps their width, whether it shows or not.\n */\nexport function steadyWidth(container: HTMLElement, measured: number, thickness: number): number {\n const style = getComputedStyle(container);\n const borders =\n Number.parseFloat(style.borderLeftWidth) + Number.parseFloat(style.borderRightWidth);\n const shown = container.offsetWidth - container.clientWidth - borders;\n return Math.max(0, measured - Math.max(0, thickness - shown));\n}\n","import { type RefObject, useCallback, useEffect, useRef, useState } from \"react\";\n\n/**\n * One `IntersectionObserver` for every page of a scrolling container: a\n * page counts as near within one container height above or below it, so it\n * can be drawn before it scrolls into view. Returns the function pages\n * register with.\n */\nexport function useNearObserver(\n root: RefObject<Element | null>,\n): (element: Element, onNear: (near: boolean) => void) => () => void {\n const observer = useRef<IntersectionObserver>(undefined);\n const callbacks = useRef(new Map<Element, (near: boolean) => void>());\n\n useEffect(() => {\n const created = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) callbacks.current.get(entry.target)?.(entry.isIntersecting);\n },\n { root: root.current, rootMargin: \"100% 0px\" },\n );\n observer.current = created;\n for (const element of callbacks.current.keys()) created.observe(element);\n return () => created.disconnect();\n }, [root]);\n\n return useCallback((element: Element, onNear: (near: boolean) => void) => {\n callbacks.current.set(element, onNear);\n observer.current?.observe(element);\n return () => {\n callbacks.current.delete(element);\n observer.current?.unobserve(element);\n };\n }, []);\n}\n\n/**\n * Whether an element registered with a near observer is near the viewport.\n * It's observed only once `sized` is true, meaning the page placeholders\n * have their real size: before the container's width is known every\n * placeholder is empty, so every page would count as near and start reading\n * and drawing at once. It stops being near when it stops being sized, such\n * as when its container is hidden.\n */\nexport function useNear(\n observe: (element: Element, onNear: (near: boolean) => void) => () => void,\n element: RefObject<Element | null>,\n sized: boolean,\n): boolean {\n const [near, setNear] = useState(false);\n useEffect(() => {\n const target = element.current;\n if (!sized || !target) return;\n const stop = observe(target, setNear);\n return () => {\n stop();\n setNear(false);\n };\n }, [observe, element, sized]);\n return near;\n}\n","import { type RefObject, useEffect, useRef, useState } from \"react\";\nimport type { PdfPageInfo } from \"../core/model/document.js\";\nimport type { PdfSession } from \"../core/session/session.js\";\nimport type { RenderQueue } from \"./viewer/render-queue.js\";\n\n/** What {@link usePageDrawing} needs. */\nexport interface PageDrawingOptions {\n readonly session: PdfSession;\n readonly pageKey: string;\n /** The plan's rotation of the page, so a change re-reads its size. */\n readonly rotation: number;\n /** Whether the page is near the viewport, and should be drawn. */\n readonly near: boolean;\n /** The page's CSS width on screen. */\n readonly displayWidth: number;\n readonly queue: RenderQueue;\n /** Called with the page's size and rotation once they're read. */\n readonly onMeasured?: (info: PdfPageInfo) => void;\n}\n\n/**\n * Shows a finished drawing: the visible canvas takes the buffer's size and\n * pixels in one task, so the browser never paints it cleared.\n */\nfunction present(buffer: HTMLCanvasElement, target: HTMLCanvasElement): void {\n target.width = buffer.width;\n target.height = buffer.height;\n target.style.width = buffer.style.width;\n target.style.height = buffer.style.height;\n target.getContext(\"2d\")?.drawImage(buffer, 0, 0);\n}\n\n/** A page's drawing state. */\nexport interface PageDrawing {\n readonly canvas: RefObject<HTMLCanvasElement | null>;\n readonly info: PdfPageInfo | undefined;\n readonly drawn: boolean;\n readonly failure: unknown;\n}\n\n/**\n * Draws one plan page into a canvas while it's near the viewport (docs/adr/0003):\n * reads its size when it first comes near and when its rotation changes,\n * queues the drawing with the component's other pages, redraws when its\n * size changes, cancels when it leaves, and gives the canvas's pixels back.\n * Shared by the viewer and the thumbnails.\n */\nexport function usePageDrawing(options: PageDrawingOptions): PageDrawing {\n const { session, pageKey, rotation, near, displayWidth, queue, onMeasured } = options;\n const canvas = useRef<HTMLCanvasElement>(null);\n const [info, setInfo] = useState<PdfPageInfo>();\n const [drawn, setDrawn] = useState(false);\n const [failure, setFailure] = useState<unknown>();\n const measured = useRef(onMeasured);\n measured.current = onMeasured;\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: a new rotation must re-read the page\n useEffect(() => {\n if (!near) return;\n const controller = new AbortController();\n session.getPage(pageKey, { signal: controller.signal }).then(\n (read) => {\n setInfo(read);\n measured.current?.(read);\n },\n (reason: unknown) => {\n if (!controller.signal.aborted) setFailure(reason);\n },\n );\n return () => controller.abort();\n }, [near, session, pageKey, rotation]);\n\n useEffect(() => {\n const target = canvas.current;\n if (!near || !info || !target || displayWidth <= 0) return;\n const turned = info.rotation === 90 || info.rotation === 270;\n const scale = displayWidth / (turned ? info.height : info.width);\n const render = queue.schedule(async (signal) => {\n // Drawn off screen, then copied in at once: an engine sizes its canvas\n // when it starts, which clears it, so drawing on screen would show a\n // blank page until the redraw finishes, as when the width settles.\n const buffer = document.createElement(\"canvas\");\n try {\n await session.renderPage(pageKey, buffer, {\n scale,\n pixelRatio: globalThis.devicePixelRatio || 1,\n signal,\n });\n if (!signal.aborted) {\n present(buffer, target);\n setDrawn(true);\n setFailure(undefined);\n }\n } catch (reason) {\n if (!signal.aborted) setFailure(reason);\n } finally {\n // Its pixels are copied or not needed; give them back now.\n buffer.width = 0;\n buffer.height = 0;\n }\n });\n return () => render.cancel();\n }, [near, info, displayWidth, session, pageKey, queue]);\n\n // A page that scrolls away gives its pixels back.\n useEffect(() => {\n if (near) return;\n const target = canvas.current;\n if (target) {\n target.width = 0;\n target.height = 0;\n }\n setDrawn(false);\n }, [near]);\n\n return { canvas, info, drawn, failure };\n}\n","import type { PdfRotation } from \"../../core/model/geometry.js\";\n\n/** A page's box on screen, and how to lay the unrotated page over it. */\nexport interface PageGeometry {\n /** The page's width and height on screen, after rotation, in CSS pixels. */\n readonly width: number;\n readonly height: number;\n /** The unrotated page's width and height, in CSS pixels. */\n readonly pageWidth: number;\n readonly pageHeight: number;\n /**\n * The CSS transform that puts a layer of the unrotated page's size, with\n * its origin at its top-left corner, over the rotated page, so overlays\n * positioned in unrotated page fractions land where the page shows them.\n */\n readonly transform: string;\n}\n\n/**\n * Lays out a page of `width` × `height` points, shown with `rotation`, at a\n * given CSS width.\n */\nexport function pageGeometry(\n size: { readonly width: number; readonly height: number },\n rotation: PdfRotation,\n displayWidth: number,\n): PageGeometry {\n const turned = rotation === 90 || rotation === 270;\n const scale = displayWidth / (turned ? size.height : size.width);\n const pageWidth = size.width * scale;\n const pageHeight = size.height * scale;\n const width = turned ? pageHeight : pageWidth;\n const height = turned ? pageWidth : pageHeight;\n const transform = {\n 0: \"none\",\n 90: `translate(${width}px, 0) rotate(90deg)`,\n 180: `translate(${width}px, ${height}px) rotate(180deg)`,\n 270: `translate(0, ${height}px) rotate(270deg)`,\n }[rotation];\n return { width, height, pageWidth, pageHeight, transform };\n}\n","/** A queued render; cancelling it stops it, whether it's waiting or running. */\nexport interface QueuedRender {\n cancel(): void;\n}\n\ntype Task = (signal: AbortSignal) => Promise<void>;\n\n/**\n * Runs at most `limit` page renders at once. The page asked for last starts\n * first, because it's usually the one the user just scrolled to, and a page\n * that scrolls away is cancelled, whether it's waiting or running.\n */\nexport class RenderQueue {\n readonly #limit: number;\n #running = 0;\n readonly #waiting: { task: Task; controller: AbortController }[] = [];\n\n constructor(limit = 2) {\n this.#limit = Math.max(1, limit);\n }\n\n schedule(task: Task): QueuedRender {\n const entry = { task, controller: new AbortController() };\n this.#waiting.push(entry);\n this.#next();\n return {\n cancel: () => {\n const index = this.#waiting.indexOf(entry);\n if (index >= 0) this.#waiting.splice(index, 1);\n entry.controller.abort();\n },\n };\n }\n\n #next(): void {\n while (this.#running < this.#limit && this.#waiting.length > 0) {\n const entry = this.#waiting.pop() as { task: Task; controller: AbortController };\n this.#running += 1;\n void entry\n .task(entry.controller.signal)\n .catch(() => {})\n .finally(() => {\n this.#running -= 1;\n this.#next();\n });\n }\n }\n}\n","import {\n Component,\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type RefObject,\n useCallback,\n useEffect,\n useId,\n useRef,\n useState,\n} from \"react\";\nimport type { PdfPageInfo } from \"../../core/model/document.js\";\nimport type { PdfPlanPage } from \"../../core/model/plan.js\";\nimport type { PdfSession } from \"../../core/session/session.js\";\nimport { usePdfDocument, usePdfMessages, usePdfSession } from \"../hooks.js\";\nimport { scrollbarThickness, steadyWidth } from \"../scrollbar.js\";\nimport { useNear, useNearObserver } from \"../use-near-observer.js\";\nimport { usePageDrawing } from \"../use-page-drawing.js\";\nimport { pageGeometry } from \"../viewer/geometry.js\";\nimport { RenderQueue } from \"../viewer/render-queue.js\";\n\n/**\n * The parts of `PdfThumbnails` that take extra classes through `classNames`.\n *\n * @public\n */\nexport type PdfThumbnailsPart = \"root\" | \"thumbnail\" | \"frame\" | \"canvas\" | \"number\";\n\n/**\n * Props for {@link PdfThumbnails}.\n *\n * @public\n */\nexport interface PdfThumbnailsProps {\n /** Extra classes on the root. */\n readonly className?: string;\n /** Extra classes on each part. */\n readonly classNames?: Readonly<Partial<Record<PdfThumbnailsPart, string>>>;\n /** Drop the visual styles, keeping layout and accessibility. */\n readonly unstyled?: boolean;\n /** How many thumbnails are drawn at once. Defaults to 2. */\n readonly concurrency?: number;\n /**\n * Runs when the user presses Delete or Backspace in the list, such as the\n * editor's delete tool. Without it, those keys do nothing here.\n */\n readonly onDelete?: () => void;\n /**\n * Runs when the user presses Alt+↑ or Alt+↓ (Option on macOS) in the list,\n * such as the editor's move tools. Without it, those keys do nothing here.\n */\n readonly onMove?: (direction: \"earlier\" | \"later\") => void;\n}\n\nconst LETTER = { width: 612, height: 792 };\n\n/** The key of the thumbnail in `root` that has focus, if one has. */\nfunction focusedThumbnail(root: HTMLElement | null): string | undefined {\n if (!root) return undefined;\n const active = document.activeElement;\n if (!(active instanceof HTMLElement) || !root.contains(active)) return undefined;\n return active.dataset[\"hmPageKey\"];\n}\n\ninterface FocusKeeperProps {\n readonly root: RefObject<HTMLDivElement | null>;\n readonly keys: readonly string[];\n /** Where focus goes if the focused thumbnail left the plan. */\n readonly fallback: string | undefined;\n}\n\n/**\n * Keeps focus in the list when the thumbnail that has it is moved, which\n * takes focus from it in some browsers, or leaves the plan: deleted, or\n * undone (docs/adr/0008). Focus goes back to it, or to the current page's\n * thumbnail, never to the page's body.\n *\n * A class, for `getSnapshotBeforeUpdate`: React calls it for the whole tree\n * before a commit changes the DOM, so it reads which thumbnail had focus\n * without reading the DOM or writing a ref during render. It covers every\n * way a thumbnail can move or go: keys, the toolbar, undo and the host's\n * own calls. If focus was elsewhere, such as on the host's page, nothing\n * was recorded and nothing is taken back. It renders nothing.\n */\nclass FocusKeeper extends Component<FocusKeeperProps> {\n override getSnapshotBeforeUpdate(): string | null {\n return focusedThumbnail(this.props.root.current) ?? null;\n }\n\n override componentDidUpdate(\n _props: FocusKeeperProps,\n _state: unknown,\n focused: string | null,\n ): void {\n const element = this.props.root.current;\n if (!focused || !element) return;\n const now = document.activeElement;\n if (now !== null && now !== document.body) return;\n const target = this.props.keys.includes(focused) ? focused : this.props.fallback;\n if (!target) return;\n element.querySelector<HTMLElement>(`[data-hm-page-key=\"${CSS.escape(target)}\"]`)?.focus();\n }\n\n override render(): null {\n return null;\n }\n}\nconst join = (...names: (string | undefined)[]) => names.filter(Boolean).join(\" \");\n\ninterface ThumbnailProps {\n readonly page: PdfPlanPage;\n readonly index: number;\n readonly count: number;\n readonly id: string;\n readonly selected: boolean;\n readonly current: boolean;\n readonly active: boolean;\n readonly displayWidth: number;\n readonly estimate: { readonly width: number; readonly height: number };\n readonly observe: (element: Element, onNear: (near: boolean) => void) => () => void;\n readonly queue: RenderQueue;\n readonly session: PdfSession;\n readonly onMeasured: (info: PdfPageInfo) => void;\n readonly onPointer: (index: number, event: MouseEvent) => void;\n readonly classNames: Readonly<Partial<Record<PdfThumbnailsPart, string>>>;\n}\n\nfunction Thumbnail(props: ThumbnailProps): ReactNode {\n const { page, index, count, id, selected, current, active, displayWidth, classNames } = props;\n const messages = usePdfMessages();\n const element = useRef<HTMLDivElement>(null);\n const near = useNear(props.observe, element, displayWidth > 0);\n const { canvas, info, drawn } = usePageDrawing({\n session: props.session,\n pageKey: page.key,\n rotation: page.rotation,\n near,\n displayWidth,\n queue: props.queue,\n onMeasured: props.onMeasured,\n });\n const geometry = pageGeometry(info ?? { ...props.estimate }, info?.rotation ?? 0, displayWidth);\n\n return (\n // The listbox handles the keyboard for every option (ADR 0014), as the\n // WAI-ARIA listbox pattern does with roving focus.\n // biome-ignore lint/a11y/useKeyWithClickEvents: the parent listbox handles keys for its options\n <div\n ref={element}\n id={id}\n role=\"option\"\n aria-selected={selected}\n aria-current={current ? \"true\" : undefined}\n aria-label={messages.t(\"thumbnails.page\", { page: index + 1, count })}\n aria-busy={near && !drawn}\n tabIndex={active ? 0 : -1}\n className={join(\"hm-pdf-thumbnail\", classNames.thumbnail)}\n data-hm-page-key={page.key}\n onClick={(event) => props.onPointer(index, event)}\n >\n <div\n className={join(\"hm-pdf-thumbnail-frame\", classNames.frame)}\n style={{ width: `${geometry.width}px`, height: `${geometry.height}px` }}\n >\n {/* biome-ignore lint/a11y/noAriaHiddenOnFocusable: the canvas is pixels only and never focusable */}\n <canvas\n ref={canvas}\n aria-hidden=\"true\"\n className={join(\"hm-pdf-thumbnail-canvas\", classNames.canvas)}\n />\n </div>\n <span aria-hidden=\"true\" className={join(\"hm-pdf-thumbnail-number\", classNames.number)}>\n {messages.t(\"thumbnails.number\", { page: index + 1 })}\n </span>\n </div>\n );\n}\n\n/**\n * A column of page thumbnails to see the whole document and choose pages\n * (ADR 0014): a listbox with several pages selectable, where the selection\n * follows focus and the chosen page is brought into view in `PdfViewer`.\n * Like the viewer, it only draws the thumbnails near its viewport.\n *\n * Keyboard: the arrow keys, Home and End move to a page, select it and show\n * it; with Shift they extend the selection; with Ctrl or ⌘ they move without\n * selecting, and Space then adds or removes the page. Ctrl or ⌘ + A selects\n * every page, and Escape keeps only the focused one. Delete and Backspace,\n * and Alt or Option with ↑ and ↓, run `onDelete` and `onMove` when given.\n * With a pointer: click,\n * Ctrl or ⌘ + click, and Shift + click.\n *\n * @public\n */\nexport function PdfThumbnails(props: PdfThumbnailsProps): ReactNode {\n const { className, classNames = {}, unstyled = false, concurrency = 2, onDelete, onMove } = props;\n const session = usePdfSession();\n const snapshot = usePdfDocument();\n const messages = usePdfMessages();\n const root = useRef<HTMLDivElement>(null);\n const prefix = useId();\n const observe = useNearObserver(root);\n const [queue] = useState(() => new RenderQueue(concurrency));\n const [width, setWidth] = useState(0);\n const [estimate, setEstimate] = useState(LETTER);\n const [activeKey, setActiveKey] = useState<string>();\n const anchor = useRef<string | undefined>(undefined);\n const { plan, selection, currentPage } = snapshot;\n const keys = plan.pages.map((page) => page.key);\n const active = activeKey && keys.includes(activeKey) ? activeKey : (currentPage ?? keys[0]);\n const activeIndex = active ? keys.indexOf(active) : -1;\n\n useEffect(() => {\n const element = root.current;\n if (!element) return;\n // Sized as if a scrollbar were shown, so one coming and going doesn't\n // resize the thumbnails, and with them the list, every frame.\n const thickness = scrollbarThickness(element);\n const observer = new ResizeObserver(([entry]) => {\n if (entry) setWidth(steadyWidth(element, entry.contentRect.width, thickness));\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n\n // Follows the viewer: the current page's thumbnail scrolls into view,\n // unless the user is working in this list.\n useEffect(() => {\n const element = root.current;\n if (!element || !currentPage || element.contains(document.activeElement)) return;\n element\n .querySelector<HTMLElement>(`[data-hm-page-key=\"${CSS.escape(currentPage)}\"]`)\n ?.scrollIntoView({ block: \"nearest\" });\n }, [currentPage]);\n\n const onMeasured = useCallback((info: PdfPageInfo) => {\n setEstimate((current) =>\n current === LETTER ? { width: info.width, height: info.height } : current,\n );\n }, []);\n\n const focus = (index: number) => {\n const key = keys[index];\n if (!key) return;\n setActiveKey(key);\n root.current?.querySelector<HTMLElement>(`[data-hm-page-key=\"${CSS.escape(key)}\"]`)?.focus();\n };\n\n /** Selects from the anchor to `index`, or `index` alone, and shows the page. */\n const choose = (index: number, mode: \"only\" | \"range\" | \"toggle\" | \"focus\") => {\n const key = keys[index];\n if (!key) return;\n focus(index);\n if (mode === \"focus\") return;\n if (mode === \"toggle\") {\n session.select(\n selection.includes(key) ? selection.filter((k) => k !== key) : [...selection, key],\n );\n anchor.current = key;\n return;\n }\n if (mode === \"range\" && anchor.current && keys.includes(anchor.current)) {\n const from = keys.indexOf(anchor.current);\n const [start, end] = from < index ? [from, index] : [index, from];\n session.select(keys.slice(start, end + 1));\n } else {\n session.select([key]);\n anchor.current = key;\n }\n session.goToPage(key);\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n if (keys.length === 0) return;\n const modifier = event.ctrlKey || event.metaKey;\n // Alt or Option with ↑ or ↓ moves pages, and never moves focus.\n if (event.altKey && (event.key === \"ArrowUp\" || event.key === \"ArrowDown\")) {\n if (onMove && !modifier && !event.shiftKey) {\n event.preventDefault();\n onMove(event.key === \"ArrowUp\" ? \"earlier\" : \"later\");\n }\n return;\n }\n const move = (index: number) => {\n event.preventDefault();\n const target = Math.max(0, Math.min(keys.length - 1, index));\n choose(target, event.shiftKey ? \"range\" : modifier ? \"focus\" : \"only\");\n };\n switch (event.key) {\n case \"ArrowDown\":\n case \"ArrowRight\":\n move(activeIndex + 1);\n break;\n case \"ArrowUp\":\n case \"ArrowLeft\":\n move(activeIndex - 1);\n break;\n case \"Home\":\n move(0);\n break;\n case \"End\":\n move(keys.length - 1);\n break;\n case \" \":\n event.preventDefault();\n if (activeIndex >= 0) choose(activeIndex, \"toggle\");\n break;\n case \"Escape\":\n if (active) session.select([active]);\n break;\n case \"Delete\":\n case \"Backspace\":\n if (onDelete && !event.altKey && !modifier && !event.shiftKey) {\n event.preventDefault();\n onDelete();\n }\n break;\n case \"a\":\n case \"A\":\n if (modifier) {\n event.preventDefault();\n session.select(keys);\n }\n break;\n }\n };\n\n const onPointer = (index: number, event: MouseEvent) => {\n choose(index, event.shiftKey ? \"range\" : event.ctrlKey || event.metaKey ? \"toggle\" : \"only\");\n };\n\n return (\n <div\n ref={root}\n role=\"listbox\"\n aria-label={messages.t(\"thumbnails.label\")}\n aria-multiselectable=\"true\"\n aria-orientation=\"vertical\"\n tabIndex={keys.length === 0 ? 0 : -1}\n onKeyDown={onKeyDown}\n className={join(\"hm-pdf-thumbnails\", className, classNames.root)}\n {...(unstyled ? { \"data-hm-unstyled\": \"\" } : {})}\n >\n {plan.pages.map((page, index) => (\n <Thumbnail\n key={page.key}\n page={page}\n index={index}\n count={keys.length}\n id={`${prefix}-${page.key}`}\n selected={selection.includes(page.key)}\n current={page.key === currentPage}\n active={page.key === active}\n displayWidth={width}\n estimate={estimate}\n observe={observe}\n queue={queue}\n session={session}\n onMeasured={onMeasured}\n onPointer={onPointer}\n classNames={classNames}\n />\n ))}\n <FocusKeeper root={root} keys={keys} fallback={active} />\n </div>\n );\n}\n","import {\n DeleteIcon,\n DownloadIcon,\n type IconComponent,\n MoveDownIcon,\n MoveUpIcon,\n OpenIcon,\n PageAddIcon,\n RedoIcon,\n RotateLeftIcon,\n RotateRightIcon,\n UndoIcon,\n} from \"@hussmartinez/ui/react\";\n\n/**\n * The components of the icons the editor's tools name, from ui's set\n * (sdk-core ADR 0030). A host's `icons` prop overrides any of them.\n *\n * @public\n */\nexport const pdfIcons: Readonly<Record<string, IconComponent>> = {\n open: OpenIcon,\n undo: UndoIcon,\n redo: RedoIcon,\n \"rotate-left\": RotateLeftIcon,\n \"rotate-right\": RotateRightIcon,\n delete: DeleteIcon,\n download: DownloadIcon,\n \"page-add\": PageAddIcon,\n \"move-up\": MoveUpIcon,\n \"move-down\": MoveDownIcon,\n};\n","/**\n * Keys that run a tool only while focus is in the thumbnails, where the\n * selection is shown, by tool ID, as `aria-keyshortcuts` gives them. The\n * toolbar advertises them on the tools' buttons; the tools register no\n * editor-wide shortcut (docs/adr/0008).\n */\nexport const THUMBNAIL_KEYS: Readonly<Record<string, string>> = {\n \"pdf.delete-pages\": \"Delete Backspace\",\n \"pdf.move-earlier\": \"Alt+ArrowUp\",\n \"pdf.move-later\": \"Alt+ArrowDown\",\n};\n","import type { ShortcutRegistry, ToolRegistry } from \"@hussmartinez/sdk-core\";\nimport { IconButton, type IconComponent, Toolbar, ToolbarGroup } from \"@hussmartinez/ui/react\";\nimport type { ReactNode } from \"react\";\nimport { THUMBNAIL_KEYS } from \"../../features/pages/thumbnail-keys.js\";\nimport type { PdfTool, PdfToolContext } from \"../../features/tool-types.js\";\nimport { usePdfDocument, usePdfMessages } from \"../hooks.js\";\n\n/**\n * Props for {@link PdfToolbar}.\n *\n * @public\n */\nexport interface PdfToolbarProps {\n /** The editor's tools, from `createToolRegistry`. */\n readonly registry: ToolRegistry<PdfTool>;\n /** The editor's shortcuts, for each button's `aria-keyshortcuts`. */\n readonly shortcuts?: ShortcutRegistry;\n /** What the tools run against. */\n readonly context: PdfToolContext;\n /** Icon components by name. */\n readonly icons: Readonly<Record<string, IconComponent>>;\n /** Whether the editor is saving, which tools read as `saving`. */\n readonly saving?: boolean;\n /** Whether the editor is inserting a document, which tools read as `inserting`. */\n readonly inserting?: boolean;\n /** Runs a tool. Defaults to running it against `context`. */\n readonly onRun?: (tool: PdfTool) => void;\n /** Extra classes on the root. */\n readonly className?: string;\n}\n\n/**\n * The editor's toolbar: ui's `Toolbar`, one labelled group per toolbar group\n * of the registry and one button per tool, disabled when the tool can't\n * run, with the tool's shortcuts as `aria-keyshortcuts`. Arrow keys move\n * between the buttons, as ui's toolbar does, so it's one tab stop.\n *\n * @public\n */\nexport function PdfToolbar(props: PdfToolbarProps): ReactNode {\n const {\n registry,\n shortcuts,\n context,\n icons,\n onRun,\n className,\n saving = false,\n inserting = false,\n } = props;\n const messages = usePdfMessages();\n const snapshot = usePdfDocument();\n const state = { snapshot, saving, inserting };\n // Tool labels and group names are keys of the catalogue, checked when the\n // tool is defined; custom keys a host adds fall back to the key itself.\n const t = messages.t as (key: string) => string;\n const run = onRun ?? ((tool: PdfTool) => void tool.run(context));\n if (registry.toolbar.length === 0) return null;\n return (\n <Toolbar label={messages.t(\"toolbar.label\")} {...(className ? { className } : {})}>\n {registry.toolbar.map((group) => (\n <ToolbarGroup\n key={group.map((tool) => tool.id).join(\" \")}\n label={t(`toolbar.groups.${group[0]?.group ?? \"other\"}`)}\n >\n {group\n .filter((tool) => tool.isAvailable?.(state) ?? true)\n .map((tool) => {\n const Icon = icons[tool.icon];\n const keys = shortcuts?.ariaKeyShortcuts(tool.id) ?? THUMBNAIL_KEYS[tool.id];\n return (\n <IconButton\n key={tool.id}\n data-hm-tool={tool.id}\n label={t(tool.label)}\n icon={Icon ? <Icon /> : null}\n disabled={!(tool.isEnabled?.(state) ?? true)}\n // A button that becomes disabled keeps focus, so keyboard\n // users stay in the toolbar (docs/adr/0008).\n focusableWhenDisabled\n {...(keys ? { \"aria-keyshortcuts\": keys } : {})}\n onClick={() => run(tool)}\n />\n );\n })}\n </ToolbarGroup>\n ))}\n </Toolbar>\n );\n}\n","import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport type { PdfLink, PdfPageInfo, PdfTextContent } from \"../../core/model/document.js\";\nimport { linkDestination, safeLinkUrl } from \"../../core/model/links.js\";\nimport type { PdfPlanPage } from \"../../core/model/plan.js\";\nimport { usePdfMessages, usePdfSession } from \"../hooks.js\";\nimport { useNear } from \"../use-near-observer.js\";\nimport { usePageDrawing } from \"../use-page-drawing.js\";\nimport { pageGeometry } from \"./geometry.js\";\nimport type { RenderQueue } from \"./render-queue.js\";\nimport type { PdfViewerClassNames } from \"./types.js\";\n\nexport interface PageProps {\n readonly page: PdfPlanPage;\n readonly number: number;\n readonly count: number;\n /** The page's CSS width on screen. */\n readonly displayWidth: number;\n /** A page size to lay out with until this page's own is known. */\n readonly estimate: { readonly width: number; readonly height: number };\n readonly observe: (element: Element, onNear: (near: boolean) => void) => () => void;\n readonly queue: RenderQueue;\n readonly onMeasured: (info: PdfPageInfo) => void;\n readonly classNames: PdfViewerClassNames;\n}\n\nconst join = (...names: (string | undefined)[]) => names.filter(Boolean).join(\" \");\n\n/** One page: a placeholder of the right size, drawn only while near the viewport. */\nexport function PdfViewerPage(props: PageProps): ReactNode {\n const { page, number, count, displayWidth, estimate, observe, queue, onMeasured, classNames } =\n props;\n const session = usePdfSession();\n const messages = usePdfMessages();\n const element = useRef<HTMLDivElement>(null);\n const textLayer = useRef<HTMLDivElement>(null);\n const near = useNear(observe, element, displayWidth > 0);\n const [text, setText] = useState<PdfTextContent>();\n const [links, setLinks] = useState<readonly PdfLink[]>([]);\n const { canvas, info, drawn, failure } = usePageDrawing({\n session,\n pageKey: page.key,\n rotation: page.rotation,\n near,\n displayWidth,\n queue,\n onMeasured,\n });\n\n // The text and links, which don't depend on the zoom, read once.\n useEffect(() => {\n if (!near || text) return;\n const controller = new AbortController();\n const signal = controller.signal;\n Promise.all([\n session.getTextContent(page.key, { signal }),\n session.getLinks(page.key, { signal }),\n ]).then(\n ([content, found]) => {\n setText(content);\n setLinks(found);\n },\n () => {},\n );\n return () => controller.abort();\n }, [near, session, page.key, text]);\n\n const size = info ?? { ...estimate, rotation: 0 };\n const geometry = pageGeometry(size, info?.rotation ?? 0, displayWidth);\n\n // Each run of text is stretched to the width the document gives it, so\n // selections line up with the drawn glyphs.\n useLayoutEffect(() => {\n const layer = textLayer.current;\n if (!layer || !text) return;\n for (const span of layer.querySelectorAll<HTMLElement>(\"[data-hm-width]\")) {\n span.style.transform = \"\";\n const natural = span.getBoundingClientRect().width;\n const wanted = Number(span.dataset[\"hmWidth\"]) * geometry.pageWidth;\n if (natural > 0 && wanted > 0) span.style.transform = `scaleX(${wanted / natural})`;\n }\n }, [text, geometry.pageWidth]);\n\n const overlay = {\n width: `${geometry.pageWidth}px`,\n height: `${geometry.pageHeight}px`,\n transform: geometry.transform,\n };\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a page is a labelled group, not a form fieldset\n <div\n ref={element}\n role=\"group\"\n aria-label={messages.t(\"viewer.page\", { page: number, count })}\n aria-busy={near && !drawn && !failure}\n className={join(\"hm-pdf-page\", classNames.page)}\n data-hm-page-key={page.key}\n style={{ width: `${geometry.width}px`, height: `${geometry.height}px` }}\n >\n {/* biome-ignore lint/a11y/noAriaHiddenOnFocusable: the canvas is pixels only and never focusable; the text layer carries the words */}\n <canvas\n ref={canvas}\n aria-hidden=\"true\"\n className={join(\"hm-pdf-page-canvas\", classNames.canvas)}\n />\n {failure !== undefined ? (\n <p role=\"alert\" className={join(\"hm-pdf-page-error\", classNames.error)}>\n {messages.error(failure)}\n </p>\n ) : null}\n {near && text ? (\n <div\n ref={textLayer}\n className={join(\"hm-pdf-text-layer\", classNames.textLayer)}\n style={overlay}\n >\n {text.items.map((item, index) => (\n <span\n // The items of a page never change order.\n // biome-ignore lint/suspicious/noArrayIndexKey: the index is the item's identity\n key={index}\n data-hm-width={item.rect.width}\n style={{\n left: `${item.rect.x * 100}%`,\n top: `${item.rect.y * 100}%`,\n fontSize: `${item.rect.height * geometry.pageHeight}px`,\n lineHeight: 1,\n }}\n >\n {item.text}\n {item.endOfLine ? \"\\n\" : \"\"}\n </span>\n ))}\n </div>\n ) : null}\n {near && links.length > 0 ? (\n <div className={join(\"hm-pdf-link-layer\", classNames.linkLayer)} style={overlay}>\n {links.map((link, index) => {\n // Checked again here, whatever the engine is (ADR 0012).\n const href = safeLinkUrl(link.url);\n const destination = href && linkDestination(href);\n if (!href || !destination) return null;\n const email = href.startsWith(\"mailto:\");\n const label = email\n ? messages.t(\"viewer.emailLink\", { destination })\n : messages.t(\"viewer.webLink\", { destination });\n return (\n <a\n // biome-ignore lint/suspicious/noArrayIndexKey: links of a page never change order\n key={index}\n className={join(\"hm-pdf-link\", classNames.link)}\n href={href}\n target={email ? undefined : \"_blank\"}\n rel=\"noopener noreferrer\"\n referrerPolicy=\"no-referrer\"\n title={label}\n style={{\n left: `${link.rect.x * 100}%`,\n top: `${link.rect.y * 100}%`,\n width: `${link.rect.width * 100}%`,\n height: `${link.rect.height * 100}%`,\n }}\n >\n {/* The name says where the link really goes, whatever the page shows. */}\n <span className=\"hm-pdf-link-label\">{label}</span>\n </a>\n );\n })}\n </div>\n ) : null}\n </div>\n );\n}\n","import { type ReactNode, useCallback, useEffect, useRef, useState } from \"react\";\nimport type { PdfPageInfo } from \"../../core/model/document.js\";\nimport { usePdfDocument, usePdfMessages, usePdfSession } from \"../hooks.js\";\nimport { scrollbarThickness, steadyWidth } from \"../scrollbar.js\";\nimport { useNearObserver } from \"../use-near-observer.js\";\nimport { PdfViewerPage } from \"./PdfViewerPage.js\";\nimport { RenderQueue } from \"./render-queue.js\";\nimport type { PdfViewerClassNames } from \"./types.js\";\n\n/**\n * Props for {@link PdfViewer}.\n *\n * @public\n */\nexport interface PdfViewerProps {\n /** Extra classes on the root. */\n readonly className?: string;\n /** Extra classes on each part. */\n readonly classNames?: PdfViewerClassNames;\n /** Drop the visual styles, keeping layout and accessibility. */\n readonly unstyled?: boolean;\n /** Page width relative to the viewer's width. Defaults to 1, fitting the width. */\n readonly zoom?: number;\n /** How many page renders run at once. Defaults to 2. */\n readonly concurrency?: number;\n}\n\n/** US Letter, until the first page's size is known. */\nconst LETTER = { width: 612, height: 792 };\n\nconst join = (...names: (string | undefined)[]) => names.filter(Boolean).join(\" \");\n\n/**\n * Shows the session's pages in a scrolling column (docs/adr/0003): each page\n * keeps its place at the right size, and only pages near the viewport are\n * drawn, a few at a time. Pages that scroll away are cancelled or give their\n * pixels back. The text is selectable, for copying and for screen readers,\n * and links are real links, limited to safe URLs and labelled with where\n * they lead (ADR 0012, ADR 0014).\n *\n * The viewer is a focusable region, so keyboard users scroll it with the\n * arrow, Page Up, Page Down, Home and End keys.\n *\n * @public\n */\nexport function PdfViewer(props: PdfViewerProps): ReactNode {\n const { className, classNames = {}, unstyled = false, zoom = 1, concurrency = 2 } = props;\n const snapshot = usePdfDocument();\n const messages = usePdfMessages();\n const root = useRef<HTMLElement>(null);\n const pages = useRef<HTMLDivElement>(null);\n const [width, setWidth] = useState(0);\n const [estimate, setEstimate] = useState(LETTER);\n const [queue] = useState(() => new RenderQueue(concurrency));\n const observe = useNearObserver(root);\n const session = usePdfSession();\n\n // Scroll anchoring, the same in every engine (WebKit has none of its own):\n // the page at the top of the viewer stays where it is on screen while\n // sizes above it change, as placeholders take their real size and the\n // first page measured replaces the estimate. A navigation sets the anchor\n // to its page, so it lands on that page however late sizes arrive.\n const anchor = useRef<{ key: string; offset: number }>(undefined);\n // The scroll position the viewer set itself, so its own scrolls don't\n // move the anchor; only the user's do.\n const own = useRef<number>(undefined);\n // The scroll position the anchor was taken at. A different one means the\n // user scrolled since, and the anchor is out of date until it's measured.\n const anchoredAt = useRef<number>(undefined);\n\n const findPage = useCallback(\n (key: string) =>\n root.current?.querySelector<HTMLElement>(`[data-hm-page-key=\"${CSS.escape(key)}\"]`) ??\n undefined,\n [],\n );\n\n const scrollOwn = useCallback((element: HTMLElement, top: number) => {\n element.scrollTop = top;\n own.current = element.scrollTop;\n anchoredAt.current = element.scrollTop;\n }, []);\n\n useEffect(() => {\n const element = pages.current;\n if (!element) return;\n // Runs after layout and before paint, so a restored position never shows\n // the shifted one first.\n // Pages are sized as if the viewer's scrollbar were shown, so one coming\n // and going doesn't resize them, and with them the pages, every frame.\n const viewerElement = root.current;\n const thickness = viewerElement ? scrollbarThickness(viewerElement) : 0;\n const observer = new ResizeObserver(([entry]) => {\n if (entry) {\n setWidth(\n viewerElement\n ? steadyWidth(viewerElement, entry.contentRect.width, thickness)\n : entry.contentRect.width,\n );\n }\n const viewer = root.current;\n const held = anchor.current;\n if (!viewer || !held) return;\n // A scroll since the anchor was taken, not yet measured, is the user's:\n // restoring the anchor would undo it. Scrolling is measured once per\n // frame, and a resize can be reported before that frame. A position the browser clamped because the pages got\n // shorter isn't the user's, so the anchor still applies then.\n const at = anchoredAt.current;\n const bottom = viewer.scrollHeight - viewer.clientHeight;\n const clamped = at !== undefined && at > bottom && Math.abs(viewer.scrollTop - bottom) < 1;\n if (at !== undefined && Math.abs(viewer.scrollTop - at) >= 1 && !clamped) return;\n const page = findPage(held.key);\n if (!page) {\n anchor.current = undefined;\n return;\n }\n const top = page.offsetTop - held.offset;\n if (Math.abs(viewer.scrollTop - top) >= 1) scrollOwn(viewer, top);\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, [findPage, scrollOwn]);\n\n // The current page follows scrolling: the last page whose top has passed a\n // third of the way down the viewer. The anchor follows the user's\n // scrolling: the last page whose top is at or above the viewer's top.\n // Measured once per animation frame.\n useEffect(() => {\n const element = root.current;\n if (!element) return;\n let frame = 0;\n const measure = () => {\n frame = 0;\n const { scrollTop } = element;\n const line = scrollTop + element.clientHeight / 3;\n const user = own.current === undefined || Math.abs(scrollTop - own.current) >= 1;\n let current: HTMLElement | undefined;\n let top: HTMLElement | undefined;\n for (const page of element.querySelectorAll<HTMLElement>(\"[data-hm-page-key]\")) {\n if (page.offsetTop > line) break;\n current = page;\n if (page.offsetTop <= scrollTop || !top) top = page;\n }\n if (user) {\n own.current = undefined;\n anchor.current = top && {\n key: top.dataset[\"hmPageKey\"] as string,\n offset: top.offsetTop - scrollTop,\n };\n anchoredAt.current = scrollTop;\n }\n const key = current?.dataset[\"hmPageKey\"];\n if (key) session.setCurrentPage(key);\n };\n const onScroll = () => {\n frame ||= requestAnimationFrame(measure);\n };\n element.addEventListener(\"scroll\", onScroll, { passive: true });\n return () => {\n element.removeEventListener(\"scroll\", onScroll);\n cancelAnimationFrame(frame);\n };\n }, [session]);\n\n // A navigation request scrolls its page to the top, at once, which also\n // suits reduced motion, and anchors it there. Only a new request scrolls:\n // every snapshot has a new navigation object, but the same sequence number.\n const sequence = snapshot.navigation?.sequence;\n const target = snapshot.navigation?.page;\n useEffect(() => {\n const element = root.current;\n if (!element || sequence === undefined || target === undefined) return;\n const page = findPage(target);\n if (!page) return;\n const inset = Number.parseFloat(getComputedStyle(pages.current as Element).paddingTop) || 0;\n anchor.current = { key: target, offset: inset };\n scrollOwn(element, page.offsetTop - inset);\n }, [sequence, target, findPage, scrollOwn]);\n\n const onMeasured = useCallback((info: PdfPageInfo) => {\n setEstimate((current) =>\n current === LETTER ? { width: info.width, height: info.height } : current,\n );\n }, []);\n\n const { plan } = snapshot;\n const displayWidth = Math.max(0, width * zoom);\n\n return (\n <section\n ref={root}\n // A scrollable region keyboard users can focus (ADR 0014).\n // biome-ignore lint/a11y/noNoninteractiveTabindex: the region scrolls, so it must take focus\n tabIndex={0}\n aria-label={messages.t(\"viewer.label\")}\n className={join(\"hm-pdf-viewer\", className, classNames.root)}\n {...(unstyled ? { \"data-hm-unstyled\": \"\" } : {})}\n >\n <div ref={pages} className={join(\"hm-pdf-viewer-pages\", classNames.pages)}>\n {plan.pages.length === 0 ? (\n <p className={join(\"hm-pdf-viewer-empty\", classNames.empty)}>\n {messages.t(\"viewer.empty\")}\n </p>\n ) : (\n plan.pages.map((page, index) => (\n <PdfViewerPage\n key={page.key}\n page={page}\n number={index + 1}\n count={plan.pages.length}\n displayWidth={displayWidth}\n estimate={estimate}\n observe={observe}\n queue={queue}\n onMeasured={onMeasured}\n classNames={classNames}\n />\n ))\n )}\n </div>\n </section>\n );\n}\n","import {\n type ChangeEvent,\n type DragEvent,\n type ReactNode,\n type RefObject,\n useId,\n useRef,\n useState,\n} from \"react\";\nimport type { PdfError } from \"../../core/errors/pdf-error.js\";\nimport { usePdfMessages } from \"../hooks.js\";\n\ninterface StartProps {\n readonly error: PdfError | undefined;\n readonly onFile: (file: File) => void;\n readonly button: RefObject<HTMLButtonElement | null>;\n readonly className: string;\n readonly alertClassName: string;\n}\n\nconst hasFiles = (event: DragEvent) => event.dataTransfer.types.includes(\"Files\");\n\n/**\n * What the editor shows with no document open: a button that opens the\n * system's file picker, a drop zone around it, and the reason the last open\n * failed, if it did. The button is the keyboard and screen reader path; the\n * drop zone is a shortcut for pointer users, so it isn't focusable itself.\n */\nexport function PdfEditorStart(props: StartProps): ReactNode {\n const { error, onFile, button, className, alertClassName } = props;\n const messages = usePdfMessages();\n const input = useRef<HTMLInputElement>(null);\n const [dragging, setDragging] = useState(false);\n const titleId = useId();\n const hintId = useId();\n\n const choose = (event: ChangeEvent<HTMLInputElement>) => {\n const [file] = event.target.files ?? [];\n // Cleared so choosing the same file again still opens it.\n event.target.value = \"\";\n if (file) onFile(file);\n };\n\n const onDragOver = (event: DragEvent) => {\n if (!hasFiles(event)) return;\n event.preventDefault();\n event.dataTransfer.dropEffect = \"copy\";\n setDragging(true);\n };\n\n const onDragLeave = (event: DragEvent) => {\n // Leaving for a child isn't leaving the zone.\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;\n setDragging(false);\n };\n\n const onDrop = (event: DragEvent) => {\n if (!hasFiles(event)) return;\n event.preventDefault();\n setDragging(false);\n const [file] = event.dataTransfer.files;\n if (file) onFile(file);\n };\n\n return (\n // The zone is a pointer shortcut only: the button opens the same picker.\n // biome-ignore lint/a11y/noStaticElementInteractions: drop targets have no keyboard role; the button is the accessible path\n <div\n className={className}\n data-hm-dragging={dragging ? \"\" : undefined}\n onDragEnter={onDragOver}\n onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\n >\n <p id={titleId} className=\"hm-pdf-editor-start-title\">\n {messages.t(error ? \"editor.start.retryTitle\" : \"editor.start.title\")}\n </p>\n {error ? (\n <p role=\"alert\" className={alertClassName}>\n {messages.error(error)}\n </p>\n ) : null}\n <button\n ref={button}\n type=\"button\"\n className=\"hm-pdf-editor-button\"\n aria-describedby={hintId}\n onClick={() => input.current?.click()}\n >\n {messages.t(error ? \"editor.start.retry\" : \"editor.start.choose\")}\n </button>\n <p id={hintId} className=\"hm-pdf-editor-start-hint\">\n {messages.t(\"editor.start.hint\")}\n </p>\n <input\n ref={input}\n type=\"file\"\n accept=\"application/pdf,.pdf\"\n // The button above is the control; this input only opens the picker.\n tabIndex={-1}\n aria-hidden=\"true\"\n hidden\n onChange={choose}\n />\n </div>\n );\n}\n","import { cleanFileName, MAX_FILE_NAME_LENGTH } from \"@hussmartinez/sdk-core\";\n\n/** The download's name when there's no usable one (docs/adr/0009). */\nexport const DEFAULT_DOWNLOAD_NAME = \"document.pdf\";\n\nconst EXTENSION = \".pdf\";\n\n/**\n * A safe name for the saved document, from the source's name or a host's\n * `downloadName`, which are both cleaned as file names (docs/adr/0009). It\n * ends in `.pdf`, in any case, stays within the name limit, and falls back\n * to {@link DEFAULT_DOWNLOAD_NAME}.\n */\nexport function downloadFileName(name: unknown): string {\n const clean = cleanFileName(name);\n if (clean === undefined) return DEFAULT_DOWNLOAD_NAME;\n if (clean.toLowerCase().endsWith(EXTENSION)) return clean;\n const base = Array.from(clean)\n .slice(0, MAX_FILE_NAME_LENGTH - EXTENSION.length)\n .join(\"\")\n .trimEnd();\n return base === \"\" ? DEFAULT_DOWNLOAD_NAME : `${base}${EXTENSION}`;\n}\n\n/**\n * Saves bytes through the browser, as a download named `name`: a `blob:`\n * URL on a detached `<a download>`. It makes no request, and needs no\n * Content Security Policy beyond the README's (docs/adr/0009).\n */\nexport function saveFile(bytes: Uint8Array, name: string): void {\n const url = URL.createObjectURL(\n new Blob([bytes as Uint8Array<ArrayBuffer>], { type: \"application/pdf\" }),\n );\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name;\n link.rel = \"noopener\";\n link.click();\n // Some browsers read the URL after the click returns, so it's revoked\n // later rather than at once.\n setTimeout(() => URL.revokeObjectURL(url), REVOKE_AFTER);\n}\n\n/** How long a download's URL stays valid, in milliseconds. */\nexport const REVOKE_AFTER = 40_000;\n","import type { Announce } from \"@hussmartinez/ui/react\";\nimport { type RefObject, useCallback, useEffect, useRef, useState } from \"react\";\nimport { isPdfError } from \"../../core/errors/pdf-error.js\";\nimport type { PdfSession } from \"../../core/session/session.js\";\nimport { downloadFileName, saveFile } from \"../../features/save/download-name.js\";\nimport type { usePdfMessages } from \"../hooks.js\";\nimport type { PdfDownloadNameInfo, PdfEditorProps } from \"./types.js\";\n\n/** How long a save runs before its Cancel button appears, in milliseconds. */\nexport const CANCEL_AFTER = 1_000;\n\n/** Where a save is, for the editor's header and its tools. */\nexport interface SaveState {\n readonly saving: boolean;\n /** Whether the Cancel button shows: only once a save takes a while. */\n readonly cancellable: boolean;\n /** The text of the last save's failure, for the header's alert. */\n readonly failure: string | undefined;\n}\n\nconst IDLE: SaveState = { saving: false, cancellable: false, failure: undefined };\n\n/**\n * The download tool's work (docs/adr/0009): builds the document in the\n * worker, then saves it through the browser or hands it to `onExport`.\n * One save runs at a time. Cancel, or opening or closing a document,\n * aborts it quietly; a failure is described by its code, or by the\n * catalogue's save failure when the host's own code fails.\n */\nexport function useSave(options: {\n readonly session: PdfSession;\n readonly messages: ReturnType<typeof usePdfMessages>;\n readonly announce: Announce;\n readonly props: RefObject<Pick<PdfEditorProps, \"onExport\" | \"downloadName\">>;\n}): SaveState & { readonly save: () => void; readonly cancel: () => void } {\n const { session, messages, announce, props } = options;\n const [state, setState] = useState<SaveState>(IDLE);\n const running = useRef<AbortController | undefined>(undefined);\n\n const cancel = useCallback(() => running.current?.abort(), []);\n\n const save = useCallback(() => {\n if (running.current) return;\n const controller = new AbortController();\n running.current = controller;\n setState({ saving: true, cancellable: false, failure: undefined });\n const timer = setTimeout(\n () => setState((current) => (current.saving ? { ...current, cancellable: true } : current)),\n CANCEL_AFTER,\n );\n let failure: string | undefined;\n const finish = () => {\n clearTimeout(timer);\n if (running.current === controller) running.current = undefined;\n setState({ saving: false, cancellable: false, failure });\n };\n void (async () => {\n const snapshot = session.getSnapshot();\n const info: PdfDownloadNameInfo = {\n pageCount: snapshot.plan.pages.length,\n ...(snapshot.sources[0]?.name ? { sourceName: snapshot.sources[0].name } : {}),\n };\n let bytes: Uint8Array;\n try {\n bytes = await session.export({ signal: controller.signal });\n } catch (error) {\n if (!controller.signal.aborted && !isPdfError(error, \"ABORTED\")) {\n failure = messages.error(error);\n }\n return;\n }\n if (controller.signal.aborted) return;\n const { onExport, downloadName } = props.current;\n try {\n const name = downloadFileName(downloadName ? downloadName(info) : info.sourceName);\n if (onExport) {\n await onExport(bytes, { fileName: name, pageCount: info.pageCount });\n announce(messages.t(\"editor.ready\"));\n } else {\n saveFile(bytes, name);\n announce(messages.t(\"editor.saved\", { name }));\n }\n } catch {\n // The host's code failed; its error is its own to log (docs/adr/0009).\n failure = messages.t(\"editor.saveFailed\");\n }\n })().finally(finish);\n }, [session, messages, announce, props]);\n\n // Opening or closing a document cancels a save, and the last failure no\n // longer applies; so does leaving the page.\n const opened = session.getSnapshot().sources[0]?.id;\n useEffect(() => {\n void opened;\n running.current?.abort();\n setState((current) => (current.failure ? { ...current, failure: undefined } : current));\n }, [opened]);\n useEffect(() => () => running.current?.abort(), []);\n\n return { ...state, save, cancel };\n}\n","import {\n createMessages,\n createShortcutRegistry,\n createToolRegistry,\n type Messages,\n} from \"@hussmartinez/sdk-core\";\nimport {\n type Announce,\n AnnouncerProvider,\n Button,\n UiMessagesProvider,\n useAnnounce,\n usePlatform,\n} from \"@hussmartinez/ui/react\";\nimport {\n type ForwardedRef,\n forwardRef,\n type KeyboardEvent,\n type ReactNode,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { PdfLimitName } from \"../../core/errors/pdf-limits.js\";\nimport type { PdfSessionSnapshot, PdfWarning } from \"../../core/session/session.js\";\nimport { targetPages } from \"../../features/pages/rotate-tools.js\";\nimport type { PdfTool, PdfToolContext } from \"../../features/tool-types.js\";\nimport { DEFAULT_TOOLBAR, pdfTools } from \"../../features/tools.js\";\nimport { PdfContext } from \"../context.js\";\nimport { type PdfEditorMessageCatalogue, pdfEditorMessages } from \"../editor-messages.js\";\nimport { usePdfDocument, usePdfMessages, usePdfSession } from \"../hooks.js\";\nimport { useProvidedSession } from \"../PdfSessionProvider.js\";\nimport { PdfThumbnails } from \"../thumbnails/PdfThumbnails.js\";\nimport { pdfIcons } from \"../toolbar/icons.js\";\nimport { PdfToolbar } from \"../toolbar/PdfToolbar.js\";\nimport { PdfViewer } from \"../viewer/PdfViewer.js\";\nimport { PdfEditorStart } from \"./PdfEditorStart.js\";\nimport type { PdfEditorChange, PdfEditorHandle, PdfEditorProps } from \"./types.js\";\nimport { useSave } from \"./use-save.js\";\n\n/**\n * A warning's text. Each one is passed `actual`; texts that don't show it\n * ignore it, which the catalogue's per-key types can't express for a union.\n */\nfunction warningText(messages: Messages<PdfEditorMessageCatalogue>, warning: PdfWarning): string {\n const t = messages.t as (key: `warnings.${PdfLimitName}`, params: { actual: number }) => string;\n return t(`warnings.${warning.limit}`, { actual: warning.actual });\n}\n\nconst join = (...names: (string | undefined)[]) => names.filter(Boolean).join(\" \");\n\n/**\n * What to announce after a tool ran from the toolbar or a shortcut, so a\n * change that has no focus of its own still reaches screen readers. Tools\n * whose result is already announced, such as opening, or visible where\n * focus is, have none.\n */\nfunction resultOf(\n tool: PdfTool,\n messages: Messages<PdfEditorMessageCatalogue>,\n before: PdfSessionSnapshot,\n after: PdfSessionSnapshot,\n): string | undefined {\n switch (tool.id) {\n case \"pdf.undo\":\n return messages.t(\"editor.undone\");\n case \"pdf.redo\":\n return messages.t(\"editor.redone\");\n case \"pdf.rotate-left\":\n case \"pdf.rotate-right\":\n return messages.t(\"editor.rotated\", { count: targetPages(before).length });\n case \"pdf.delete-pages\":\n return messages.t(\"editor.deleted\", { count: targetPages(before).length });\n case \"pdf.move-earlier\":\n case \"pdf.move-later\": {\n // The move selects the moved pages; it says where the first one went.\n if (after.plan === before.plan) return undefined;\n const [first] = after.selection;\n const position = after.plan.pages.findIndex((page) => page.key === first) + 1;\n return messages.t(\"editor.moved\", { count: after.selection.length, position });\n }\n default:\n return undefined;\n }\n}\n\n/** What changed between two snapshots, if the host should hear about it. */\nfunction changeBetween(\n before: PdfSessionSnapshot,\n after: PdfSessionSnapshot,\n): PdfEditorChange | undefined {\n const pageCount = after.plan.pages.length;\n const opened = after.sources[0];\n if (after.status === \"ready\" && opened?.id !== before.sources[0]?.id) {\n return { reason: \"open\", pageCount, ...(opened?.name ? { fileName: opened.name } : {}) };\n }\n if (before.sources.length > 0 && after.sources.length === 0) {\n return { reason: \"close\", pageCount: 0 };\n }\n if (after.status === \"ready\" && after.plan !== before.plan) {\n return { reason: \"edit\", pageCount };\n }\n return undefined;\n}\n\n/**\n * Hands ui's `announce` to the editor's body, which renders the provider\n * inside its own root: ui's live regions follow the provider's children,\n * and inside the root they never land in the host's layout.\n */\nfunction AnnounceBridge({ target }: { target: { current: Announce } }): null {\n const announce = useAnnounce();\n useEffect(() => {\n target.current = announce;\n }, [target, announce]);\n return null;\n}\n\ninterface BodyProps\n extends Pick<\n PdfEditorProps,\n | \"file\"\n | \"onChange\"\n | \"onExport\"\n | \"downloadName\"\n | \"className\"\n | \"classNames\"\n | \"unstyled\"\n | \"tools\"\n | \"toolbar\"\n | \"icons\"\n > {\n readonly handle: ForwardedRef<PdfEditorHandle>;\n}\n\nfunction PdfEditorBody(props: BodyProps): ReactNode {\n const { file, onChange, className, classNames = {}, unstyled = false, handle } = props;\n const session = usePdfSession();\n const snapshot = usePdfDocument();\n const messages = usePdfMessages();\n // ui's announcer lives inside the root, below this component.\n const announceTo = useRef<Announce>(() => {});\n const announce = useCallback<Announce>(\n (message, options) => announceTo.current(message, options),\n [],\n );\n const platform = usePlatform();\n const root = useRef<HTMLDivElement>(null);\n const startButton = useRef<HTMLButtonElement>(null);\n const input = useRef<HTMLInputElement>(null);\n const insertInput = useRef<HTMLInputElement>(null);\n const [inserting, setInserting] = useState(false);\n const latestOnChange = useRef(onChange);\n latestOnChange.current = onChange;\n const saveProps = useRef(props);\n saveProps.current = props;\n const saving = useSave({ session, messages, announce, props: saveProps });\n\n // Mistakes in `tools` or `toolbar`, such as an unknown id, throw here, when\n // the editor renders, rather than leaving a tool silently missing.\n const registry = useMemo(\n () =>\n createToolRegistry(pdfTools, {\n ...(props.tools ? { tools: props.tools } : {}),\n toolbar:\n props.toolbar ??\n DEFAULT_TOOLBAR.map((group) =>\n group.filter((id) => !props.tools || props.tools.includes(id)),\n ).filter((group) => group.length > 0),\n }),\n [props.tools, props.toolbar],\n );\n const shortcuts = useMemo(\n () => createShortcutRegistry({ platform, tools: registry.tools }),\n [platform, registry],\n );\n const context: PdfToolContext = useMemo(\n () => ({\n session,\n chooseFile: () => input.current?.click(),\n chooseInsertFile: () => insertInput.current?.click(),\n save: saving.save,\n }),\n [session, saving.save],\n );\n const icons = useMemo(() => ({ ...pdfIcons, ...props.icons }), [props.icons]);\n\n // Keys that only work in the thumbnails, for tools the host kept (docs/adr/0008).\n const deleteTool = registry.get(\"pdf.delete-pages\");\n const moveTools = {\n earlier: registry.get(\"pdf.move-earlier\"),\n later: registry.get(\"pdf.move-later\"),\n };\n\n const runTool = (tool: PdfTool) => {\n const before = session.getSnapshot();\n const state = { snapshot: before, saving: saving.saving, inserting };\n if (!(tool.isEnabled?.(state) ?? true)) return;\n void Promise.resolve(tool.run(context)).then(() => {\n const result = resultOf(tool, messages, before, session.getSnapshot());\n if (result) announce(result);\n });\n };\n\n // Shortcuts work while focus is inside the editor, never on the whole page\n // (WCAG 2.1.4, sdk-core ADR 0030).\n const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {\n const id = shortcuts.match(event.nativeEvent);\n const tool = id ? registry.get(id) : undefined;\n if (!tool) return;\n event.preventDefault();\n runTool(tool);\n };\n\n useImperativeHandle(\n handle,\n () => ({\n session,\n open: (next, options) => session.open(next, options),\n export: (options) => session.export(options),\n undo: () => session.undo(),\n redo: () => session.redo(),\n close: () => session.close(),\n }),\n [session],\n );\n\n // The host's file opens when its identity changes; a newer one cancels it.\n useEffect(() => {\n if (file === undefined) return;\n if (file === null) {\n void session.close();\n return;\n }\n const controller = new AbortController();\n // A failure is in the snapshot, which the editor shows.\n session.open(file, { signal: controller.signal }).catch(() => {});\n return () => controller.abort();\n }, [session, file]);\n\n // Changes reach the host, and opening and closing reach screen readers.\n useEffect(() => {\n let before = session.getSnapshot();\n return session.subscribe(() => {\n const after = session.getSnapshot();\n const change = changeBetween(before, after);\n before = after;\n if (!change) return;\n if (change.reason === \"open\") {\n announce(messages.t(\"editor.opened\", { count: change.pageCount }));\n } else if (change.reason === \"close\") {\n announce(messages.t(\"editor.closed\"));\n }\n latestOnChange.current?.(change);\n });\n }, [session, messages, announce]);\n\n // Focus follows the content that replaced what had it: the document once\n // it opens, or the button to try again after a failure. Focus elsewhere on\n // the host's page is left alone.\n const { status } = snapshot;\n const previous = useRef(status);\n useEffect(() => {\n if (previous.current === status) return;\n previous.current = status;\n const active = document.activeElement;\n const ours = active === null || active === document.body || root.current?.contains(active);\n if (!ours) return;\n if (status === \"ready\") root.current?.querySelector<HTMLElement>(\".hm-pdf-viewer\")?.focus();\n if (status === \"error\") startButton.current?.focus();\n }, [status]);\n\n const open = (chosen: File) => {\n // A failure is in the snapshot, which the editor shows.\n session.open(chosen).catch(() => {});\n };\n\n /**\n * Inserts every page of another file after the current page, then selects\n * the inserted pages and shows the first (docs/adr/0008). A failure is in\n * the snapshot, which the header's alert shows, and changes nothing.\n */\n const insert = async (chosen: File) => {\n const before = session.getSnapshot();\n const current = before.plan.pages.findIndex((page) => page.key === before.currentPage);\n const at = current >= 0 ? current + 1 : before.plan.pages.length;\n setInserting(true);\n try {\n await session.insert(chosen, { at });\n } catch {\n return;\n } finally {\n setInserting(false);\n }\n const had = new Set(before.plan.pages.map((page) => page.key));\n const added = session\n .getSnapshot()\n .plan.pages.filter((page) => !had.has(page.key))\n .map((page) => page.key);\n const [first] = added;\n if (!first) return;\n session.select(added);\n session.goToPage(first);\n announce(messages.t(\"editor.inserted\", { count: added.length, page: at }));\n };\n\n const { error, warnings } = snapshot;\n const showError = error !== undefined && error.code !== \"ABORTED\";\n let content: ReactNode;\n if (status === \"ready\") {\n content = (\n <>\n <PdfThumbnails\n className={join(\"hm-pdf-editor-sidebar\", classNames.sidebar)}\n unstyled={unstyled}\n {...(deleteTool ? { onDelete: () => runTool(deleteTool) } : {})}\n {...(moveTools.earlier || moveTools.later\n ? {\n onMove: (direction: \"earlier\" | \"later\") => {\n const tool = moveTools[direction];\n if (tool) runTool(tool);\n },\n }\n : {})}\n />\n <PdfViewer unstyled={unstyled} />\n </>\n );\n } else if (status === \"opening\") {\n content = (\n <div role=\"status\" className={join(\"hm-pdf-editor-loading\", classNames.status)}>\n {/* Indeterminate: the engine reports no progress while it opens. */}\n <progress className=\"hm-pdf-editor-progress\" aria-hidden=\"true\" />\n <p>{messages.t(\"editor.opening\")}</p>\n </div>\n );\n } else {\n content = (\n <PdfEditorStart\n error={showError ? error : undefined}\n onFile={open}\n button={startButton}\n className={join(\"hm-pdf-editor-start\", classNames.start)}\n alertClassName={join(\"hm-pdf-editor-alert\", classNames.alert)}\n />\n );\n }\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a labelled group of the editor's regions, not a fieldset\n <div\n ref={root}\n role=\"group\"\n aria-label={messages.t(\"editor.label\")}\n aria-busy={status === \"opening\" || snapshot.busy || saving.saving}\n // ui's text root (ui ADR 0010), unless the host styles the editor itself.\n className={join(\n unstyled ? undefined : \"hm-text\",\n \"hm-pdf-editor\",\n className,\n classNames.root,\n )}\n data-hm-status={status}\n onKeyDown={onKeyDown}\n {...(unstyled ? { \"data-hm-unstyled\": \"\" } : {})}\n >\n <input\n ref={input}\n type=\"file\"\n accept=\"application/pdf,.pdf\"\n // The open tool is the control; this input only opens the picker.\n tabIndex={-1}\n aria-hidden=\"true\"\n hidden\n onChange={(event) => {\n const [chosen] = event.target.files ?? [];\n event.target.value = \"\";\n if (chosen) open(chosen);\n }}\n />\n <input\n ref={insertInput}\n type=\"file\"\n accept=\"application/pdf,.pdf\"\n // The insert tool is the control; this input only opens the picker.\n tabIndex={-1}\n aria-hidden=\"true\"\n hidden\n data-hm-insert=\"\"\n onChange={(event) => {\n const [chosen] = event.target.files ?? [];\n event.target.value = \"\";\n if (chosen) void insert(chosen);\n }}\n />\n <div className={join(\"hm-pdf-editor-header\", classNames.header)}>\n <PdfToolbar\n registry={registry}\n shortcuts={shortcuts}\n context={context}\n icons={icons}\n onRun={runTool}\n saving={saving.saving}\n inserting={inserting}\n className={join(\"hm-pdf-editor-toolbar\", classNames.toolbar)}\n />\n {saving.saving ? (\n <div className={join(\"hm-pdf-editor-saving\", classNames.status)}>\n <p role=\"status\">{messages.t(\"editor.saving\")}</p>\n {saving.cancellable ? (\n <Button size=\"small\" onClick={saving.cancel}>\n {messages.t(\"editor.cancelSave\")}\n </Button>\n ) : null}\n </div>\n ) : null}\n {saving.failure ? (\n <p role=\"alert\" className={join(\"hm-pdf-editor-alert\", classNames.alert)}>\n {saving.failure}\n </p>\n ) : null}\n {status === \"ready\" && showError ? (\n <p role=\"alert\" className={join(\"hm-pdf-editor-alert\", classNames.alert)}>\n {messages.error(error)}\n </p>\n ) : null}\n {status === \"ready\" && (warnings.length > 0 || snapshot.historyTrimmed) ? (\n <div role=\"status\" className={join(\"hm-pdf-editor-warnings\", classNames.status)}>\n <ul>\n {warnings.map((warning) => (\n <li key={warning.limit}>{warningText(messages, warning)}</li>\n ))}\n {snapshot.historyTrimmed ? <li>{messages.t(\"editor.historyTrimmed\")}</li> : null}\n </ul>\n </div>\n ) : null}\n </div>\n <div className={join(\"hm-pdf-editor-body\", classNames.body)}>{content}</div>\n <AnnouncerProvider>\n <AnnounceBridge target={announceTo} />\n </AnnouncerProvider>\n </div>\n );\n}\n\n/**\n * The complete editor: a document's pages beside it as thumbnails, with\n * designed states for no document, opening and a failed open (ADR 0014).\n * It creates its own session, through `PdfSessionProvider`, unless one is\n * passed, and releases what it created when it unmounts.\n *\n * Users open a PDF with the button, which keyboard and screen reader users\n * reach like any other, or by dropping it on the editor. Opening and\n * closing are announced, and focus moves to the document once it opens, or\n * to the button to try again if it couldn't.\n *\n * Its toolbar is built from {@link pdfTools}: choose them with `tools` and\n * arrange them with `toolbar`. Each tool's shortcut works while focus is in\n * the editor, and undoing, redoing and rotating are announced.\n *\n * Load `@hussmartinez/ui/styles.css` once, before the SDK's stylesheet: the\n * toolbar's focus rings and target sizes are in it (sdk-core ADR 0036).\n *\n * Give the editor a bounded height, such as a grid row or a fixed height:\n * its viewer and thumbnails scroll within it.\n *\n * @example\n * ```tsx\n * const editor = useRef<PdfEditorHandle>(null);\n * <PdfEditor ref={editor} file={file} onChange={({ reason }) => setDirty(reason === \"edit\")} />;\n * const bytes = await editor.current?.export();\n * ```\n *\n * @public\n */\nexport const PdfEditor = /* @__PURE__ */ forwardRef(function PdfEditor(\n props: PdfEditorProps,\n handle: ForwardedRef<PdfEditorHandle>,\n): ReactNode {\n const {\n file,\n onChange,\n onExport,\n downloadName,\n className,\n classNames,\n unstyled,\n tools,\n toolbar,\n icons,\n messages: overrides,\n locale = \"en\",\n ...source\n } = props;\n const session = useProvidedSession(source);\n // One Messages object, with the host's locale and overrides, for the\n // editor's components and for ui's (sdk-core ADR 0046).\n const messages = useMemo(\n () =>\n createMessages(pdfEditorMessages, {\n locale,\n ...(overrides ? { overrides } : {}),\n }),\n [locale, overrides],\n );\n const value = useMemo(() => ({ session, messages }), [session, messages]);\n return (\n <PdfContext.Provider value={value}>\n <UiMessagesProvider messages={messages}>\n <PdfEditorBody\n handle={handle}\n {...(file !== undefined ? { file } : {})}\n {...(onChange ? { onChange } : {})}\n {...(onExport ? { onExport } : {})}\n {...(downloadName ? { downloadName } : {})}\n {...(className !== undefined ? { className } : {})}\n {...(classNames ? { classNames } : {})}\n {...(unstyled !== undefined ? { unstyled } : {})}\n {...(tools ? { tools } : {})}\n {...(toolbar ? { toolbar } : {})}\n {...(icons ? { icons } : {})}\n />\n </UiMessagesProvider>\n </PdfContext.Provider>\n );\n});\n"],"mappings":";;;;;;;;;AAIA,IAAa,WAAoC,2BAAW;CAC1D,IAAI;CACJ,OAAO;CACP,MAAM;CACN,OAAO;CACP,YAAY,EAAE,eAAe,SAAS;CACtC,MAAM,EAAE,cAAc;EACpB,QAAQ,KAAK;CACf;CACA,WAAW;AACb,CAAC;AAGD,IAAa,WAAoC,2BAAW;CAC1D,IAAI;CACJ,OAAO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