@embedpdf/plugin-commands 3.0.0-next.22 → 3.0.0-next.23
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/contract/host.cjs +1 -1
- package/dist/contract/host.d.cts +3 -3
- package/dist/contract/host.d.ts +3 -3
- package/dist/contract/host.js +1 -1
- package/dist/{contract-lGfvyWMG.d.ts → contract-Bt0jzEeF.d.cts} +26 -16
- package/dist/{contract-lGfvyWMG.d.cts → contract-Bt0jzEeF.d.ts} +26 -16
- package/dist/{contract-sqmSSPlP.cjs → contract-CgR0waU2.cjs} +5 -5
- package/dist/contract-CgR0waU2.cjs.map +1 -0
- package/dist/{contract-FbiUhTWC.js → contract-DzkHZxi7.js} +5 -5
- package/dist/contract-DzkHZxi7.js.map +1 -0
- package/dist/contract.cjs +1 -1
- package/dist/contract.d.cts +2 -2
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +1 -1
- package/dist/{host-contract-Db4TZ_JI.d.cts → host-contract-BvjavDn3.d.cts} +2 -2
- package/dist/{host-contract-B58WiZ-H.d.ts → host-contract-WcBrcWQN.d.ts} +2 -2
- package/dist/index.cjs +21 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +22 -8
- package/dist/index.js.map +1 -1
- package/dist/standard.cjs +1 -1
- package/dist/standard.cjs.map +1 -1
- package/dist/standard.d.cts +2 -2
- package/dist/standard.d.ts +2 -2
- package/dist/standard.js +1 -1
- package/dist/standard.js.map +1 -1
- package/package.json +10 -10
- package/dist/contract-FbiUhTWC.js.map +0 -1
- package/dist/contract-sqmSSPlP.cjs.map +0 -1
package/dist/standard.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standard.cjs","names":["StageToken","RenderToken","InteractionToken","AnnotationToken","SNAPSHOT_TOOL","SelectionToken","DocumentsToken"],"sources":["../src/standard.ts"],"sourcesContent":["/**\n * @embedpdf/plugin-commands/standard — the commands every viewer has: zoom,\n * pages, view rotation, a command for every tool, copy, the snapshot, delete,\n * download and print, with shortcuts, and labels in EmbedPDF's eight\n * languages (the i18n plugin has the strings). Some of them reach the browser\n * (the clipboard, a file download), which plugins never touch, so each\n * framework's `/commands` builds them with its platform: that is the\n * `standardCommands` an app imports. Print goes through the kernel, which has\n * the host's printer.\n */\nimport { DocumentsToken } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { InteractionToken, type Tool } from '@embedpdf/plugin-interaction/contract';\nimport { RenderToken, SNAPSHOT_TOOL, type PageImage } from '@embedpdf/plugin-render/contract';\nimport { SelectionToken, type SelectionCapability } from '@embedpdf/plugin-selection/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport type { CommandContext, CommandDef, CommandFamily } from './contract';\n\n/** What the standard commands need from the browser. */\nexport interface StandardCommandsPlatform {\n /** Copy the selected text to the clipboard. */\n copySelection(selection: SelectionCapability): Promise<unknown>;\n /**\n * Copy an image to the clipboard. Called in the press or key itself, before\n * the image is there: a browser may take the clipboard only then.\n */\n copyImage(image: Promise<PageImage>): Promise<unknown>;\n /** Give the user the bytes as a file download, of the given content type. */\n saveFile(bytes: Uint8Array | Blob, fileName: string, contentType: string): void;\n}\n\nconst stageOf = (context: CommandContext) => context.tryGet(StageToken);\nconst snapshotOf = (context: CommandContext) => context.tryGet(RenderToken)?.getSnapshot() ?? null;\nconst interactionOf = (context: CommandContext) => context.tryGet(InteractionToken);\n\n/** Enabled while the document has a Stage. */\nconst hasStage = (context: CommandContext): boolean => stageOf(context) !== null;\n\n/** The ids of a tool list, made once per list, which keeps its identity while the tools don't change. */\nconst toolIds = new WeakMap<readonly Tool[], readonly string[]>();\nconst idsOf = (tools: readonly Tool[]): readonly string[] => {\n let ids = toolIds.get(tools);\n if (!ids) {\n ids = tools.map((tool) => tool.id);\n toolIds.set(tools, ids);\n }\n return ids;\n};\n\n/**\n * Whether the user may use a tool: one that draws annotations needs permission to create them.\n * A tool another plugin owns asks nothing here; that plugin refuses its own gesture.\n */\nconst mayUseTool = (context: CommandContext, toolId: string): boolean => {\n const annotation = context.tryGet(AnnotationToken);\n return !annotation?.tools.get(toolId) || annotation.canCreate();\n};\n\n/** Switching to a tool: active while it's the tool, there only when the document has it. */\nconst toolCommand = (toolId: string): Omit<CommandDef, 'id' | 'shortcut'> => ({\n labelKey: `commands.tool.${toolId}`,\n label: toolId,\n icon: toolId,\n categories: ['tool'],\n run: (context) => interactionOf(context)?.activateTool(toolId),\n active: (context) => interactionOf(context)?.getActiveToolId() === toolId,\n visible: (context) => interactionOf(context)?.hasTool(toolId) ?? false,\n enabled: (context) => mayUseTool(context, toolId),\n});\n\n/** `tool:<id>` for every tool the document has. */\nconst toolCommands: CommandFamily = {\n prefix: 'tool:',\n names: (context) => {\n const interaction = interactionOf(context);\n return interaction ? idsOf(interaction.listTools()) : [];\n },\n command: toolCommand,\n};\n\n/** The standard commands, with the browser's part from `platform`. */\nexport function createStandardCommands(\n platform: StandardCommandsPlatform,\n): readonly (CommandDef | CommandFamily)[] {\n return [\n // ── zoom ──\n {\n id: 'zoom:in',\n labelKey: 'commands.zoom.in',\n label: 'Zoom in',\n icon: 'zoom-in',\n shortcut: ['Mod+=', 'Mod+NumpadAdd'],\n categories: ['zoom'],\n run: (context) => stageOf(context)?.zoomIn(),\n enabled: (context) => stageOf(context)?.canZoomIn() ?? false,\n },\n {\n id: 'zoom:out',\n labelKey: 'commands.zoom.out',\n label: 'Zoom out',\n icon: 'zoom-out',\n shortcut: ['Mod+-', 'Mod+NumpadSubtract'],\n categories: ['zoom'],\n run: (context) => stageOf(context)?.zoomOut(),\n enabled: (context) => stageOf(context)?.canZoomOut() ?? false,\n },\n {\n id: 'zoom:fit-width',\n labelKey: 'commands.zoom.fitWidth',\n label: 'Fit width',\n icon: 'fit-width',\n categories: ['zoom'],\n run: (context) => stageOf(context)?.fitWidth(),\n active: (context) => stageOf(context)?.getZoomMode() === 'fit-width',\n enabled: hasStage,\n },\n {\n id: 'zoom:fit-page',\n labelKey: 'commands.zoom.fitPage',\n label: 'Fit page',\n icon: 'fit-page',\n categories: ['zoom'],\n run: (context) => stageOf(context)?.fitPage(),\n active: (context) => stageOf(context)?.getZoomMode() === 'fit-page',\n enabled: hasStage,\n },\n\n // ── pages ──\n {\n id: 'page:next',\n labelKey: 'commands.page.next',\n label: 'Next page',\n icon: 'next-page',\n shortcut: 'ArrowRight',\n categories: ['page'],\n run: (context) => stageOf(context)?.nextPage(),\n enabled: (context) => stageOf(context)?.canGoNext() ?? false,\n },\n {\n id: 'page:previous',\n labelKey: 'commands.page.previous',\n label: 'Previous page',\n icon: 'previous-page',\n shortcut: 'ArrowLeft',\n categories: ['page'],\n run: (context) => stageOf(context)?.previousPage(),\n enabled: (context) => stageOf(context)?.canGoPrevious() ?? false,\n },\n {\n id: 'page:first',\n labelKey: 'commands.page.first',\n label: 'First page',\n icon: 'first-page',\n shortcut: 'Home',\n categories: ['page'],\n run: (context) => stageOf(context)?.goToFirstPage(),\n enabled: (context) => stageOf(context)?.canGoPrevious() ?? false,\n },\n {\n id: 'page:last',\n labelKey: 'commands.page.last',\n label: 'Last page',\n icon: 'last-page',\n shortcut: 'End',\n categories: ['page'],\n run: (context) => stageOf(context)?.goToLastPage(),\n enabled: (context) => stageOf(context)?.canGoNext() ?? false,\n },\n\n // ── view rotation: how the pages show, nothing written to the PDF ──\n {\n id: 'view:rotate-clockwise',\n labelKey: 'commands.view.rotateClockwise',\n label: 'Rotate clockwise',\n icon: 'rotate-clockwise',\n categories: ['view'],\n run: (context) => stageOf(context)?.rotateViewBy(90),\n enabled: hasStage,\n },\n {\n id: 'view:rotate-counterclockwise',\n labelKey: 'commands.view.rotateCounterclockwise',\n label: 'Rotate counterclockwise',\n icon: 'rotate-counterclockwise',\n categories: ['view'],\n run: (context) => stageOf(context)?.rotateViewBy(-90),\n enabled: hasStage,\n },\n\n // ── tools: the built-in ones have Acrobat's single keys; the family covers every other ──\n { ...toolCommand('pointer'), id: 'tool:pointer', shortcut: 'V' },\n { ...toolCommand('pan'), id: 'tool:pan', shortcut: 'H' },\n { ...toolCommand('zoom'), id: 'tool:zoom', shortcut: 'Z' },\n {\n ...toolCommand(SNAPSHOT_TOOL),\n id: 'tool:snapshot',\n allowed: (context) => context.tryGet(RenderToken)?.canSnapshot() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-content-copy',\n },\n toolCommands,\n\n // ── selections ──\n {\n id: 'selection:copy',\n labelKey: 'commands.selection.copy',\n label: 'Copy',\n icon: 'copy',\n shortcut: 'Mod+C',\n categories: ['selection'],\n run: (context) => platform.copySelection(context.get(SelectionToken)),\n // `canCopy()` in `enabled`, not `allowed`: a refused command keeps its keys, and Mod+C\n // with nothing selected in the viewer belongs to the page. The clipboard wiring says\n // when a selection may not be copied.\n enabled: (context) => {\n const selection = context.tryGet(SelectionToken);\n return !!selection && selection.hasSelection() && selection.canCopy();\n },\n },\n {\n id: 'annotation:delete',\n labelKey: 'commands.annotation.delete',\n label: 'Delete',\n icon: 'delete',\n shortcut: ['Delete', 'Backspace'],\n categories: ['annotation'],\n run: (context) => context.get(AnnotationToken).selection.delete({ signal: context.signal }),\n enabled: (context) => {\n const annotation = context.tryGet(AnnotationToken);\n if (!annotation) return false;\n const selected = annotation.selection.list();\n // `isEditable`: the annotation plugin's `editable` setting lets people change it by hand.\n return (\n selected.length > 0 &&\n selected.every(({ ref }) => annotation.canDelete(ref) && annotation.isEditable(ref))\n );\n },\n },\n\n // ── the snapshot the snapshot tool holds ──\n {\n id: 'snapshot:copy',\n labelKey: 'commands.snapshot.copy',\n label: 'Copy',\n icon: 'copy',\n shortcut: 'Mod+C',\n categories: ['snapshot'],\n // Straight to the clipboard, in the press itself: the picture follows when it's there.\n run: (context) => {\n const snapshot = snapshotOf(context);\n return snapshot ? platform.copyImage(snapshot.image) : undefined;\n },\n enabled: (context) => snapshotOf(context) !== null,\n },\n {\n id: 'snapshot:save',\n labelKey: 'commands.snapshot.save',\n label: 'Save image',\n icon: 'download',\n categories: ['snapshot'],\n run: async (context) => {\n const snapshot = snapshotOf(context);\n if (!snapshot) return;\n const documents = context.get(DocumentsToken);\n const id = context.documentId ?? undefined;\n const blob = await (await snapshot.image).blob();\n const number =\n documents\n .listPages(id)\n .findIndex((page) => page.ref.objectNumber === snapshot.page.objectNumber) + 1;\n platform.saveFile(blob, snapshotFileNameOf(documents.get(id)?.name, number), 'image/png');\n },\n enabled: (context) => snapshotOf(context) !== null,\n },\n {\n id: 'snapshot:clear',\n labelKey: 'commands.snapshot.clear',\n label: 'Clear snapshot',\n shortcut: 'Escape',\n categories: ['snapshot'],\n run: (context) => context.get(RenderToken).clearSnapshot(),\n enabled: (context) => snapshotOf(context) !== null,\n },\n\n // ── the document ──\n {\n id: 'document:download',\n labelKey: 'commands.document.download',\n label: 'Download',\n icon: 'download',\n shortcut: 'Mod+S',\n categories: ['document'],\n allowed: (context) => context.tryGet(DocumentsToken)?.canDownload() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-download',\n run: async (context) => {\n const documents = context.get(DocumentsToken);\n const id = context.documentId ?? undefined;\n const bytes = await documents.download(id, { signal: context.signal });\n platform.saveFile(bytes, fileNameOf(documents.get(id)?.name), 'application/pdf');\n },\n enabled: (context) => context.documentId !== null,\n },\n {\n id: 'document:print',\n labelKey: 'commands.document.print',\n label: 'Print',\n icon: 'print',\n shortcut: 'Mod+P',\n categories: ['document'],\n allowed: (context) => context.tryGet(DocumentsToken)?.canPrint() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-print',\n // The kernel prints the document's pages, and runs the document's own\n // print actions around the dialog when the actions plugin is there.\n run: async (context) => {\n const documents = context.get(DocumentsToken);\n await documents.print(context.documentId ?? undefined, { signal: context.signal });\n },\n enabled: (context) => context.documentId !== null,\n },\n ];\n}\n\n/** The download's file name: the document's name, ending in `.pdf`. */\nfunction fileNameOf(name: string | undefined): string {\n if (!name) return 'document.pdf';\n return /\\.pdf$/i.test(name) ? name : `${name}.pdf`;\n}\n\n/** A snapshot's file name: the document's name and the page's number, as a PNG (`Report p3.png`). */\nfunction snapshotFileNameOf(name: string | undefined, pageNumber: number): string {\n const base = (name ?? 'document').replace(/\\.pdf$/i, '');\n return `${base} p${pageNumber}.png`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,MAAM,WAAW,YAA4B,QAAQ,OAAOA,gCAAAA,UAAU;AACtE,MAAM,cAAc,YAA4B,QAAQ,OAAOC,iCAAAA,WAAW,CAAC,EAAE,YAAY,KAAK;AAC9F,MAAM,iBAAiB,YAA4B,QAAQ,OAAOC,sCAAAA,gBAAgB;;AAGlF,MAAM,YAAY,YAAqC,QAAQ,OAAO,MAAM;;AAG5E,MAAM,0BAAU,IAAI,QAA4C;AAChE,MAAM,SAAS,UAA8C;CAC3D,IAAI,MAAM,QAAQ,IAAI,KAAK;CAC3B,IAAI,CAAC,KAAK;EACR,MAAM,MAAM,KAAK,SAAS,KAAK,EAAE;EACjC,QAAQ,IAAI,OAAO,GAAG;CACxB;CACA,OAAO;AACT;;;;;AAMA,MAAM,cAAc,SAAyB,WAA4B;CACvE,MAAM,aAAa,QAAQ,OAAOC,qCAAAA,eAAe;CACjD,OAAO,CAAC,YAAY,MAAM,IAAI,MAAM,KAAK,WAAW,UAAU;AAChE;;AAGA,MAAM,eAAe,YAAyD;CAC5E,UAAU,iBAAiB;CAC3B,OAAO;CACP,MAAM;CACN,YAAY,CAAC,MAAM;CACnB,MAAM,YAAY,cAAc,OAAO,CAAC,EAAE,aAAa,MAAM;CAC7D,SAAS,YAAY,cAAc,OAAO,CAAC,EAAE,gBAAgB,MAAM;CACnE,UAAU,YAAY,cAAc,OAAO,CAAC,EAAE,QAAQ,MAAM,KAAK;CACjE,UAAU,YAAY,WAAW,SAAS,MAAM;AAClD;;AAGA,MAAM,eAA8B;CAClC,QAAQ;CACR,QAAQ,YAAY;EAClB,MAAM,cAAc,cAAc,OAAO;EACzC,OAAO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I,OAAO,GAAG,KAAK;AAC/C;;AAGA,SAAS,mBAAmB,MAA0B,YAA4B;CAEhF,OAAO,IADO,QAAQ,WAAA,CAAY,QAAQ,WAAW,EACxC,EAAE,IAAI,WAAW;AAChC"}
|
|
1
|
+
{"version":3,"file":"standard.cjs","names":["StageToken","RenderToken","InteractionToken","AnnotationToken","SNAPSHOT_TOOL","SelectionToken","DocumentsToken"],"sources":["../src/standard.ts"],"sourcesContent":["/**\n * @embedpdf/plugin-commands/standard — the commands every viewer has: zoom,\n * pages, view rotation, a command for every tool, copy, the snapshot, delete,\n * download and print, with shortcuts, and labels in EmbedPDF's eight\n * languages (the i18n plugin has the strings). Some of them reach the browser\n * (the clipboard, a file download), which plugins never touch, so each\n * framework's `/commands` builds them with its platform: that is the\n * `standardCommands` an app imports. Print goes through the kernel, which has\n * the host's printer.\n */\nimport { DocumentsToken } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { InteractionToken, type Tool } from '@embedpdf/plugin-interaction/contract';\nimport { RenderToken, SNAPSHOT_TOOL, type PageImage } from '@embedpdf/plugin-render/contract';\nimport { SelectionToken, type SelectionCapability } from '@embedpdf/plugin-selection/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport type { CommandContext, CommandDefinition, CommandFamily } from './contract';\n\n/** What the standard commands need from the browser. */\nexport interface StandardCommandsPlatform {\n /** Copy the selected text to the clipboard. */\n copySelection(selection: SelectionCapability): Promise<unknown>;\n /**\n * Copy an image to the clipboard. Called in the press or key itself, before\n * the image is there: a browser may take the clipboard only then.\n */\n copyImage(image: Promise<PageImage>): Promise<unknown>;\n /** Give the user the bytes as a file download, of the given content type. */\n saveFile(bytes: Uint8Array | Blob, fileName: string, contentType: string): void;\n}\n\nconst stageOf = (context: CommandContext) => context.tryGet(StageToken);\nconst snapshotOf = (context: CommandContext) => context.tryGet(RenderToken)?.getSnapshot() ?? null;\nconst interactionOf = (context: CommandContext) => context.tryGet(InteractionToken);\n\n/** Enabled while the document has a Stage. */\nconst hasStage = (context: CommandContext): boolean => stageOf(context) !== null;\n\n/** The ids of a tool list, made once per list, which keeps its identity while the tools don't change. */\nconst toolIds = new WeakMap<readonly Tool[], readonly string[]>();\nconst idsOf = (tools: readonly Tool[]): readonly string[] => {\n let ids = toolIds.get(tools);\n if (!ids) {\n ids = tools.map((tool) => tool.id);\n toolIds.set(tools, ids);\n }\n return ids;\n};\n\n/**\n * Whether the user may use a tool: one that draws annotations needs permission to create them.\n * A tool another plugin owns asks nothing here; that plugin refuses its own gesture.\n */\nconst mayUseTool = (context: CommandContext, toolId: string): boolean => {\n const annotation = context.tryGet(AnnotationToken);\n return !annotation?.tools.get(toolId) || annotation.canCreate();\n};\n\n/** Switching to a tool: active while it's the tool, there only when the document has it. */\nconst toolCommand = (toolId: string): Omit<CommandDefinition, 'id' | 'shortcut'> => ({\n labelKey: `commands.tool.${toolId}`,\n label: toolId,\n icon: toolId,\n categories: ['tool'],\n run: (context) => interactionOf(context)?.activateTool(toolId),\n active: (context) => interactionOf(context)?.getActiveToolId() === toolId,\n visible: (context) => interactionOf(context)?.hasTool(toolId) ?? false,\n enabled: (context) => mayUseTool(context, toolId),\n});\n\n/** `tool:<id>` for every tool the document has. */\nconst toolCommands: CommandFamily = {\n prefix: 'tool:',\n names: (context) => {\n const interaction = interactionOf(context);\n return interaction ? idsOf(interaction.listTools()) : [];\n },\n command: toolCommand,\n};\n\n/** The standard commands, with the browser's part from `platform`. */\nexport function createStandardCommands(\n platform: StandardCommandsPlatform,\n): readonly (CommandDefinition | CommandFamily)[] {\n return [\n // ── zoom ──\n {\n id: 'zoom:in',\n labelKey: 'commands.zoom.in',\n label: 'Zoom in',\n icon: 'zoom-in',\n shortcut: ['Mod+=', 'Mod+NumpadAdd'],\n categories: ['zoom'],\n run: (context) => stageOf(context)?.zoomIn(),\n enabled: (context) => stageOf(context)?.canZoomIn() ?? false,\n },\n {\n id: 'zoom:out',\n labelKey: 'commands.zoom.out',\n label: 'Zoom out',\n icon: 'zoom-out',\n shortcut: ['Mod+-', 'Mod+NumpadSubtract'],\n categories: ['zoom'],\n run: (context) => stageOf(context)?.zoomOut(),\n enabled: (context) => stageOf(context)?.canZoomOut() ?? false,\n },\n {\n id: 'zoom:fit-width',\n labelKey: 'commands.zoom.fitWidth',\n label: 'Fit width',\n icon: 'fit-width',\n categories: ['zoom'],\n run: (context) => stageOf(context)?.fitWidth(),\n active: (context) => stageOf(context)?.getZoomMode() === 'fit-width',\n enabled: hasStage,\n },\n {\n id: 'zoom:fit-page',\n labelKey: 'commands.zoom.fitPage',\n label: 'Fit page',\n icon: 'fit-page',\n categories: ['zoom'],\n run: (context) => stageOf(context)?.fitPage(),\n active: (context) => stageOf(context)?.getZoomMode() === 'fit-page',\n enabled: hasStage,\n },\n\n // ── pages ──\n {\n id: 'page:next',\n labelKey: 'commands.page.next',\n label: 'Next page',\n icon: 'next-page',\n shortcut: 'ArrowRight',\n categories: ['page'],\n run: (context) => stageOf(context)?.nextPage(),\n enabled: (context) => stageOf(context)?.canGoNext() ?? false,\n },\n {\n id: 'page:previous',\n labelKey: 'commands.page.previous',\n label: 'Previous page',\n icon: 'previous-page',\n shortcut: 'ArrowLeft',\n categories: ['page'],\n run: (context) => stageOf(context)?.previousPage(),\n enabled: (context) => stageOf(context)?.canGoPrevious() ?? false,\n },\n {\n id: 'page:first',\n labelKey: 'commands.page.first',\n label: 'First page',\n icon: 'first-page',\n shortcut: 'Home',\n categories: ['page'],\n run: (context) => stageOf(context)?.goToFirstPage(),\n enabled: (context) => stageOf(context)?.canGoPrevious() ?? false,\n },\n {\n id: 'page:last',\n labelKey: 'commands.page.last',\n label: 'Last page',\n icon: 'last-page',\n shortcut: 'End',\n categories: ['page'],\n run: (context) => stageOf(context)?.goToLastPage(),\n enabled: (context) => stageOf(context)?.canGoNext() ?? false,\n },\n\n // ── view rotation: how the pages show, nothing written to the PDF ──\n {\n id: 'view:rotate-clockwise',\n labelKey: 'commands.view.rotateClockwise',\n label: 'Rotate clockwise',\n icon: 'rotate-clockwise',\n categories: ['view'],\n run: (context) => stageOf(context)?.rotateViewBy(90),\n enabled: hasStage,\n },\n {\n id: 'view:rotate-counterclockwise',\n labelKey: 'commands.view.rotateCounterclockwise',\n label: 'Rotate counterclockwise',\n icon: 'rotate-counterclockwise',\n categories: ['view'],\n run: (context) => stageOf(context)?.rotateViewBy(-90),\n enabled: hasStage,\n },\n\n // ── tools: the built-in ones have Acrobat's single keys; the family covers every other ──\n { ...toolCommand('pointer'), id: 'tool:pointer', shortcut: 'V' },\n { ...toolCommand('pan'), id: 'tool:pan', shortcut: 'H' },\n { ...toolCommand('zoom'), id: 'tool:zoom', shortcut: 'Z' },\n {\n ...toolCommand(SNAPSHOT_TOOL),\n id: 'tool:snapshot',\n allowed: (context) => context.tryGet(RenderToken)?.canSnapshot() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-content-copy',\n },\n toolCommands,\n\n // ── selections ──\n {\n id: 'selection:copy',\n labelKey: 'commands.selection.copy',\n label: 'Copy',\n icon: 'copy',\n shortcut: 'Mod+C',\n categories: ['selection'],\n run: (context) => platform.copySelection(context.get(SelectionToken)),\n // `canCopy()` in `enabled`, not `allowed`: a refused command keeps its keys, and Mod+C\n // with nothing selected in the viewer belongs to the page. The clipboard wiring says\n // when a selection may not be copied.\n enabled: (context) => {\n const selection = context.tryGet(SelectionToken);\n return !!selection && selection.hasSelection() && selection.canCopy();\n },\n },\n {\n id: 'annotation:delete',\n labelKey: 'commands.annotation.delete',\n label: 'Delete',\n icon: 'delete',\n shortcut: ['Delete', 'Backspace'],\n categories: ['annotation'],\n run: (context) => context.get(AnnotationToken).selection.delete({ signal: context.signal }),\n enabled: (context) => {\n const annotation = context.tryGet(AnnotationToken);\n if (!annotation) return false;\n const selected = annotation.selection.getSelected();\n // `isEditable`: the annotation plugin's `editable` setting lets people change it by hand.\n return (\n selected.length > 0 &&\n selected.every(({ ref }) => annotation.canDelete(ref) && annotation.isEditable(ref))\n );\n },\n },\n\n // ── the snapshot the snapshot tool holds ──\n {\n id: 'snapshot:copy',\n labelKey: 'commands.snapshot.copy',\n label: 'Copy',\n icon: 'copy',\n shortcut: 'Mod+C',\n categories: ['snapshot'],\n // Straight to the clipboard, in the press itself: the picture follows when it's there.\n run: (context) => {\n const snapshot = snapshotOf(context);\n return snapshot ? platform.copyImage(snapshot.image) : undefined;\n },\n enabled: (context) => snapshotOf(context) !== null,\n },\n {\n id: 'snapshot:save',\n labelKey: 'commands.snapshot.save',\n label: 'Save image',\n icon: 'download',\n categories: ['snapshot'],\n run: async (context) => {\n const snapshot = snapshotOf(context);\n if (!snapshot) return;\n const documents = context.get(DocumentsToken);\n const id = context.documentId ?? undefined;\n const blob = await (await snapshot.image).blob();\n const number =\n documents\n .listPages(id)\n .findIndex((page) => page.ref.objectNumber === snapshot.page.objectNumber) + 1;\n platform.saveFile(blob, snapshotFileNameOf(documents.get(id)?.name, number), 'image/png');\n },\n enabled: (context) => snapshotOf(context) !== null,\n },\n {\n id: 'snapshot:clear',\n labelKey: 'commands.snapshot.clear',\n label: 'Clear snapshot',\n shortcut: 'Escape',\n categories: ['snapshot'],\n run: (context) => context.get(RenderToken).clearSnapshot(),\n enabled: (context) => snapshotOf(context) !== null,\n },\n\n // ── the document ──\n {\n id: 'document:download',\n labelKey: 'commands.document.download',\n label: 'Download',\n icon: 'download',\n shortcut: 'Mod+S',\n categories: ['document'],\n allowed: (context) => context.tryGet(DocumentsToken)?.canDownload() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-download',\n run: async (context) => {\n const documents = context.get(DocumentsToken);\n const id = context.documentId ?? undefined;\n const bytes = await documents.download(id, { signal: context.signal });\n platform.saveFile(bytes, fileNameOf(documents.get(id)?.name), 'application/pdf');\n },\n enabled: (context) => context.documentId !== null,\n },\n {\n id: 'document:print',\n labelKey: 'commands.document.print',\n label: 'Print',\n icon: 'print',\n shortcut: 'Mod+P',\n categories: ['document'],\n allowed: (context) => context.tryGet(DocumentsToken)?.canPrint() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-print',\n // The kernel prints the document's pages, and runs the document's own\n // print actions around the dialog when the actions plugin is there.\n run: async (context) => {\n const documents = context.get(DocumentsToken);\n await documents.print(context.documentId ?? undefined, { signal: context.signal });\n },\n enabled: (context) => context.documentId !== null,\n },\n ];\n}\n\n/** The download's file name: the document's name, ending in `.pdf`. */\nfunction fileNameOf(name: string | undefined): string {\n if (!name) return 'document.pdf';\n return /\\.pdf$/i.test(name) ? name : `${name}.pdf`;\n}\n\n/** A snapshot's file name: the document's name and the page's number, as a PNG (`Report p3.png`). */\nfunction snapshotFileNameOf(name: string | undefined, pageNumber: number): string {\n const base = (name ?? 'document').replace(/\\.pdf$/i, '');\n return `${base} p${pageNumber}.png`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,MAAM,WAAW,YAA4B,QAAQ,OAAOA,gCAAAA,UAAU;AACtE,MAAM,cAAc,YAA4B,QAAQ,OAAOC,iCAAAA,WAAW,CAAC,EAAE,YAAY,KAAK;AAC9F,MAAM,iBAAiB,YAA4B,QAAQ,OAAOC,sCAAAA,gBAAgB;;AAGlF,MAAM,YAAY,YAAqC,QAAQ,OAAO,MAAM;;AAG5E,MAAM,0BAAU,IAAI,QAA4C;AAChE,MAAM,SAAS,UAA8C;CAC3D,IAAI,MAAM,QAAQ,IAAI,KAAK;CAC3B,IAAI,CAAC,KAAK;EACR,MAAM,MAAM,KAAK,SAAS,KAAK,EAAE;EACjC,QAAQ,IAAI,OAAO,GAAG;CACxB;CACA,OAAO;AACT;;;;;AAMA,MAAM,cAAc,SAAyB,WAA4B;CACvE,MAAM,aAAa,QAAQ,OAAOC,qCAAAA,eAAe;CACjD,OAAO,CAAC,YAAY,MAAM,IAAI,MAAM,KAAK,WAAW,UAAU;AAChE;;AAGA,MAAM,eAAe,YAAgE;CACnF,UAAU,iBAAiB;CAC3B,OAAO;CACP,MAAM;CACN,YAAY,CAAC,MAAM;CACnB,MAAM,YAAY,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AAe;GAGf,KAAK,OAAO,YAAY;IAEtB,MADkB,QAAQ,IAAIA,eAAAA,cAChB,CAAC,CAAC,MAAM,QAAQ,cAAc,KAAA,GAAW,EAAE,QAAQ,QAAQ,OAAO,CAAC;GACnF;GACA,UAAU,YAAY,QAAQ,eAAe;EAC/C;CACF;AACF;;AAGA,SAAS,WAAW,MAAkC;CACpD,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK;AAC/C;;AAGA,SAAS,mBAAmB,MAA0B,YAA4B;CAEhF,OAAO,IADO,QAAQ,WAAA,CAAY,QAAQ,WAAW,EACxC,EAAE,IAAI,WAAW;AAChC"}
|
package/dist/standard.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as
|
|
1
|
+
import { i as CommandDefinition, s as CommandFamily } from "./contract-Bt0jzEeF.cjs";
|
|
2
2
|
import { PageImage } from "@embedpdf/plugin-render/contract";
|
|
3
3
|
import { SelectionCapability } from "@embedpdf/plugin-selection/contract";
|
|
4
4
|
//#region src/standard.d.ts
|
|
@@ -15,7 +15,7 @@ interface StandardCommandsPlatform {
|
|
|
15
15
|
saveFile(bytes: Uint8Array | Blob, fileName: string, contentType: string): void;
|
|
16
16
|
}
|
|
17
17
|
/** The standard commands, with the browser's part from `platform`. */
|
|
18
|
-
declare function createStandardCommands(platform: StandardCommandsPlatform): readonly (
|
|
18
|
+
declare function createStandardCommands(platform: StandardCommandsPlatform): readonly (CommandDefinition | CommandFamily)[];
|
|
19
19
|
//#endregion
|
|
20
20
|
export { StandardCommandsPlatform, createStandardCommands };
|
|
21
21
|
//# sourceMappingURL=standard.d.cts.map
|
package/dist/standard.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as
|
|
1
|
+
import { i as CommandDefinition, s as CommandFamily } from "./contract-Bt0jzEeF.js";
|
|
2
2
|
import { PageImage } from "@embedpdf/plugin-render/contract";
|
|
3
3
|
import { SelectionCapability } from "@embedpdf/plugin-selection/contract";
|
|
4
4
|
//#region src/standard.d.ts
|
|
@@ -15,7 +15,7 @@ interface StandardCommandsPlatform {
|
|
|
15
15
|
saveFile(bytes: Uint8Array | Blob, fileName: string, contentType: string): void;
|
|
16
16
|
}
|
|
17
17
|
/** The standard commands, with the browser's part from `platform`. */
|
|
18
|
-
declare function createStandardCommands(platform: StandardCommandsPlatform): readonly (
|
|
18
|
+
declare function createStandardCommands(platform: StandardCommandsPlatform): readonly (CommandDefinition | CommandFamily)[];
|
|
19
19
|
//#endregion
|
|
20
20
|
export { StandardCommandsPlatform, createStandardCommands };
|
|
21
21
|
//# sourceMappingURL=standard.d.ts.map
|
package/dist/standard.js
CHANGED
|
@@ -205,7 +205,7 @@ function createStandardCommands(platform) {
|
|
|
205
205
|
enabled: (context) => {
|
|
206
206
|
const annotation = context.tryGet(AnnotationToken);
|
|
207
207
|
if (!annotation) return false;
|
|
208
|
-
const selected = annotation.selection.
|
|
208
|
+
const selected = annotation.selection.getSelected();
|
|
209
209
|
return selected.length > 0 && selected.every(({ ref }) => annotation.canDelete(ref) && annotation.isEditable(ref));
|
|
210
210
|
}
|
|
211
211
|
},
|
package/dist/standard.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standard.js","names":[],"sources":["../src/standard.ts"],"sourcesContent":["/**\n * @embedpdf/plugin-commands/standard — the commands every viewer has: zoom,\n * pages, view rotation, a command for every tool, copy, the snapshot, delete,\n * download and print, with shortcuts, and labels in EmbedPDF's eight\n * languages (the i18n plugin has the strings). Some of them reach the browser\n * (the clipboard, a file download), which plugins never touch, so each\n * framework's `/commands` builds them with its platform: that is the\n * `standardCommands` an app imports. Print goes through the kernel, which has\n * the host's printer.\n */\nimport { DocumentsToken } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { InteractionToken, type Tool } from '@embedpdf/plugin-interaction/contract';\nimport { RenderToken, SNAPSHOT_TOOL, type PageImage } from '@embedpdf/plugin-render/contract';\nimport { SelectionToken, type SelectionCapability } from '@embedpdf/plugin-selection/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport type { CommandContext, CommandDef, CommandFamily } from './contract';\n\n/** What the standard commands need from the browser. */\nexport interface StandardCommandsPlatform {\n /** Copy the selected text to the clipboard. */\n copySelection(selection: SelectionCapability): Promise<unknown>;\n /**\n * Copy an image to the clipboard. Called in the press or key itself, before\n * the image is there: a browser may take the clipboard only then.\n */\n copyImage(image: Promise<PageImage>): Promise<unknown>;\n /** Give the user the bytes as a file download, of the given content type. */\n saveFile(bytes: Uint8Array | Blob, fileName: string, contentType: string): void;\n}\n\nconst stageOf = (context: CommandContext) => context.tryGet(StageToken);\nconst snapshotOf = (context: CommandContext) => context.tryGet(RenderToken)?.getSnapshot() ?? null;\nconst interactionOf = (context: CommandContext) => context.tryGet(InteractionToken);\n\n/** Enabled while the document has a Stage. */\nconst hasStage = (context: CommandContext): boolean => stageOf(context) !== null;\n\n/** The ids of a tool list, made once per list, which keeps its identity while the tools don't change. */\nconst toolIds = new WeakMap<readonly Tool[], readonly string[]>();\nconst idsOf = (tools: readonly Tool[]): readonly string[] => {\n let ids = toolIds.get(tools);\n if (!ids) {\n ids = tools.map((tool) => tool.id);\n toolIds.set(tools, ids);\n }\n return ids;\n};\n\n/**\n * Whether the user may use a tool: one that draws annotations needs permission to create them.\n * A tool another plugin owns asks nothing here; that plugin refuses its own gesture.\n */\nconst mayUseTool = (context: CommandContext, toolId: string): boolean => {\n const annotation = context.tryGet(AnnotationToken);\n return !annotation?.tools.get(toolId) || annotation.canCreate();\n};\n\n/** Switching to a tool: active while it's the tool, there only when the document has it. */\nconst toolCommand = (toolId: string): Omit<CommandDef, 'id' | 'shortcut'> => ({\n labelKey: `commands.tool.${toolId}`,\n label: toolId,\n icon: toolId,\n categories: ['tool'],\n run: (context) => interactionOf(context)?.activateTool(toolId),\n active: (context) => interactionOf(context)?.getActiveToolId() === toolId,\n visible: (context) => interactionOf(context)?.hasTool(toolId) ?? false,\n enabled: (context) => mayUseTool(context, toolId),\n});\n\n/** `tool:<id>` for every tool the document has. */\nconst toolCommands: CommandFamily = {\n prefix: 'tool:',\n names: (context) => {\n const interaction = interactionOf(context);\n return interaction ? idsOf(interaction.listTools()) : [];\n },\n command: toolCommand,\n};\n\n/** The standard commands, with the browser's part from `platform`. */\nexport function createStandardCommands(\n platform: StandardCommandsPlatform,\n): readonly (CommandDef | CommandFamily)[] {\n return [\n // ── zoom ──\n {\n id: 'zoom:in',\n labelKey: 'commands.zoom.in',\n label: 'Zoom in',\n icon: 'zoom-in',\n shortcut: ['Mod+=', 'Mod+NumpadAdd'],\n categories: ['zoom'],\n run: (context) => stageOf(context)?.zoomIn(),\n enabled: (context) => stageOf(context)?.canZoomIn() ?? false,\n },\n {\n id: 'zoom:out',\n labelKey: 'commands.zoom.out',\n label: 'Zoom out',\n icon: 'zoom-out',\n shortcut: ['Mod+-', 'Mod+NumpadSubtract'],\n categories: ['zoom'],\n run: (context) => stageOf(context)?.zoomOut(),\n enabled: (context) => stageOf(context)?.canZoomOut() ?? false,\n },\n {\n id: 'zoom:fit-width',\n labelKey: 'commands.zoom.fitWidth',\n label: 'Fit width',\n icon: 'fit-width',\n categories: ['zoom'],\n run: (context) => stageOf(context)?.fitWidth(),\n active: (context) => stageOf(context)?.getZoomMode() === 'fit-width',\n enabled: hasStage,\n },\n {\n id: 'zoom:fit-page',\n labelKey: 'commands.zoom.fitPage',\n label: 'Fit page',\n icon: 'fit-page',\n categories: ['zoom'],\n run: (context) => stageOf(context)?.fitPage(),\n active: (context) => stageOf(context)?.getZoomMode() === 'fit-page',\n enabled: hasStage,\n },\n\n // ── pages ──\n {\n id: 'page:next',\n labelKey: 'commands.page.next',\n label: 'Next page',\n icon: 'next-page',\n shortcut: 'ArrowRight',\n categories: ['page'],\n run: (context) => stageOf(context)?.nextPage(),\n enabled: (context) => stageOf(context)?.canGoNext() ?? false,\n },\n {\n id: 'page:previous',\n labelKey: 'commands.page.previous',\n label: 'Previous page',\n icon: 'previous-page',\n shortcut: 'ArrowLeft',\n categories: ['page'],\n run: (context) => stageOf(context)?.previousPage(),\n enabled: (context) => stageOf(context)?.canGoPrevious() ?? false,\n },\n {\n id: 'page:first',\n labelKey: 'commands.page.first',\n label: 'First page',\n icon: 'first-page',\n shortcut: 'Home',\n categories: ['page'],\n run: (context) => stageOf(context)?.goToFirstPage(),\n enabled: (context) => stageOf(context)?.canGoPrevious() ?? false,\n },\n {\n id: 'page:last',\n labelKey: 'commands.page.last',\n label: 'Last page',\n icon: 'last-page',\n shortcut: 'End',\n categories: ['page'],\n run: (context) => stageOf(context)?.goToLastPage(),\n enabled: (context) => stageOf(context)?.canGoNext() ?? false,\n },\n\n // ── view rotation: how the pages show, nothing written to the PDF ──\n {\n id: 'view:rotate-clockwise',\n labelKey: 'commands.view.rotateClockwise',\n label: 'Rotate clockwise',\n icon: 'rotate-clockwise',\n categories: ['view'],\n run: (context) => stageOf(context)?.rotateViewBy(90),\n enabled: hasStage,\n },\n {\n id: 'view:rotate-counterclockwise',\n labelKey: 'commands.view.rotateCounterclockwise',\n label: 'Rotate counterclockwise',\n icon: 'rotate-counterclockwise',\n categories: ['view'],\n run: (context) => stageOf(context)?.rotateViewBy(-90),\n enabled: hasStage,\n },\n\n // ── tools: the built-in ones have Acrobat's single keys; the family covers every other ──\n { ...toolCommand('pointer'), id: 'tool:pointer', shortcut: 'V' },\n { ...toolCommand('pan'), id: 'tool:pan', shortcut: 'H' },\n { ...toolCommand('zoom'), id: 'tool:zoom', shortcut: 'Z' },\n {\n ...toolCommand(SNAPSHOT_TOOL),\n id: 'tool:snapshot',\n allowed: (context) => context.tryGet(RenderToken)?.canSnapshot() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-content-copy',\n },\n toolCommands,\n\n // ── selections ──\n {\n id: 'selection:copy',\n labelKey: 'commands.selection.copy',\n label: 'Copy',\n icon: 'copy',\n shortcut: 'Mod+C',\n categories: ['selection'],\n run: (context) => platform.copySelection(context.get(SelectionToken)),\n // `canCopy()` in `enabled`, not `allowed`: a refused command keeps its keys, and Mod+C\n // with nothing selected in the viewer belongs to the page. The clipboard wiring says\n // when a selection may not be copied.\n enabled: (context) => {\n const selection = context.tryGet(SelectionToken);\n return !!selection && selection.hasSelection() && selection.canCopy();\n },\n },\n {\n id: 'annotation:delete',\n labelKey: 'commands.annotation.delete',\n label: 'Delete',\n icon: 'delete',\n shortcut: ['Delete', 'Backspace'],\n categories: ['annotation'],\n run: (context) => context.get(AnnotationToken).selection.delete({ signal: context.signal }),\n enabled: (context) => {\n const annotation = context.tryGet(AnnotationToken);\n if (!annotation) return false;\n const selected = annotation.selection.list();\n // `isEditable`: the annotation plugin's `editable` setting lets people change it by hand.\n return (\n selected.length > 0 &&\n selected.every(({ ref }) => annotation.canDelete(ref) && annotation.isEditable(ref))\n );\n },\n },\n\n // ── the snapshot the snapshot tool holds ──\n {\n id: 'snapshot:copy',\n labelKey: 'commands.snapshot.copy',\n label: 'Copy',\n icon: 'copy',\n shortcut: 'Mod+C',\n categories: ['snapshot'],\n // Straight to the clipboard, in the press itself: the picture follows when it's there.\n run: (context) => {\n const snapshot = snapshotOf(context);\n return snapshot ? platform.copyImage(snapshot.image) : undefined;\n },\n enabled: (context) => snapshotOf(context) !== null,\n },\n {\n id: 'snapshot:save',\n labelKey: 'commands.snapshot.save',\n label: 'Save image',\n icon: 'download',\n categories: ['snapshot'],\n run: async (context) => {\n const snapshot = snapshotOf(context);\n if (!snapshot) return;\n const documents = context.get(DocumentsToken);\n const id = context.documentId ?? undefined;\n const blob = await (await snapshot.image).blob();\n const number =\n documents\n .listPages(id)\n .findIndex((page) => page.ref.objectNumber === snapshot.page.objectNumber) + 1;\n platform.saveFile(blob, snapshotFileNameOf(documents.get(id)?.name, number), 'image/png');\n },\n enabled: (context) => snapshotOf(context) !== null,\n },\n {\n id: 'snapshot:clear',\n labelKey: 'commands.snapshot.clear',\n label: 'Clear snapshot',\n shortcut: 'Escape',\n categories: ['snapshot'],\n run: (context) => context.get(RenderToken).clearSnapshot(),\n enabled: (context) => snapshotOf(context) !== null,\n },\n\n // ── the document ──\n {\n id: 'document:download',\n labelKey: 'commands.document.download',\n label: 'Download',\n icon: 'download',\n shortcut: 'Mod+S',\n categories: ['document'],\n allowed: (context) => context.tryGet(DocumentsToken)?.canDownload() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-download',\n run: async (context) => {\n const documents = context.get(DocumentsToken);\n const id = context.documentId ?? undefined;\n const bytes = await documents.download(id, { signal: context.signal });\n platform.saveFile(bytes, fileNameOf(documents.get(id)?.name), 'application/pdf');\n },\n enabled: (context) => context.documentId !== null,\n },\n {\n id: 'document:print',\n labelKey: 'commands.document.print',\n label: 'Print',\n icon: 'print',\n shortcut: 'Mod+P',\n categories: ['document'],\n allowed: (context) => context.tryGet(DocumentsToken)?.canPrint() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-print',\n // The kernel prints the document's pages, and runs the document's own\n // print actions around the dialog when the actions plugin is there.\n run: async (context) => {\n const documents = context.get(DocumentsToken);\n await documents.print(context.documentId ?? undefined, { signal: context.signal });\n },\n enabled: (context) => context.documentId !== null,\n },\n ];\n}\n\n/** The download's file name: the document's name, ending in `.pdf`. */\nfunction fileNameOf(name: string | undefined): string {\n if (!name) return 'document.pdf';\n return /\\.pdf$/i.test(name) ? name : `${name}.pdf`;\n}\n\n/** A snapshot's file name: the document's name and the page's number, as a PNG (`Report p3.png`). */\nfunction snapshotFileNameOf(name: string | undefined, pageNumber: number): string {\n const base = (name ?? 'document').replace(/\\.pdf$/i, '');\n return `${base} p${pageNumber}.png`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,MAAM,WAAW,YAA4B,QAAQ,OAAO,UAAU;AACtE,MAAM,cAAc,YAA4B,QAAQ,OAAO,WAAW,CAAC,EAAE,YAAY,KAAK;AAC9F,MAAM,iBAAiB,YAA4B,QAAQ,OAAO,gBAAgB;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AAM,YAAY,QAAQ,IAAI,cAAc;IAC5C,MAAM,KAAK,QAAQ,cAAc,KAAA;IACjC,MAAM,QAAQ,MAAM,UAAU,SAAS,IAAI,EAAE,QAAQ,QAAQ,OAAO,CAAC;IACrE,SAAS,SAAS,OAAO,WAAW,UAAU,IAAI,EAAE,CAAC,EAAE,IAAI,GAAG,iBAAiB;GACjF;GACA,UAAU,YAAY,QAAQ,eAAe;EAC/C;EACA;GACE,IAAI;GACJ,UAAU;GACV,OAAO;GACP,MAAM;GACN,UAAU;GACV,YAAY,CAAC,UAAU;GACvB,UAAU,YAAY,QAAQ,OAAO,cAAc,CAAC,EAAE,SAAS,KAAK;GACpE,eAAe;GAGf,KAAK,OAAO,YAAY;IAEtB,MADkB,QAAQ,IAAI,cAChB,CAAC,CAAC,MAAM,QAAQ,cAAc,KAAA,GAAW,EAAE,QAAQ,QAAQ,OAAO,CAAC;GACnF;GACA,UAAU,YAAY,QAAQ,eAAe;EAC/C;CACF;AACF;;AAGA,SAAS,WAAW,MAAkC;CACpD,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK;AAC/C;;AAGA,SAAS,mBAAmB,MAA0B,YAA4B;CAEhF,OAAO,IADO,QAAQ,WAAA,CAAY,QAAQ,WAAW,EACxC,EAAE,IAAI,WAAW;AAChC"}
|
|
1
|
+
{"version":3,"file":"standard.js","names":[],"sources":["../src/standard.ts"],"sourcesContent":["/**\n * @embedpdf/plugin-commands/standard — the commands every viewer has: zoom,\n * pages, view rotation, a command for every tool, copy, the snapshot, delete,\n * download and print, with shortcuts, and labels in EmbedPDF's eight\n * languages (the i18n plugin has the strings). Some of them reach the browser\n * (the clipboard, a file download), which plugins never touch, so each\n * framework's `/commands` builds them with its platform: that is the\n * `standardCommands` an app imports. Print goes through the kernel, which has\n * the host's printer.\n */\nimport { DocumentsToken } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { InteractionToken, type Tool } from '@embedpdf/plugin-interaction/contract';\nimport { RenderToken, SNAPSHOT_TOOL, type PageImage } from '@embedpdf/plugin-render/contract';\nimport { SelectionToken, type SelectionCapability } from '@embedpdf/plugin-selection/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport type { CommandContext, CommandDefinition, CommandFamily } from './contract';\n\n/** What the standard commands need from the browser. */\nexport interface StandardCommandsPlatform {\n /** Copy the selected text to the clipboard. */\n copySelection(selection: SelectionCapability): Promise<unknown>;\n /**\n * Copy an image to the clipboard. Called in the press or key itself, before\n * the image is there: a browser may take the clipboard only then.\n */\n copyImage(image: Promise<PageImage>): Promise<unknown>;\n /** Give the user the bytes as a file download, of the given content type. */\n saveFile(bytes: Uint8Array | Blob, fileName: string, contentType: string): void;\n}\n\nconst stageOf = (context: CommandContext) => context.tryGet(StageToken);\nconst snapshotOf = (context: CommandContext) => context.tryGet(RenderToken)?.getSnapshot() ?? null;\nconst interactionOf = (context: CommandContext) => context.tryGet(InteractionToken);\n\n/** Enabled while the document has a Stage. */\nconst hasStage = (context: CommandContext): boolean => stageOf(context) !== null;\n\n/** The ids of a tool list, made once per list, which keeps its identity while the tools don't change. */\nconst toolIds = new WeakMap<readonly Tool[], readonly string[]>();\nconst idsOf = (tools: readonly Tool[]): readonly string[] => {\n let ids = toolIds.get(tools);\n if (!ids) {\n ids = tools.map((tool) => tool.id);\n toolIds.set(tools, ids);\n }\n return ids;\n};\n\n/**\n * Whether the user may use a tool: one that draws annotations needs permission to create them.\n * A tool another plugin owns asks nothing here; that plugin refuses its own gesture.\n */\nconst mayUseTool = (context: CommandContext, toolId: string): boolean => {\n const annotation = context.tryGet(AnnotationToken);\n return !annotation?.tools.get(toolId) || annotation.canCreate();\n};\n\n/** Switching to a tool: active while it's the tool, there only when the document has it. */\nconst toolCommand = (toolId: string): Omit<CommandDefinition, 'id' | 'shortcut'> => ({\n labelKey: `commands.tool.${toolId}`,\n label: toolId,\n icon: toolId,\n categories: ['tool'],\n run: (context) => interactionOf(context)?.activateTool(toolId),\n active: (context) => interactionOf(context)?.getActiveToolId() === toolId,\n visible: (context) => interactionOf(context)?.hasTool(toolId) ?? false,\n enabled: (context) => mayUseTool(context, toolId),\n});\n\n/** `tool:<id>` for every tool the document has. */\nconst toolCommands: CommandFamily = {\n prefix: 'tool:',\n names: (context) => {\n const interaction = interactionOf(context);\n return interaction ? idsOf(interaction.listTools()) : [];\n },\n command: toolCommand,\n};\n\n/** The standard commands, with the browser's part from `platform`. */\nexport function createStandardCommands(\n platform: StandardCommandsPlatform,\n): readonly (CommandDefinition | CommandFamily)[] {\n return [\n // ── zoom ──\n {\n id: 'zoom:in',\n labelKey: 'commands.zoom.in',\n label: 'Zoom in',\n icon: 'zoom-in',\n shortcut: ['Mod+=', 'Mod+NumpadAdd'],\n categories: ['zoom'],\n run: (context) => stageOf(context)?.zoomIn(),\n enabled: (context) => stageOf(context)?.canZoomIn() ?? false,\n },\n {\n id: 'zoom:out',\n labelKey: 'commands.zoom.out',\n label: 'Zoom out',\n icon: 'zoom-out',\n shortcut: ['Mod+-', 'Mod+NumpadSubtract'],\n categories: ['zoom'],\n run: (context) => stageOf(context)?.zoomOut(),\n enabled: (context) => stageOf(context)?.canZoomOut() ?? false,\n },\n {\n id: 'zoom:fit-width',\n labelKey: 'commands.zoom.fitWidth',\n label: 'Fit width',\n icon: 'fit-width',\n categories: ['zoom'],\n run: (context) => stageOf(context)?.fitWidth(),\n active: (context) => stageOf(context)?.getZoomMode() === 'fit-width',\n enabled: hasStage,\n },\n {\n id: 'zoom:fit-page',\n labelKey: 'commands.zoom.fitPage',\n label: 'Fit page',\n icon: 'fit-page',\n categories: ['zoom'],\n run: (context) => stageOf(context)?.fitPage(),\n active: (context) => stageOf(context)?.getZoomMode() === 'fit-page',\n enabled: hasStage,\n },\n\n // ── pages ──\n {\n id: 'page:next',\n labelKey: 'commands.page.next',\n label: 'Next page',\n icon: 'next-page',\n shortcut: 'ArrowRight',\n categories: ['page'],\n run: (context) => stageOf(context)?.nextPage(),\n enabled: (context) => stageOf(context)?.canGoNext() ?? false,\n },\n {\n id: 'page:previous',\n labelKey: 'commands.page.previous',\n label: 'Previous page',\n icon: 'previous-page',\n shortcut: 'ArrowLeft',\n categories: ['page'],\n run: (context) => stageOf(context)?.previousPage(),\n enabled: (context) => stageOf(context)?.canGoPrevious() ?? false,\n },\n {\n id: 'page:first',\n labelKey: 'commands.page.first',\n label: 'First page',\n icon: 'first-page',\n shortcut: 'Home',\n categories: ['page'],\n run: (context) => stageOf(context)?.goToFirstPage(),\n enabled: (context) => stageOf(context)?.canGoPrevious() ?? false,\n },\n {\n id: 'page:last',\n labelKey: 'commands.page.last',\n label: 'Last page',\n icon: 'last-page',\n shortcut: 'End',\n categories: ['page'],\n run: (context) => stageOf(context)?.goToLastPage(),\n enabled: (context) => stageOf(context)?.canGoNext() ?? false,\n },\n\n // ── view rotation: how the pages show, nothing written to the PDF ──\n {\n id: 'view:rotate-clockwise',\n labelKey: 'commands.view.rotateClockwise',\n label: 'Rotate clockwise',\n icon: 'rotate-clockwise',\n categories: ['view'],\n run: (context) => stageOf(context)?.rotateViewBy(90),\n enabled: hasStage,\n },\n {\n id: 'view:rotate-counterclockwise',\n labelKey: 'commands.view.rotateCounterclockwise',\n label: 'Rotate counterclockwise',\n icon: 'rotate-counterclockwise',\n categories: ['view'],\n run: (context) => stageOf(context)?.rotateViewBy(-90),\n enabled: hasStage,\n },\n\n // ── tools: the built-in ones have Acrobat's single keys; the family covers every other ──\n { ...toolCommand('pointer'), id: 'tool:pointer', shortcut: 'V' },\n { ...toolCommand('pan'), id: 'tool:pan', shortcut: 'H' },\n { ...toolCommand('zoom'), id: 'tool:zoom', shortcut: 'Z' },\n {\n ...toolCommand(SNAPSHOT_TOOL),\n id: 'tool:snapshot',\n allowed: (context) => context.tryGet(RenderToken)?.canSnapshot() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-content-copy',\n },\n toolCommands,\n\n // ── selections ──\n {\n id: 'selection:copy',\n labelKey: 'commands.selection.copy',\n label: 'Copy',\n icon: 'copy',\n shortcut: 'Mod+C',\n categories: ['selection'],\n run: (context) => platform.copySelection(context.get(SelectionToken)),\n // `canCopy()` in `enabled`, not `allowed`: a refused command keeps its keys, and Mod+C\n // with nothing selected in the viewer belongs to the page. The clipboard wiring says\n // when a selection may not be copied.\n enabled: (context) => {\n const selection = context.tryGet(SelectionToken);\n return !!selection && selection.hasSelection() && selection.canCopy();\n },\n },\n {\n id: 'annotation:delete',\n labelKey: 'commands.annotation.delete',\n label: 'Delete',\n icon: 'delete',\n shortcut: ['Delete', 'Backspace'],\n categories: ['annotation'],\n run: (context) => context.get(AnnotationToken).selection.delete({ signal: context.signal }),\n enabled: (context) => {\n const annotation = context.tryGet(AnnotationToken);\n if (!annotation) return false;\n const selected = annotation.selection.getSelected();\n // `isEditable`: the annotation plugin's `editable` setting lets people change it by hand.\n return (\n selected.length > 0 &&\n selected.every(({ ref }) => annotation.canDelete(ref) && annotation.isEditable(ref))\n );\n },\n },\n\n // ── the snapshot the snapshot tool holds ──\n {\n id: 'snapshot:copy',\n labelKey: 'commands.snapshot.copy',\n label: 'Copy',\n icon: 'copy',\n shortcut: 'Mod+C',\n categories: ['snapshot'],\n // Straight to the clipboard, in the press itself: the picture follows when it's there.\n run: (context) => {\n const snapshot = snapshotOf(context);\n return snapshot ? platform.copyImage(snapshot.image) : undefined;\n },\n enabled: (context) => snapshotOf(context) !== null,\n },\n {\n id: 'snapshot:save',\n labelKey: 'commands.snapshot.save',\n label: 'Save image',\n icon: 'download',\n categories: ['snapshot'],\n run: async (context) => {\n const snapshot = snapshotOf(context);\n if (!snapshot) return;\n const documents = context.get(DocumentsToken);\n const id = context.documentId ?? undefined;\n const blob = await (await snapshot.image).blob();\n const number =\n documents\n .listPages(id)\n .findIndex((page) => page.ref.objectNumber === snapshot.page.objectNumber) + 1;\n platform.saveFile(blob, snapshotFileNameOf(documents.get(id)?.name, number), 'image/png');\n },\n enabled: (context) => snapshotOf(context) !== null,\n },\n {\n id: 'snapshot:clear',\n labelKey: 'commands.snapshot.clear',\n label: 'Clear snapshot',\n shortcut: 'Escape',\n categories: ['snapshot'],\n run: (context) => context.get(RenderToken).clearSnapshot(),\n enabled: (context) => snapshotOf(context) !== null,\n },\n\n // ── the document ──\n {\n id: 'document:download',\n labelKey: 'commands.document.download',\n label: 'Download',\n icon: 'download',\n shortcut: 'Mod+S',\n categories: ['document'],\n allowed: (context) => context.tryGet(DocumentsToken)?.canDownload() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-download',\n run: async (context) => {\n const documents = context.get(DocumentsToken);\n const id = context.documentId ?? undefined;\n const bytes = await documents.download(id, { signal: context.signal });\n platform.saveFile(bytes, fileNameOf(documents.get(id)?.name), 'application/pdf');\n },\n enabled: (context) => context.documentId !== null,\n },\n {\n id: 'document:print',\n labelKey: 'commands.document.print',\n label: 'Print',\n icon: 'print',\n shortcut: 'Mod+P',\n categories: ['document'],\n allowed: (context) => context.tryGet(DocumentsToken)?.canPrint() ?? true,\n notAllowedKey: 'commands.notAllowed.doc-print',\n // The kernel prints the document's pages, and runs the document's own\n // print actions around the dialog when the actions plugin is there.\n run: async (context) => {\n const documents = context.get(DocumentsToken);\n await documents.print(context.documentId ?? undefined, { signal: context.signal });\n },\n enabled: (context) => context.documentId !== null,\n },\n ];\n}\n\n/** The download's file name: the document's name, ending in `.pdf`. */\nfunction fileNameOf(name: string | undefined): string {\n if (!name) return 'document.pdf';\n return /\\.pdf$/i.test(name) ? name : `${name}.pdf`;\n}\n\n/** A snapshot's file name: the document's name and the page's number, as a PNG (`Report p3.png`). */\nfunction snapshotFileNameOf(name: string | undefined, pageNumber: number): string {\n const base = (name ?? 'document').replace(/\\.pdf$/i, '');\n return `${base} p${pageNumber}.png`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,MAAM,WAAW,YAA4B,QAAQ,OAAO,UAAU;AACtE,MAAM,cAAc,YAA4B,QAAQ,OAAO,WAAW,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cAAc,CAAC,EAAE,YAAY,KAAK;GACvE,eAAe;GACf,KAAK,OAAO,YAAY;IACtB,MAAM,YAAY,QAAQ,IAAI,cAAc;IAC5C,MAAM,KAAK,QAAQ,cAAc,KAAA;IACjC,MAAM,QAAQ,MAAM,UAAU,SAAS,IAAI,EAAE,QAAQ,QAAQ,OAAO,CAAC;IACrE,SAAS,SAAS,OAAO,WAAW,UAAU,IAAI,EAAE,CAAC,EAAE,IAAI,GAAG,iBAAiB;GACjF;GACA,UAAU,YAAY,QAAQ,eAAe;EAC/C;EACA;GACE,IAAI;GACJ,UAAU;GACV,OAAO;GACP,MAAM;GACN,UAAU;GACV,YAAY,CAAC,UAAU;GACvB,UAAU,YAAY,QAAQ,OAAO,cAAc,CAAC,EAAE,SAAS,KAAK;GACpE,eAAe;GAGf,KAAK,OAAO,YAAY;IAEtB,MADkB,QAAQ,IAAI,cAChB,CAAC,CAAC,MAAM,QAAQ,cAAc,KAAA,GAAW,EAAE,QAAQ,QAAQ,OAAO,CAAC;GACnF;GACA,UAAU,YAAY,QAAQ,eAAe;EAC/C;CACF;AACF;;AAGA,SAAS,WAAW,MAAkC;CACpD,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK;AAC/C;;AAGA,SAAS,mBAAmB,MAA0B,YAA4B;CAEhF,OAAO,IADO,QAAQ,WAAA,CAAY,QAAQ,WAAW,EACxC,EAAE,IAAI,WAAW;AAChC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@embedpdf/plugin-commands",
|
|
3
|
-
"version": "3.0.0-next.
|
|
3
|
+
"version": "3.0.0-next.23",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "The commands: one name per action of the viewer, with its label, icon, state and shortcut, which toolbars, menus, a command palette and the keyboard all show and run. A command's state is read from live state, so every reader follows the kernel's one change stream. `/standard` has the commands every viewer has.",
|
|
6
6
|
"type": "module",
|
|
@@ -30,15 +30,15 @@
|
|
|
30
30
|
"dist"
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@embedpdf/core": "3.0.0-next.
|
|
34
|
-
"@embedpdf/core
|
|
35
|
-
"@embedpdf/plugin-annotation": "3.0.0-next.
|
|
36
|
-
"@embedpdf/plugin-
|
|
37
|
-
"@embedpdf/plugin-
|
|
38
|
-
"@embedpdf/plugin-
|
|
39
|
-
"@embedpdf/plugin-shell": "3.0.0-next.
|
|
40
|
-
"@embedpdf/plugin-stage": "3.0.0-next.
|
|
41
|
-
"@embedpdf/plugin-
|
|
33
|
+
"@embedpdf/core-ui": "3.0.0-next.23",
|
|
34
|
+
"@embedpdf/core": "3.0.0-next.23",
|
|
35
|
+
"@embedpdf/plugin-annotation": "3.0.0-next.23",
|
|
36
|
+
"@embedpdf/plugin-interaction": "3.0.0-next.23",
|
|
37
|
+
"@embedpdf/plugin-render": "3.0.0-next.23",
|
|
38
|
+
"@embedpdf/plugin-selection": "3.0.0-next.23",
|
|
39
|
+
"@embedpdf/plugin-shell": "3.0.0-next.23",
|
|
40
|
+
"@embedpdf/plugin-stage": "3.0.0-next.23",
|
|
41
|
+
"@embedpdf/plugin-i18n": "3.0.0-next.23"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"typescript": "^5.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"contract-FbiUhTWC.js","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it to the host capability. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { CommandsCapability } from './contract';\n\nexport const CommandsToken = createCapabilityToken<CommandsCapability>('commands', {\n hint: `add commandsPlugin() from '@embedpdf/plugin-commands' to your plugins list`,\n});\n","/**\n * @embedpdf/plugin-commands/contract — the commands that toolbars, menus,\n * shortcuts and a command palette all show and run.\n *\n * A command's state is read from live state: `resolveCommand` asks the other\n * capabilities when it's called, so every reader follows the kernel's one\n * change stream, with no events. Definitions hold functions, so they live in\n * the settings and the plugin's registry, never in state.\n */\nimport type {\n CapabilityToken,\n DeepPartial,\n EventHook,\n OperationOptions,\n Permission,\n PluginErrorInfo,\n SettingLock,\n SettingsApi,\n Unsubscribe,\n} from '@embedpdf/core';\nimport { didYouMean, formatShortcut } from '@embedpdf/core-ui';\n\nexport { CommandsToken } from './token';\n\nexport type CommandId = string;\n\n/**\n * What a command's derivations and `run` see: capabilities resolved for the command's document\n * (the one named, else the document in scope, else the active one), and your app's state.\n */\nexport interface CommandContext<AppState = any> {\n /** The command's document, or `null` when none is open. */\n readonly documentId: string | null;\n /** Your app's state, as the `appState` setting has it now: `any` until you give its type. */\n readonly appState: AppState;\n /** What the caller passed: `execute(id, { args })`. */\n readonly args?: unknown;\n /** Fires when the caller cancels `execute()`: pass it on to the calls `run` makes. */\n readonly signal?: AbortSignal;\n /** A capability, for the command's document when the plugin is document-scoped. Throws when it isn't available. */\n get<T>(token: CapabilityToken<T>): T;\n /** Like `get`, but `null` when the capability isn't available (no plugin, no document). */\n tryGet<T>(token: CapabilityToken<T>): T | null;\n}\n\n/**\n * Up to two colors that go with a command's icon, such as a tool's current color: data a\n * renderer may use (tint the icon, show a swatch), like `icon` itself.\n */\nexport interface IconAccent {\n /** The mark: a stroke, the markup or the text color. */\n readonly primary?: string;\n /** The fill, when there is one. */\n readonly secondary?: string;\n}\n\n/**\n * One command, as you define it. Its functions get your app's state as `AppState`; they're\n * methods, so a command typed for your state (`CommandDef<Review>`) goes wherever a command does.\n */\nexport interface CommandDef<AppState = any> {\n /** A unique name, by convention `area:action`: `'zoom:in'`, `'review:approve'`. */\n readonly id: string;\n /** What the user sees. With `labelKey` too, it's what shows when no language has the key. */\n readonly label?: string;\n /**\n * A translation key for the label, read through the i18n plugin. Without the plugin, or a\n * string for the key, the command shows `label`, else the key.\n */\n readonly labelKey?: string;\n /** Your icon's name; your buttons turn it into an icon. */\n readonly icon?: string;\n /** Colors for the icon, read from live state like `active`. */\n iconAccent?(context: CommandContext<AppState>): IconAccent | null;\n /** A key such as `'Mod+K'` (`Mod` is Cmd on a Mac, Ctrl elsewhere), or a list of them. */\n readonly shortcut?: string | readonly string[];\n /**\n * Whether its shortcut also runs while the cursor is in a text field where the shortcuts\n * listen (a search box, a comment), as the viewer's Find does. Default false: a key typed in\n * a field is the field's.\n */\n readonly shortcutInTextFields?: boolean;\n /**\n * The features it belongs to, so turning one off turns it off: `['annotations.highlight']`.\n * Turning off a feature turns off every feature under it, on whole dotted parts: `annotations`\n * covers `annotations.highlight`, not `annotationsExtra`.\n */\n readonly categories?: readonly string[];\n /**\n * The scope permissions it needs, such as `'doc.annotate.modify'`, checked against its\n * document. Without them it's hidden, or shown disabled with its reason under the\n * `notAllowed: 'disable'` setting. With no document open there is nothing to check.\n */\n readonly requires?: readonly Permission[];\n /**\n * Whether the session may run it, from the plugins' `can*` checks\n * (`documents.canPrint()`), for a command whose permission is a plugin's to know. When it\n * says no, the command isn't allowed, as with `requires`. Asked only while a document is\n * open; one that throws allows it.\n */\n allowed?(context: CommandContext<AppState>): boolean;\n /**\n * The translation key of the sentence that says why `allowed` refused it, with `{label}` for\n * its label: `'commands.notAllowed.doc-print'`. Without it, or a string for it,\n * `commands.notAllowed.default`.\n */\n readonly notAllowedKey?: string;\n /**\n * The lock on the setting it changes, for a command that changes one\n * (`(context) => context.get(StageToken).getLock('spread')`), or `null`.\n * While a lock holds, it shows disabled, whatever the `notAllowed` setting\n * says, with the sentence under the lock's `reasonKey` (else\n * `commands.locked.default`) as its `disabledReason`; it stays `active` for\n * its own value. One that throws counts as unlocked.\n */\n locked?(context: CommandContext<AppState>): SettingLock | null;\n\n // ── what the command opens ───────────────────────────────────────────────\n // A command that opens a panel, menu or dialog says so instead of opening\n // it in `run`: it then needs no `run`, it shows as active while the surface\n // is open, and a button can show that it opens a menu.\n /** Opens and closes a menu of yours, by its id. */\n readonly menu?: string;\n /**\n * Opens and closes a panel, closing the others with the same `exclusive` tag. With `focus`,\n * opening it asks for the cursor (the shell's `open(id, { focus: true })`).\n */\n readonly panel?:\n | string\n | { readonly id: string; readonly exclusive?: string; readonly focus?: boolean };\n /** Opens and closes a dialog; one dialog is open at a time. */\n readonly modal?: string;\n\n // ── read from live state and your app's, again whenever either changes ──\n /** When it can run. Default: always. One that throws counts as false. */\n enabled?(context: CommandContext<AppState>): boolean;\n /** When it shows as pressed, such as the current tool. One that throws counts as false. */\n active?(context: CommandContext<AppState>): boolean;\n /** When it shows at all. Default: always. One that throws counts as false. */\n visible?(context: CommandContext<AppState>): boolean;\n\n /** What it does; `execute()` resolves once it has. Not needed for a `menu`, `panel` or `modal`. */\n run?(context: CommandContext<AppState>): void | Promise<unknown>;\n}\n\n/**\n * A command for each of a set of names, made from one definition, such as `tool:<id>` for every\n * tool a document has. Its commands resolve and run like any other, and `listCommands()` lists\n * one per name. A command defined with the same id wins over the family's.\n */\nexport interface CommandFamily {\n /** Where the commands' ids start: `'tool:'` makes `tool:highlight`. */\n readonly prefix: string;\n /** The names the command's document has, in order. Return the same array while nothing changed. */\n readonly names: (context: CommandContext) => readonly string[];\n /** The command for one name. A family's commands have no shortcuts. */\n readonly command: (name: string) => Omit<CommandDef, 'id' | 'shortcut'>;\n}\n\n/** A command as a button shows it: everything read for its document. */\nexport interface ResolvedCommand {\n readonly id: string;\n readonly label: string;\n readonly icon?: string;\n readonly iconAccent?: IconAccent;\n readonly shortcuts: readonly string[];\n readonly menu?: string;\n readonly enabled: boolean;\n readonly active: boolean;\n readonly visible: boolean;\n readonly categories: readonly string[];\n /**\n * Why it's disabled, as a sentence for its tooltip: set when the scope doesn't allow it and\n * the `notAllowed` setting is `'disable'`, or when a lock holds the setting it changes.\n */\n readonly disabledReason?: string;\n}\n\n/**\n * Why a command won't run whatever the moment: it's turned off in this viewer\n * (`disabledCategories`, `disabledCommands`), the scope doesn't allow it (`requires`), or a lock\n * holds the setting it changes (`locked`). A command that only can't run right now (`enabled`,\n * `visible`) has no refusal.\n */\nexport interface CommandRefusal {\n readonly reason: 'turned-off' | 'not-allowed' | 'locked';\n /** A sentence for the user, translated through the i18n plugin when it's there. */\n readonly message: string;\n}\n\n/**\n * Whether two resolved commands show the same, for readers that compare what a command looks\n * like rather than which object holds it (a group of commands, or one command for two documents).\n */\nexport const resolvedCommandsEqual = (\n left: ResolvedCommand | null,\n right: ResolvedCommand | null,\n): boolean => {\n if (left === right) return true;\n if (!left || !right) return false;\n return (\n left.id === right.id &&\n left.label === right.label &&\n left.icon === right.icon &&\n left.iconAccent?.primary === right.iconAccent?.primary &&\n left.iconAccent?.secondary === right.iconAccent?.secondary &&\n left.menu === right.menu &&\n left.enabled === right.enabled &&\n left.active === right.active &&\n left.visible === right.visible &&\n left.disabledReason === right.disabledReason &&\n left.shortcuts.length === right.shortcuts.length &&\n left.shortcuts.every((shortcut, index) => shortcut === right.shortcuts[index])\n );\n};\n\n/**\n * What a component or a toolbar draws for a command id no plugin registered: labelled with its\n * id, neither enabled nor visible, the way a turned-off command is.\n */\nexport const unregisteredCommand = (id: CommandId): ResolvedCommand => ({\n id,\n label: id,\n shortcuts: [],\n enabled: false,\n active: false,\n visible: false,\n categories: [],\n});\n\n/** What a component that asks for an id no plugin registered hears, in development. */\nexport const unknownCommandWarning = (id: CommandId, known: Iterable<CommandId>): string =>\n `no command \"${id}\"${didYouMean(id, known)}: it shows as neither visible nor enabled`;\n\n/** A command with everything a button needs: what it shows, `run`, and its shortcut for a tooltip. */\nexport interface BoundCommand extends ResolvedCommand {\n /** Run the command for the document it was read for. */\n readonly run: () => Promise<ExecuteResult>;\n /** Its first shortcut, formatted for the platform (`'⌘K'` on a Mac, `'Ctrl+K'` elsewhere), or `null`. */\n readonly shortcut: string | null;\n}\n\n/**\n * A resolved command, bound for a button: `run` executes it through `execute`, and `shortcut` is\n * its first shortcut formatted for the platform. Which platform is the caller's to know\n * (`isMacPlatform()` in `@embedpdf/web`).\n */\nexport function boundCommandOf(\n command: ResolvedCommand,\n execute: (id: CommandId) => Promise<ExecuteResult>,\n options: { readonly isMac: boolean },\n): BoundCommand {\n const [first] = command.shortcuts;\n return {\n ...command,\n run: () => execute(command.id),\n shortcut: first === undefined ? null : formatShortcut(first, { isMac: options.isMac }),\n };\n}\n\n/**\n * The commands plugin's settings. `commandsPlugin(config)` registers them over\n * {@link COMMANDS_DEFAULTS}, and `updateSettings()` changes them while the app runs.\n */\nexport interface CommandsSettings {\n /** The commands your viewer has. A later definition with an id that's taken replaces the earlier one. */\n readonly commands: readonly (CommandDef | CommandFamily)[];\n /**\n * Your app's state, which every command's functions get as `appState`: values, and functions\n * that change them. A new value replaces the old one whole, and every command is asked again.\n */\n readonly appState: unknown;\n /**\n * Categories turned off, with every category under them: their commands are hidden and\n * refused wherever they appear.\n */\n readonly disabledCategories: readonly string[];\n /** Commands turned off one by one, by id: hidden and refused wherever they appear. */\n readonly disabledCommands: readonly CommandId[];\n /**\n * What a command the scope doesn't allow does: `'hide'` leaves it out, `'disable'` shows it\n * disabled, with the reason in its `disabledReason`.\n */\n readonly notAllowed: NotAllowedMode;\n}\n\n/** How a command shows when the scope doesn't allow it: hidden, or disabled with its reason. */\nexport type NotAllowedMode = 'hide' | 'disable';\n\n/** What the commands settings are when the app registers none. */\nexport const COMMANDS_DEFAULTS: CommandsSettings = {\n commands: [],\n appState: undefined,\n disabledCategories: [],\n disabledCommands: [],\n notAllowed: 'hide',\n};\n\n/** What `commandsPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type CommandsConfig<AppState = any> = Omit<\n DeepPartial<CommandsSettings>,\n 'commands' | 'appState'\n> & {\n readonly commands?: readonly (CommandDef<AppState> | CommandFamily)[];\n readonly appState?: AppState;\n};\n\nexport interface RegisterCommandOptions {\n /** Replace a command with the same id; without it, a taken id throws `conflict`. */\n replace?: boolean;\n}\n\nexport interface ExecuteOptions extends OperationOptions {\n /** The document to run it for; the document in scope, else the active one, when left out. */\n documentId?: string;\n /** Passed to the command's `run` and derivations as `args`. */\n args?: unknown;\n}\n\n/** How `execute()` went: it ran, or it was refused before running, and why. */\nexport type ExecuteResult =\n | { readonly status: 'executed' }\n | { readonly status: 'rejected'; readonly reason: 'not-found' | 'disabled' | 'hidden' };\n\n// ── events ──\nexport interface CommandExecutedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly args: unknown;\n}\nexport interface CommandExecutionFailedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly error: PluginErrorInfo;\n}\n\n/**\n * The commands. A call that leaves out the document is for the document in scope when the\n * capability was resolved for one (`ctx.forDocument`, a `<DocumentScope>`), and for the active\n * document otherwise.\n */\nexport interface CommandsCapability extends SettingsApi<CommandsSettings> {\n // ── the commands ──\n /**\n * Add a command while the app runs, and get a function that removes it. A taken id throws\n * `conflict` unless `replace`.\n */\n registerCommand(definition: CommandDef, options?: RegisterCommandOptions): Unsubscribe;\n /** `registerCommand` for several definitions; the function removes all of them. */\n registerCommands(\n definitions: readonly CommandDef[],\n options?: RegisterCommandOptions,\n ): Unsubscribe;\n /** Whether a command has this id; with a family, every id that starts with its prefix does. */\n hasCommand(id: CommandId): boolean;\n /** A command as you defined it, or `null`. */\n getCommand(id: CommandId): CommandDef | null;\n /** Every command's id for the active document, in the order they were added. The same array until one changes. */\n listCommandIds(): readonly CommandId[];\n\n // ── what a button shows ──\n /** A command as a button shows it, or `null` for an unknown id. The same object while nothing about it changed. */\n resolveCommand(id: CommandId, documentId?: string): ResolvedCommand | null;\n /** Every command, resolved, in the order they were added. The same array while nothing changed. */\n listCommands(documentId?: string): readonly ResolvedCommand[];\n /** The visible commands whose label or id contains the query, for a command palette. */\n searchCommands(query: string, documentId?: string): readonly ResolvedCommand[];\n /** Every shortcut with its command, for a keyboard help sheet. The same array until the commands change. */\n listShortcuts(): readonly { readonly commandId: CommandId; readonly shortcut: string }[];\n\n // ── running them ──\n /**\n * Run a command; resolves once its `run` has, with `{ status: 'executed' }` and\n * `onExecuted`, or `{ status: 'rejected', reason }` for a command that is unknown, hidden or\n * disabled (a command turned off is hidden). A `run` that throws fires `onExecutionFailed` and rejects with its `PluginError`;\n * the signal rejects `operation-cancelled`.\n */\n execute(id: CommandId, options?: ExecuteOptions): Promise<ExecuteResult>;\n /** Whether a command can run now: it exists, and is enabled and visible. */\n canExecute(id: CommandId, documentId?: string): boolean;\n /**\n * Why a command won't run whatever the moment: it's turned off, or not allowed for its\n * document. `null` when it may run (or only can't right now), and for an unknown id.\n */\n getRefusal(id: CommandId, documentId?: string): CommandRefusal | null;\n\n // ── turning commands off ──\n /** The categories turned off. */\n getDisabledCategories(): readonly string[];\n /** Whether a category is turned off: it, or a category it's under (`annotations` for `annotations.highlight`). */\n isCategoryDisabled(category: string): boolean;\n /** Turn a category off, with every category under it: the `disabledCategories` setting gains it. */\n disableCategory(category: string): void;\n /** Turn a category on again. */\n enableCategory(category: string): void;\n /** Replace the categories that are off. */\n setDisabledCategories(categories: readonly string[]): void;\n /** The commands turned off one by one. */\n getDisabledCommands(): readonly CommandId[];\n /** Whether a command is turned off: by its id, or through one of its categories. */\n isCommandDisabled(id: CommandId): boolean;\n /** Turn one command off: the `disabledCommands` setting gains it. */\n disableCommand(id: CommandId): void;\n /** Turn a command on again; it stays off while one of its categories is. */\n enableCommand(id: CommandId): void;\n /** Replace the commands that are off one by one. */\n setDisabledCommands(ids: readonly CommandId[]): void;\n\n // ── events ──\n /** A command ran. */\n readonly onExecuted: EventHook<CommandExecutedEvent>;\n /** A command's `run` threw; `execute` rejects with the same error. */\n readonly onExecutionFailed: EventHook<CommandExecutionFailedEvent>;\n}\n"],"mappings":";;;;;AAMA,MAAa,gBAAgB,sBAA0C,YAAY,EACjF,MAAM,6EACR,CAAC;;;;;;;AC0LD,MAAa,yBACX,MACA,UACY;CACZ,IAAI,SAAS,OAAO,OAAO;CAC3B,IAAI,CAAC,QAAQ,CAAC,OAAO,OAAO;CAC5B,OACE,KAAK,OAAO,MAAM,MAClB,KAAK,UAAU,MAAM,SACrB,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,YAAY,MAAM,YAAY,WAC/C,KAAK,YAAY,cAAc,MAAM,YAAY,aACjD,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,MAAM,WACvB,KAAK,WAAW,MAAM,UACtB,KAAK,YAAY,MAAM,WACvB,KAAK,mBAAmB,MAAM,kBAC9B,KAAK,UAAU,WAAW,MAAM,UAAU,UAC1C,KAAK,UAAU,OAAO,UAAU,UAAU,aAAa,MAAM,UAAU,MAAM;AAEjF;;;;;AAMA,MAAa,uBAAuB,QAAoC;CACtE;CACA,OAAO;CACP,WAAW,CAAC;CACZ,SAAS;CACT,QAAQ;CACR,SAAS;CACT,YAAY,CAAC;AACf;;AAGA,MAAa,yBAAyB,IAAe,UACnD,eAAe,GAAG,GAAG,WAAW,IAAI,KAAK,EAAE;;;;;;AAe7C,SAAgB,eACd,SACA,SACA,SACc;CACd,MAAM,CAAC,SAAS,QAAQ;CACxB,OAAO;EACL,GAAG;EACH,WAAW,QAAQ,QAAQ,EAAE;EAC7B,UAAU,UAAU,KAAA,IAAY,OAAO,eAAe,OAAO,EAAE,OAAO,QAAQ,MAAM,CAAC;CACvF;AACF;;AAgCA,MAAa,oBAAsC;CACjD,UAAU,CAAC;CACX,UAAU,KAAA;CACV,oBAAoB,CAAC;CACrB,kBAAkB,CAAC;CACnB,YAAY;AACd"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"contract-sqmSSPlP.cjs","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it to the host capability. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { CommandsCapability } from './contract';\n\nexport const CommandsToken = createCapabilityToken<CommandsCapability>('commands', {\n hint: `add commandsPlugin() from '@embedpdf/plugin-commands' to your plugins list`,\n});\n","/**\n * @embedpdf/plugin-commands/contract — the commands that toolbars, menus,\n * shortcuts and a command palette all show and run.\n *\n * A command's state is read from live state: `resolveCommand` asks the other\n * capabilities when it's called, so every reader follows the kernel's one\n * change stream, with no events. Definitions hold functions, so they live in\n * the settings and the plugin's registry, never in state.\n */\nimport type {\n CapabilityToken,\n DeepPartial,\n EventHook,\n OperationOptions,\n Permission,\n PluginErrorInfo,\n SettingLock,\n SettingsApi,\n Unsubscribe,\n} from '@embedpdf/core';\nimport { didYouMean, formatShortcut } from '@embedpdf/core-ui';\n\nexport { CommandsToken } from './token';\n\nexport type CommandId = string;\n\n/**\n * What a command's derivations and `run` see: capabilities resolved for the command's document\n * (the one named, else the document in scope, else the active one), and your app's state.\n */\nexport interface CommandContext<AppState = any> {\n /** The command's document, or `null` when none is open. */\n readonly documentId: string | null;\n /** Your app's state, as the `appState` setting has it now: `any` until you give its type. */\n readonly appState: AppState;\n /** What the caller passed: `execute(id, { args })`. */\n readonly args?: unknown;\n /** Fires when the caller cancels `execute()`: pass it on to the calls `run` makes. */\n readonly signal?: AbortSignal;\n /** A capability, for the command's document when the plugin is document-scoped. Throws when it isn't available. */\n get<T>(token: CapabilityToken<T>): T;\n /** Like `get`, but `null` when the capability isn't available (no plugin, no document). */\n tryGet<T>(token: CapabilityToken<T>): T | null;\n}\n\n/**\n * Up to two colors that go with a command's icon, such as a tool's current color: data a\n * renderer may use (tint the icon, show a swatch), like `icon` itself.\n */\nexport interface IconAccent {\n /** The mark: a stroke, the markup or the text color. */\n readonly primary?: string;\n /** The fill, when there is one. */\n readonly secondary?: string;\n}\n\n/**\n * One command, as you define it. Its functions get your app's state as `AppState`; they're\n * methods, so a command typed for your state (`CommandDef<Review>`) goes wherever a command does.\n */\nexport interface CommandDef<AppState = any> {\n /** A unique name, by convention `area:action`: `'zoom:in'`, `'review:approve'`. */\n readonly id: string;\n /** What the user sees. With `labelKey` too, it's what shows when no language has the key. */\n readonly label?: string;\n /**\n * A translation key for the label, read through the i18n plugin. Without the plugin, or a\n * string for the key, the command shows `label`, else the key.\n */\n readonly labelKey?: string;\n /** Your icon's name; your buttons turn it into an icon. */\n readonly icon?: string;\n /** Colors for the icon, read from live state like `active`. */\n iconAccent?(context: CommandContext<AppState>): IconAccent | null;\n /** A key such as `'Mod+K'` (`Mod` is Cmd on a Mac, Ctrl elsewhere), or a list of them. */\n readonly shortcut?: string | readonly string[];\n /**\n * Whether its shortcut also runs while the cursor is in a text field where the shortcuts\n * listen (a search box, a comment), as the viewer's Find does. Default false: a key typed in\n * a field is the field's.\n */\n readonly shortcutInTextFields?: boolean;\n /**\n * The features it belongs to, so turning one off turns it off: `['annotations.highlight']`.\n * Turning off a feature turns off every feature under it, on whole dotted parts: `annotations`\n * covers `annotations.highlight`, not `annotationsExtra`.\n */\n readonly categories?: readonly string[];\n /**\n * The scope permissions it needs, such as `'doc.annotate.modify'`, checked against its\n * document. Without them it's hidden, or shown disabled with its reason under the\n * `notAllowed: 'disable'` setting. With no document open there is nothing to check.\n */\n readonly requires?: readonly Permission[];\n /**\n * Whether the session may run it, from the plugins' `can*` checks\n * (`documents.canPrint()`), for a command whose permission is a plugin's to know. When it\n * says no, the command isn't allowed, as with `requires`. Asked only while a document is\n * open; one that throws allows it.\n */\n allowed?(context: CommandContext<AppState>): boolean;\n /**\n * The translation key of the sentence that says why `allowed` refused it, with `{label}` for\n * its label: `'commands.notAllowed.doc-print'`. Without it, or a string for it,\n * `commands.notAllowed.default`.\n */\n readonly notAllowedKey?: string;\n /**\n * The lock on the setting it changes, for a command that changes one\n * (`(context) => context.get(StageToken).getLock('spread')`), or `null`.\n * While a lock holds, it shows disabled, whatever the `notAllowed` setting\n * says, with the sentence under the lock's `reasonKey` (else\n * `commands.locked.default`) as its `disabledReason`; it stays `active` for\n * its own value. One that throws counts as unlocked.\n */\n locked?(context: CommandContext<AppState>): SettingLock | null;\n\n // ── what the command opens ───────────────────────────────────────────────\n // A command that opens a panel, menu or dialog says so instead of opening\n // it in `run`: it then needs no `run`, it shows as active while the surface\n // is open, and a button can show that it opens a menu.\n /** Opens and closes a menu of yours, by its id. */\n readonly menu?: string;\n /**\n * Opens and closes a panel, closing the others with the same `exclusive` tag. With `focus`,\n * opening it asks for the cursor (the shell's `open(id, { focus: true })`).\n */\n readonly panel?:\n | string\n | { readonly id: string; readonly exclusive?: string; readonly focus?: boolean };\n /** Opens and closes a dialog; one dialog is open at a time. */\n readonly modal?: string;\n\n // ── read from live state and your app's, again whenever either changes ──\n /** When it can run. Default: always. One that throws counts as false. */\n enabled?(context: CommandContext<AppState>): boolean;\n /** When it shows as pressed, such as the current tool. One that throws counts as false. */\n active?(context: CommandContext<AppState>): boolean;\n /** When it shows at all. Default: always. One that throws counts as false. */\n visible?(context: CommandContext<AppState>): boolean;\n\n /** What it does; `execute()` resolves once it has. Not needed for a `menu`, `panel` or `modal`. */\n run?(context: CommandContext<AppState>): void | Promise<unknown>;\n}\n\n/**\n * A command for each of a set of names, made from one definition, such as `tool:<id>` for every\n * tool a document has. Its commands resolve and run like any other, and `listCommands()` lists\n * one per name. A command defined with the same id wins over the family's.\n */\nexport interface CommandFamily {\n /** Where the commands' ids start: `'tool:'` makes `tool:highlight`. */\n readonly prefix: string;\n /** The names the command's document has, in order. Return the same array while nothing changed. */\n readonly names: (context: CommandContext) => readonly string[];\n /** The command for one name. A family's commands have no shortcuts. */\n readonly command: (name: string) => Omit<CommandDef, 'id' | 'shortcut'>;\n}\n\n/** A command as a button shows it: everything read for its document. */\nexport interface ResolvedCommand {\n readonly id: string;\n readonly label: string;\n readonly icon?: string;\n readonly iconAccent?: IconAccent;\n readonly shortcuts: readonly string[];\n readonly menu?: string;\n readonly enabled: boolean;\n readonly active: boolean;\n readonly visible: boolean;\n readonly categories: readonly string[];\n /**\n * Why it's disabled, as a sentence for its tooltip: set when the scope doesn't allow it and\n * the `notAllowed` setting is `'disable'`, or when a lock holds the setting it changes.\n */\n readonly disabledReason?: string;\n}\n\n/**\n * Why a command won't run whatever the moment: it's turned off in this viewer\n * (`disabledCategories`, `disabledCommands`), the scope doesn't allow it (`requires`), or a lock\n * holds the setting it changes (`locked`). A command that only can't run right now (`enabled`,\n * `visible`) has no refusal.\n */\nexport interface CommandRefusal {\n readonly reason: 'turned-off' | 'not-allowed' | 'locked';\n /** A sentence for the user, translated through the i18n plugin when it's there. */\n readonly message: string;\n}\n\n/**\n * Whether two resolved commands show the same, for readers that compare what a command looks\n * like rather than which object holds it (a group of commands, or one command for two documents).\n */\nexport const resolvedCommandsEqual = (\n left: ResolvedCommand | null,\n right: ResolvedCommand | null,\n): boolean => {\n if (left === right) return true;\n if (!left || !right) return false;\n return (\n left.id === right.id &&\n left.label === right.label &&\n left.icon === right.icon &&\n left.iconAccent?.primary === right.iconAccent?.primary &&\n left.iconAccent?.secondary === right.iconAccent?.secondary &&\n left.menu === right.menu &&\n left.enabled === right.enabled &&\n left.active === right.active &&\n left.visible === right.visible &&\n left.disabledReason === right.disabledReason &&\n left.shortcuts.length === right.shortcuts.length &&\n left.shortcuts.every((shortcut, index) => shortcut === right.shortcuts[index])\n );\n};\n\n/**\n * What a component or a toolbar draws for a command id no plugin registered: labelled with its\n * id, neither enabled nor visible, the way a turned-off command is.\n */\nexport const unregisteredCommand = (id: CommandId): ResolvedCommand => ({\n id,\n label: id,\n shortcuts: [],\n enabled: false,\n active: false,\n visible: false,\n categories: [],\n});\n\n/** What a component that asks for an id no plugin registered hears, in development. */\nexport const unknownCommandWarning = (id: CommandId, known: Iterable<CommandId>): string =>\n `no command \"${id}\"${didYouMean(id, known)}: it shows as neither visible nor enabled`;\n\n/** A command with everything a button needs: what it shows, `run`, and its shortcut for a tooltip. */\nexport interface BoundCommand extends ResolvedCommand {\n /** Run the command for the document it was read for. */\n readonly run: () => Promise<ExecuteResult>;\n /** Its first shortcut, formatted for the platform (`'⌘K'` on a Mac, `'Ctrl+K'` elsewhere), or `null`. */\n readonly shortcut: string | null;\n}\n\n/**\n * A resolved command, bound for a button: `run` executes it through `execute`, and `shortcut` is\n * its first shortcut formatted for the platform. Which platform is the caller's to know\n * (`isMacPlatform()` in `@embedpdf/web`).\n */\nexport function boundCommandOf(\n command: ResolvedCommand,\n execute: (id: CommandId) => Promise<ExecuteResult>,\n options: { readonly isMac: boolean },\n): BoundCommand {\n const [first] = command.shortcuts;\n return {\n ...command,\n run: () => execute(command.id),\n shortcut: first === undefined ? null : formatShortcut(first, { isMac: options.isMac }),\n };\n}\n\n/**\n * The commands plugin's settings. `commandsPlugin(config)` registers them over\n * {@link COMMANDS_DEFAULTS}, and `updateSettings()` changes them while the app runs.\n */\nexport interface CommandsSettings {\n /** The commands your viewer has. A later definition with an id that's taken replaces the earlier one. */\n readonly commands: readonly (CommandDef | CommandFamily)[];\n /**\n * Your app's state, which every command's functions get as `appState`: values, and functions\n * that change them. A new value replaces the old one whole, and every command is asked again.\n */\n readonly appState: unknown;\n /**\n * Categories turned off, with every category under them: their commands are hidden and\n * refused wherever they appear.\n */\n readonly disabledCategories: readonly string[];\n /** Commands turned off one by one, by id: hidden and refused wherever they appear. */\n readonly disabledCommands: readonly CommandId[];\n /**\n * What a command the scope doesn't allow does: `'hide'` leaves it out, `'disable'` shows it\n * disabled, with the reason in its `disabledReason`.\n */\n readonly notAllowed: NotAllowedMode;\n}\n\n/** How a command shows when the scope doesn't allow it: hidden, or disabled with its reason. */\nexport type NotAllowedMode = 'hide' | 'disable';\n\n/** What the commands settings are when the app registers none. */\nexport const COMMANDS_DEFAULTS: CommandsSettings = {\n commands: [],\n appState: undefined,\n disabledCategories: [],\n disabledCommands: [],\n notAllowed: 'hide',\n};\n\n/** What `commandsPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type CommandsConfig<AppState = any> = Omit<\n DeepPartial<CommandsSettings>,\n 'commands' | 'appState'\n> & {\n readonly commands?: readonly (CommandDef<AppState> | CommandFamily)[];\n readonly appState?: AppState;\n};\n\nexport interface RegisterCommandOptions {\n /** Replace a command with the same id; without it, a taken id throws `conflict`. */\n replace?: boolean;\n}\n\nexport interface ExecuteOptions extends OperationOptions {\n /** The document to run it for; the document in scope, else the active one, when left out. */\n documentId?: string;\n /** Passed to the command's `run` and derivations as `args`. */\n args?: unknown;\n}\n\n/** How `execute()` went: it ran, or it was refused before running, and why. */\nexport type ExecuteResult =\n | { readonly status: 'executed' }\n | { readonly status: 'rejected'; readonly reason: 'not-found' | 'disabled' | 'hidden' };\n\n// ── events ──\nexport interface CommandExecutedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly args: unknown;\n}\nexport interface CommandExecutionFailedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly error: PluginErrorInfo;\n}\n\n/**\n * The commands. A call that leaves out the document is for the document in scope when the\n * capability was resolved for one (`ctx.forDocument`, a `<DocumentScope>`), and for the active\n * document otherwise.\n */\nexport interface CommandsCapability extends SettingsApi<CommandsSettings> {\n // ── the commands ──\n /**\n * Add a command while the app runs, and get a function that removes it. A taken id throws\n * `conflict` unless `replace`.\n */\n registerCommand(definition: CommandDef, options?: RegisterCommandOptions): Unsubscribe;\n /** `registerCommand` for several definitions; the function removes all of them. */\n registerCommands(\n definitions: readonly CommandDef[],\n options?: RegisterCommandOptions,\n ): Unsubscribe;\n /** Whether a command has this id; with a family, every id that starts with its prefix does. */\n hasCommand(id: CommandId): boolean;\n /** A command as you defined it, or `null`. */\n getCommand(id: CommandId): CommandDef | null;\n /** Every command's id for the active document, in the order they were added. The same array until one changes. */\n listCommandIds(): readonly CommandId[];\n\n // ── what a button shows ──\n /** A command as a button shows it, or `null` for an unknown id. The same object while nothing about it changed. */\n resolveCommand(id: CommandId, documentId?: string): ResolvedCommand | null;\n /** Every command, resolved, in the order they were added. The same array while nothing changed. */\n listCommands(documentId?: string): readonly ResolvedCommand[];\n /** The visible commands whose label or id contains the query, for a command palette. */\n searchCommands(query: string, documentId?: string): readonly ResolvedCommand[];\n /** Every shortcut with its command, for a keyboard help sheet. The same array until the commands change. */\n listShortcuts(): readonly { readonly commandId: CommandId; readonly shortcut: string }[];\n\n // ── running them ──\n /**\n * Run a command; resolves once its `run` has, with `{ status: 'executed' }` and\n * `onExecuted`, or `{ status: 'rejected', reason }` for a command that is unknown, hidden or\n * disabled (a command turned off is hidden). A `run` that throws fires `onExecutionFailed` and rejects with its `PluginError`;\n * the signal rejects `operation-cancelled`.\n */\n execute(id: CommandId, options?: ExecuteOptions): Promise<ExecuteResult>;\n /** Whether a command can run now: it exists, and is enabled and visible. */\n canExecute(id: CommandId, documentId?: string): boolean;\n /**\n * Why a command won't run whatever the moment: it's turned off, or not allowed for its\n * document. `null` when it may run (or only can't right now), and for an unknown id.\n */\n getRefusal(id: CommandId, documentId?: string): CommandRefusal | null;\n\n // ── turning commands off ──\n /** The categories turned off. */\n getDisabledCategories(): readonly string[];\n /** Whether a category is turned off: it, or a category it's under (`annotations` for `annotations.highlight`). */\n isCategoryDisabled(category: string): boolean;\n /** Turn a category off, with every category under it: the `disabledCategories` setting gains it. */\n disableCategory(category: string): void;\n /** Turn a category on again. */\n enableCategory(category: string): void;\n /** Replace the categories that are off. */\n setDisabledCategories(categories: readonly string[]): void;\n /** The commands turned off one by one. */\n getDisabledCommands(): readonly CommandId[];\n /** Whether a command is turned off: by its id, or through one of its categories. */\n isCommandDisabled(id: CommandId): boolean;\n /** Turn one command off: the `disabledCommands` setting gains it. */\n disableCommand(id: CommandId): void;\n /** Turn a command on again; it stays off while one of its categories is. */\n enableCommand(id: CommandId): void;\n /** Replace the commands that are off one by one. */\n setDisabledCommands(ids: readonly CommandId[]): void;\n\n // ── events ──\n /** A command ran. */\n readonly onExecuted: EventHook<CommandExecutedEvent>;\n /** A command's `run` threw; `execute` rejects with the same error. */\n readonly onExecutionFailed: EventHook<CommandExecutionFailedEvent>;\n}\n"],"mappings":";;;;;AAMA,MAAa,iBAAA,GAAA,eAAA,sBAAA,CAA0D,YAAY,EACjF,MAAM,6EACR,CAAC;;;;;;;AC0LD,MAAa,yBACX,MACA,UACY;CACZ,IAAI,SAAS,OAAO,OAAO;CAC3B,IAAI,CAAC,QAAQ,CAAC,OAAO,OAAO;CAC5B,OACE,KAAK,OAAO,MAAM,MAClB,KAAK,UAAU,MAAM,SACrB,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,YAAY,MAAM,YAAY,WAC/C,KAAK,YAAY,cAAc,MAAM,YAAY,aACjD,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,MAAM,WACvB,KAAK,WAAW,MAAM,UACtB,KAAK,YAAY,MAAM,WACvB,KAAK,mBAAmB,MAAM,kBAC9B,KAAK,UAAU,WAAW,MAAM,UAAU,UAC1C,KAAK,UAAU,OAAO,UAAU,UAAU,aAAa,MAAM,UAAU,MAAM;AAEjF;;;;;AAMA,MAAa,uBAAuB,QAAoC;CACtE;CACA,OAAO;CACP,WAAW,CAAC;CACZ,SAAS;CACT,QAAQ;CACR,SAAS;CACT,YAAY,CAAC;AACf;;AAGA,MAAa,yBAAyB,IAAe,UACnD,eAAe,GAAG,IAAA,GAAA,kBAAA,WAAA,CAAc,IAAI,KAAK,EAAE;;;;;;AAe7C,SAAgB,eACd,SACA,SACA,SACc;CACd,MAAM,CAAC,SAAS,QAAQ;CACxB,OAAO;EACL,GAAG;EACH,WAAW,QAAQ,QAAQ,EAAE;EAC7B,UAAU,UAAU,KAAA,IAAY,QAAA,GAAA,kBAAA,eAAA,CAAsB,OAAO,EAAE,OAAO,QAAQ,MAAM,CAAC;CACvF;AACF;;AAgCA,MAAa,oBAAsC;CACjD,UAAU,CAAC;CACX,UAAU,KAAA;CACV,oBAAoB,CAAC;CACrB,kBAAkB,CAAC;CACnB,YAAY;AACd"}
|