@embedpdf/plugin-commands 3.0.0-next.21 → 3.0.0-next.22
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.map +1 -1
- package/dist/contract/host.d.cts +1 -1
- package/dist/contract/host.d.ts +1 -1
- package/dist/contract/host.js.map +1 -1
- package/dist/{host-contract-Cekzl4U8.d.ts → host-contract-B58WiZ-H.d.ts} +5 -4
- package/dist/{host-contract-DmzPrsSX.d.cts → host-contract-Db4TZ_JI.d.cts} +5 -4
- package/dist/index.cjs +15 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +15 -6
- package/dist/index.js.map +1 -1
- package/dist/standard.cjs +59 -7
- package/dist/standard.cjs.map +1 -1
- package/dist/standard.d.cts +8 -2
- package/dist/standard.d.ts +8 -2
- package/dist/standard.js +59 -7
- package/dist/standard.js.map +1 -1
- package/package.json +10 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.cjs","names":["PublicCommandsToken"],"sources":["../../src/host-contract.ts"],"sourcesContent":["/**\n * @embedpdf/plugin-commands/contract/host — the host lens: the keystroke\n * matcher and the menu a command opens, for the toolbar's \"More\" menu. The\n * same runtime token as the public contract, typed wider.\n */\nimport { createHostToken } from '@embedpdf/core';\nimport type { KeyStroke } from '@embedpdf/core-ui';\n\nimport type { CommandId, CommandRefusal, CommandsCapability } from './contract';\nimport { CommandsToken as PublicCommandsToken } from './token';\n\nexport * from './contract';\n\n/** The command a keystroke's shortcut names, and why it won't run when it's refused. */\nexport interface ShortcutMatch {\n readonly commandId: CommandId;\n /** Set when the command is turned off or not allowed; `null` when it may run (or just can't right now). */\n readonly refusal: CommandRefusal | null;\n}\n\nexport interface CommandsHostCapability extends CommandsCapability {\n /**\n * The command whose shortcut a keystroke matches, for the active document, or `null`. Of\n * several with the same keys, one that isn't refused
|
|
1
|
+
{"version":3,"file":"host.cjs","names":["PublicCommandsToken"],"sources":["../../src/host-contract.ts"],"sourcesContent":["/**\n * @embedpdf/plugin-commands/contract/host — the host lens: the keystroke\n * matcher and the menu a command opens, for the toolbar's \"More\" menu. The\n * same runtime token as the public contract, typed wider.\n */\nimport { createHostToken } from '@embedpdf/core';\nimport type { KeyStroke } from '@embedpdf/core-ui';\n\nimport type { CommandId, CommandRefusal, CommandsCapability } from './contract';\nimport { CommandsToken as PublicCommandsToken } from './token';\n\nexport * from './contract';\n\n/** The command a keystroke's shortcut names, and why it won't run when it's refused. */\nexport interface ShortcutMatch {\n readonly commandId: CommandId;\n /** Set when the command is turned off or not allowed; `null` when it may run (or just can't right now). */\n readonly refusal: CommandRefusal | null;\n}\n\nexport interface CommandsHostCapability extends CommandsCapability {\n /**\n * The command whose shortcut a keystroke matches, for the active document, or `null`. Of\n * several with the same keys, one that can run now wins, then one that isn't refused (it only\n * can't run right now); a refused one counts only while its `visible` says it would show. With\n * `inTextField` (the key was typed in one), only a command whose `shortcutInTextFields` says so\n * matches.\n */\n matchStroke(\n stroke: KeyStroke,\n options: { isMac: boolean; inTextField?: boolean },\n ): ShortcutMatch | null;\n /** The menu a command opens, for the \"More\" menu's nested menus; `null` for an unknown id. */\n getMenuTarget(id: CommandId): { menu?: string } | null;\n}\n\nexport const CommandsToken = createHostToken<CommandsHostCapability>(PublicCommandsToken);\n"],"mappings":";;;;;;;;AAoCA,MAAa,iBAAA,2BAAA,CAAA,CAAA,gBAAA,CAAwDA,iBAAAA,aAAmB"}
|
package/dist/contract/host.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { S as unregisteredCommand, _ as RegisterCommandOptions, a as CommandExecutedEvent, b as resolvedCommandsEqual, c as CommandId, d as CommandsConfig, f as CommandsSettings, g as NotAllowedMode, h as IconAccent, i as CommandDef, l as CommandRefusal, m as ExecuteResult, n as COMMANDS_DEFAULTS, o as CommandExecutionFailedEvent, p as ExecuteOptions, r as CommandContext, s as CommandFamily, t as BoundCommand, u as CommandsCapability, v as ResolvedCommand, x as unknownCommandWarning, y as boundCommandOf } from "../contract-lGfvyWMG.cjs";
|
|
2
|
-
import { n as CommandsToken, r as ShortcutMatch, t as CommandsHostCapability } from "../host-contract-
|
|
2
|
+
import { n as CommandsToken, r as ShortcutMatch, t as CommandsHostCapability } from "../host-contract-Db4TZ_JI.cjs";
|
|
3
3
|
export { BoundCommand, COMMANDS_DEFAULTS, CommandContext, CommandDef, CommandExecutedEvent, CommandExecutionFailedEvent, CommandFamily, CommandId, CommandRefusal, CommandsCapability, CommandsConfig, CommandsHostCapability, CommandsSettings, CommandsToken, ExecuteOptions, ExecuteResult, IconAccent, NotAllowedMode, RegisterCommandOptions, ResolvedCommand, ShortcutMatch, boundCommandOf, resolvedCommandsEqual, unknownCommandWarning, unregisteredCommand };
|
package/dist/contract/host.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { S as unregisteredCommand, _ as RegisterCommandOptions, a as CommandExecutedEvent, b as resolvedCommandsEqual, c as CommandId, d as CommandsConfig, f as CommandsSettings, g as NotAllowedMode, h as IconAccent, i as CommandDef, l as CommandRefusal, m as ExecuteResult, n as COMMANDS_DEFAULTS, o as CommandExecutionFailedEvent, p as ExecuteOptions, r as CommandContext, s as CommandFamily, t as BoundCommand, u as CommandsCapability, v as ResolvedCommand, x as unknownCommandWarning, y as boundCommandOf } from "../contract-lGfvyWMG.js";
|
|
2
|
-
import { n as CommandsToken, r as ShortcutMatch, t as CommandsHostCapability } from "../host-contract-
|
|
2
|
+
import { n as CommandsToken, r as ShortcutMatch, t as CommandsHostCapability } from "../host-contract-B58WiZ-H.js";
|
|
3
3
|
export { BoundCommand, COMMANDS_DEFAULTS, CommandContext, CommandDef, CommandExecutedEvent, CommandExecutionFailedEvent, CommandFamily, CommandId, CommandRefusal, CommandsCapability, CommandsConfig, CommandsHostCapability, CommandsSettings, CommandsToken, ExecuteOptions, ExecuteResult, IconAccent, NotAllowedMode, RegisterCommandOptions, ResolvedCommand, ShortcutMatch, boundCommandOf, resolvedCommandsEqual, unknownCommandWarning, unregisteredCommand };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.js","names":["PublicCommandsToken"],"sources":["../../src/host-contract.ts"],"sourcesContent":["/**\n * @embedpdf/plugin-commands/contract/host — the host lens: the keystroke\n * matcher and the menu a command opens, for the toolbar's \"More\" menu. The\n * same runtime token as the public contract, typed wider.\n */\nimport { createHostToken } from '@embedpdf/core';\nimport type { KeyStroke } from '@embedpdf/core-ui';\n\nimport type { CommandId, CommandRefusal, CommandsCapability } from './contract';\nimport { CommandsToken as PublicCommandsToken } from './token';\n\nexport * from './contract';\n\n/** The command a keystroke's shortcut names, and why it won't run when it's refused. */\nexport interface ShortcutMatch {\n readonly commandId: CommandId;\n /** Set when the command is turned off or not allowed; `null` when it may run (or just can't right now). */\n readonly refusal: CommandRefusal | null;\n}\n\nexport interface CommandsHostCapability extends CommandsCapability {\n /**\n * The command whose shortcut a keystroke matches, for the active document, or `null`. Of\n * several with the same keys, one that isn't refused
|
|
1
|
+
{"version":3,"file":"host.js","names":["PublicCommandsToken"],"sources":["../../src/host-contract.ts"],"sourcesContent":["/**\n * @embedpdf/plugin-commands/contract/host — the host lens: the keystroke\n * matcher and the menu a command opens, for the toolbar's \"More\" menu. The\n * same runtime token as the public contract, typed wider.\n */\nimport { createHostToken } from '@embedpdf/core';\nimport type { KeyStroke } from '@embedpdf/core-ui';\n\nimport type { CommandId, CommandRefusal, CommandsCapability } from './contract';\nimport { CommandsToken as PublicCommandsToken } from './token';\n\nexport * from './contract';\n\n/** The command a keystroke's shortcut names, and why it won't run when it's refused. */\nexport interface ShortcutMatch {\n readonly commandId: CommandId;\n /** Set when the command is turned off or not allowed; `null` when it may run (or just can't right now). */\n readonly refusal: CommandRefusal | null;\n}\n\nexport interface CommandsHostCapability extends CommandsCapability {\n /**\n * The command whose shortcut a keystroke matches, for the active document, or `null`. Of\n * several with the same keys, one that can run now wins, then one that isn't refused (it only\n * can't run right now); a refused one counts only while its `visible` says it would show. With\n * `inTextField` (the key was typed in one), only a command whose `shortcutInTextFields` says so\n * matches.\n */\n matchStroke(\n stroke: KeyStroke,\n options: { isMac: boolean; inTextField?: boolean },\n ): ShortcutMatch | null;\n /** The menu a command opens, for the \"More\" menu's nested menus; `null` for an unknown id. */\n getMenuTarget(id: CommandId): { menu?: string } | null;\n}\n\nexport const CommandsToken = createHostToken<CommandsHostCapability>(PublicCommandsToken);\n"],"mappings":";;;;;;;;AAoCA,MAAa,gBAAgB,gBAAwCA,eAAmB"}
|
|
@@ -10,9 +10,10 @@ interface ShortcutMatch {
|
|
|
10
10
|
interface CommandsHostCapability extends CommandsCapability {
|
|
11
11
|
/**
|
|
12
12
|
* The command whose shortcut a keystroke matches, for the active document, or `null`. Of
|
|
13
|
-
* several with the same keys, one that
|
|
14
|
-
* its `visible` says it would show. With
|
|
15
|
-
* command whose `shortcutInTextFields` says so
|
|
13
|
+
* several with the same keys, one that can run now wins, then one that isn't refused (it only
|
|
14
|
+
* can't run right now); a refused one counts only while its `visible` says it would show. With
|
|
15
|
+
* `inTextField` (the key was typed in one), only a command whose `shortcutInTextFields` says so
|
|
16
|
+
* matches.
|
|
16
17
|
*/
|
|
17
18
|
matchStroke(stroke: KeyStroke, options: {
|
|
18
19
|
isMac: boolean;
|
|
@@ -26,4 +27,4 @@ interface CommandsHostCapability extends CommandsCapability {
|
|
|
26
27
|
declare const CommandsToken: import("@embedpdf/core").CapabilityToken<CommandsHostCapability>;
|
|
27
28
|
//#endregion
|
|
28
29
|
export { CommandsToken as n, ShortcutMatch as r, CommandsHostCapability as t };
|
|
29
|
-
//# sourceMappingURL=host-contract-
|
|
30
|
+
//# sourceMappingURL=host-contract-B58WiZ-H.d.ts.map
|
|
@@ -10,9 +10,10 @@ interface ShortcutMatch {
|
|
|
10
10
|
interface CommandsHostCapability extends CommandsCapability {
|
|
11
11
|
/**
|
|
12
12
|
* The command whose shortcut a keystroke matches, for the active document, or `null`. Of
|
|
13
|
-
* several with the same keys, one that
|
|
14
|
-
* its `visible` says it would show. With
|
|
15
|
-
* command whose `shortcutInTextFields` says so
|
|
13
|
+
* several with the same keys, one that can run now wins, then one that isn't refused (it only
|
|
14
|
+
* can't run right now); a refused one counts only while its `visible` says it would show. With
|
|
15
|
+
* `inTextField` (the key was typed in one), only a command whose `shortcutInTextFields` says so
|
|
16
|
+
* matches.
|
|
16
17
|
*/
|
|
17
18
|
matchStroke(stroke: KeyStroke, options: {
|
|
18
19
|
isMac: boolean;
|
|
@@ -26,4 +27,4 @@ interface CommandsHostCapability extends CommandsCapability {
|
|
|
26
27
|
declare const CommandsToken: import("@embedpdf/core").CapabilityToken<CommandsHostCapability>;
|
|
27
28
|
//#endregion
|
|
28
29
|
export { CommandsToken as n, ShortcutMatch as r, CommandsHostCapability as t };
|
|
29
|
-
//# sourceMappingURL=host-contract-
|
|
30
|
+
//# sourceMappingURL=host-contract-Db4TZ_JI.d.cts.map
|
package/dist/index.cjs
CHANGED
|
@@ -487,23 +487,32 @@ function createCommandsController(ctx) {
|
|
|
487
487
|
onExecuted: executed.on,
|
|
488
488
|
onExecutionFailed: executionFailed.on,
|
|
489
489
|
matchStroke: (stroke, options) => {
|
|
490
|
+
let waiting = null;
|
|
490
491
|
let refused = null;
|
|
491
492
|
for (const entry of definedCommands()) {
|
|
492
493
|
if (options.inTextField && !entry.definition.shortcutInTextFields) continue;
|
|
493
494
|
if (!entry.parsed.some((shortcut) => (0, _embedpdf_core_ui.matchShortcut)(shortcut, stroke, options))) continue;
|
|
494
495
|
const context = commandContext();
|
|
495
496
|
const refusal = refusalOf(entry.definition, context);
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
497
|
+
const visible = derive(entry.definition.visible, context, true);
|
|
498
|
+
if (!refusal) {
|
|
499
|
+
if (visible && derive(entry.definition.enabled, context, true)) return {
|
|
500
|
+
commandId: entry.definition.id,
|
|
501
|
+
refusal: null
|
|
502
|
+
};
|
|
503
|
+
waiting ?? (waiting = {
|
|
504
|
+
commandId: entry.definition.id,
|
|
505
|
+
refusal: null
|
|
506
|
+
});
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
if (!visible) continue;
|
|
501
510
|
refused ?? (refused = {
|
|
502
511
|
commandId: entry.definition.id,
|
|
503
512
|
refusal
|
|
504
513
|
});
|
|
505
514
|
}
|
|
506
|
-
return refused;
|
|
515
|
+
return waiting ?? refused;
|
|
507
516
|
},
|
|
508
517
|
getMenuTarget: (id) => {
|
|
509
518
|
const entry = entryOf(id);
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["parseShortcut","I18nToken","DocumentsToken","ShellToken","PluginError","CommandsToken","I18nToken","ShellToken","COMMANDS_DEFAULTS"],"sources":["../src/registry.ts","../src/services/availability.ts","../src/write/turning-off.ts","../src/controller.ts","../src/commands.plugin.ts"],"sourcesContent":["/** A command definition with its shortcuts parsed once, and how the registry tells a family apart. */\nimport { parseShortcut, type ParsedShortcut } from '@embedpdf/core-ui';\n\nimport type { CommandDef, CommandFamily } from './contract';\n\nexport interface RegisteredCommand {\n readonly definition: CommandDef;\n readonly shortcuts: readonly string[];\n readonly parsed: readonly ParsedShortcut[];\n}\n\nexport const registeredCommand = (definition: CommandDef): RegisteredCommand => {\n const shortcuts =\n definition.shortcut === undefined ? [] : ([] as string[]).concat(definition.shortcut);\n return { definition, shortcuts, parsed: shortcuts.map(parseShortcut) };\n};\n\nexport const isCommandFamily = (item: CommandDef | CommandFamily): item is CommandFamily =>\n 'prefix' in item;\n\n/** The commands the settings define, by id (a later id replaces an earlier one), and their families. */\nexport interface ConfiguredCommands {\n readonly commands: ReadonlyMap<string, RegisteredCommand>;\n readonly families: readonly CommandFamily[];\n}\n\nexport function configuredCommands(\n items: readonly (CommandDef | CommandFamily)[],\n): ConfiguredCommands {\n const commands = new Map<string, RegisteredCommand>();\n const families: CommandFamily[] = [];\n for (const item of items) {\n if (isCommandFamily(item)) families.push(item);\n else commands.set(item.id, registeredCommand(item));\n }\n return { commands, families };\n}\n","/**\n * Whether a command is there at all, apart from what it says about the\n * moment (`enabled`, `visible`): turned off in this viewer (its id, or one of\n * its categories), not allowed for its document (the scope's `requires`, or\n * the plugins' checks in `allowed`), or held by a lock on the setting it\n * changes (`locked`), and the sentence that says why, translated when the\n * i18n plugin is there.\n */\nimport type {\n DocumentHandle,\n Permission,\n PluginContext,\n SettingLock,\n Settings,\n} from '@embedpdf/core';\nimport { I18nToken } from '@embedpdf/plugin-i18n/contract';\n\nimport type { CommandContext, CommandDef, CommandRefusal, CommandsSettings } from '../contract';\n\n/**\n * Whether a category is off: it, or a category it's under, is in the list. Parts are whole\n * dotted segments, so `annotations` covers `annotations.highlight` and not `annotationsExtra`.\n */\nexport const isCategoryOff = (category: string, disabled: readonly string[]): boolean =>\n disabled.some((off) => category === off || category.startsWith(`${off}.`));\n\n/**\n * The label: a language's string under the command's id, else under its `labelKey` (the current\n * language, then the fallback one), else `label`, else the id. So a string for\n * `'document:download'` relabels that one command, whichever key its label is under.\n */\nexport const labelOf = (definition: CommandDef, context: CommandContext): string => {\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return definition.label ?? definition.labelKey ?? definition.id;\n const fallbackKey = definition.labelKey ? { fallbackKey: definition.labelKey } : {};\n // A command with a key and no label of its own warns once when no language has the key.\n return definition.label === undefined && definition.labelKey\n ? i18n.t(definition.id, fallbackKey)\n : i18n.t(definition.id, { ...fallbackKey, fallback: definition.label ?? definition.id });\n};\n\n/**\n * Whether a document's session holds a permission: what `ctx.allows` answers for a\n * document-scoped plugin, asked here of the command's document, since the commands are one\n * set for the whole workspace.\n */\nconst sessionHolds = (security: DocumentHandle['security'], permission: Permission): boolean =>\n permission === 'annotations:create'\n ? security.allowsAnnotation('create')\n : security.allows(permission);\n\n/** Where a language keeps the sentence for a permission: `commands.notAllowed.doc-text-copy`. */\nconst permissionKeyOf = (permission: Permission): string =>\n `commands.notAllowed.${permission.replace(/[.:]/g, '-')}`;\n\n/** The general sentence's key: `{label} isn't allowed`. */\nconst DEFAULT_NOT_ALLOWED_KEY = 'commands.notAllowed.default';\n\n/** The sentence for a command the session may not run, under `key`, else the general one. */\nexport const notAllowedMessage = (key: string, label: string, context: CommandContext): string => {\n const fallback = `${label} isn't allowed`;\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return fallback;\n const params = { label };\n return i18n.t(key, {\n params,\n fallback: i18n.t(DEFAULT_NOT_ALLOWED_KEY, { params, fallback }),\n });\n};\n\n/** The general locked sentence's key: `{label} can't be changed in this document`. */\nconst DEFAULT_LOCKED_KEY = 'commands.locked.default';\n\n/** The sentence for a command whose setting a lock holds: its `reasonKey`, else the general one. */\nexport const lockedMessage = (\n lock: SettingLock,\n label: string,\n context: CommandContext,\n): string => {\n const fallback = `${label} can't be changed in this document`;\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return fallback;\n const params = { label };\n const general = i18n.t(DEFAULT_LOCKED_KEY, { params, fallback });\n return lock.reasonKey === undefined\n ? general\n : i18n.t(lock.reasonKey, { params, fallback: general });\n};\n\n/** The sentence for a command that's turned off. */\nconst turnedOffMessage = (label: string, context: CommandContext): string => {\n const i18n = context.tryGet(I18nToken);\n return i18n\n ? i18n.t('commands.turnedOff', { params: { label }, fallback: \"{label} isn't available\" })\n : `${label} isn't available`;\n};\n\nexport function createAvailability(\n ctx: PluginContext<void, CommandsSettings>,\n settings: Settings<CommandsSettings>,\n) {\n /** Whether a command is turned off: by its id, or through one of its categories. */\n const isTurnedOff = (definition: CommandDef): boolean => {\n const { disabledCategories, disabledCommands } = settings.get();\n return (\n disabledCommands.includes(definition.id) ||\n (definition.categories ?? []).some((category) => isCategoryOff(category, disabledCategories))\n );\n };\n\n /** Whether a command's `allowed` check says yes; one that throws allows it. */\n const passesCheck = (definition: CommandDef, context: CommandContext): boolean => {\n if (!definition.allowed) return true;\n try {\n return definition.allowed(context);\n } catch {\n return true;\n }\n };\n\n /** The lock on the setting a command changes, or `null`; a `locked` that throws is no lock. */\n const lockOf = (definition: CommandDef, context: CommandContext): SettingLock | null => {\n if (!definition.locked) return null;\n try {\n return definition.locked(context);\n } catch {\n return null;\n }\n };\n\n /**\n * Why its document's session may not run a command, as the key of the sentence that says\n * so, or `null` when it may: the first permission `requires` names that the session doesn't\n * hold (`commands.notAllowed.doc-print`), else its `allowed` check saying no (its\n * `notAllowedKey`). With no document open there is no session to ask, and nothing is refused.\n */\n const notAllowedKeyOf = (definition: CommandDef, context: CommandContext): string | null => {\n if (!definition.requires?.length && !definition.allowed) return null;\n const handle = context.documentId === null ? null : ctx.documentHandle(context.documentId);\n if (!handle) return null;\n const missing = definition.requires?.find(\n (permission) => !sessionHolds(handle.security, permission),\n );\n if (missing !== undefined) return permissionKeyOf(missing);\n return passesCheck(definition, context)\n ? null\n : (definition.notAllowedKey ?? DEFAULT_NOT_ALLOWED_KEY);\n };\n\n /** Why a command won't run whatever the moment, or `null` when it may run. */\n const refusalOf = (definition: CommandDef, context: CommandContext): CommandRefusal | null => {\n if (isTurnedOff(definition)) {\n return {\n reason: 'turned-off',\n message: turnedOffMessage(labelOf(definition, context), context),\n };\n }\n const notAllowed = notAllowedKeyOf(definition, context);\n if (notAllowed !== null) {\n return {\n reason: 'not-allowed',\n message: notAllowedMessage(notAllowed, labelOf(definition, context), context),\n };\n }\n const lock = lockOf(definition, context);\n return lock === null\n ? null\n : { reason: 'locked', message: lockedMessage(lock, labelOf(definition, context), context) };\n };\n\n return { isTurnedOff, notAllowedKeyOf, lockOf, refusalOf };\n}\n","/**\n * Turning commands off and on: by category, with every category under it, and\n * one by one. Both lists are settings, so they change live and\n * `resetSettings()` restores what the app registered.\n */\nimport type { Settings } from '@embedpdf/core';\n\nimport type { CommandDef, CommandsCapability, CommandsSettings } from '../contract';\nimport { isCategoryOff } from '../services/availability';\n\ntype OffList = 'disabledCategories' | 'disabledCommands';\n\nexport function createTurningOff(\n settings: Settings<CommandsSettings>,\n definitionOf: (id: string) => CommandDef | null,\n isTurnedOff: (definition: CommandDef) => boolean,\n) {\n const listOf = (list: OffList): readonly string[] => settings.get()[list];\n const replace = (list: OffList, names: readonly string[]): void =>\n settings.api.updateSettings(\n list === 'disabledCategories'\n ? { disabledCategories: [...names] }\n : { disabledCommands: [...names] },\n );\n // Adding a name that's there, or removing one that isn't, changes nothing and fires nothing.\n const add = (list: OffList, name: string): void => {\n const current = listOf(list);\n if (!current.includes(name)) replace(list, [...current, name]);\n };\n const remove = (list: OffList, name: string): void => {\n const current = listOf(list);\n if (current.includes(name))\n replace(\n list,\n current.filter((other) => other !== name),\n );\n };\n\n return {\n getDisabledCategories: () => listOf('disabledCategories'),\n isCategoryDisabled: (category) => isCategoryOff(category, listOf('disabledCategories')),\n disableCategory: (category) => add('disabledCategories', category),\n enableCategory: (category) => remove('disabledCategories', category),\n setDisabledCategories: (categories) => replace('disabledCategories', categories),\n getDisabledCommands: () => listOf('disabledCommands'),\n isCommandDisabled: (id) => {\n const definition = definitionOf(id);\n return definition ? isTurnedOff(definition) : listOf('disabledCommands').includes(id);\n },\n disableCommand: (id) => add('disabledCommands', id),\n enableCommand: (id) => remove('disabledCommands', id),\n setDisabledCommands: (ids) => replace('disabledCommands', ids),\n } satisfies Partial<CommandsCapability>;\n}\n","/**\n * The commands controller: the commands (from the settings, added while the\n * app runs, and from families), resolution for a document (derivations over\n * live state, safe to throw), the one way to run a command, turning commands\n * off (by category and one by one), what the session may run (the scope's\n * `requires`, the plugins' checks in `allowed`), and the host-only keystroke\n * matcher.\n *\n * Definitions hold functions, so the commands added while the app runs are a\n * map outside state; every change to it calls `ctx.notify()` so readers read\n * again.\n */\nimport {\n DocumentsToken,\n isPluginError,\n memo,\n memoByKey,\n PluginError,\n toPluginError,\n toPluginErrorInfo,\n type CapabilityToken,\n type PluginContext,\n type Unsubscribe,\n} from '@embedpdf/core';\nimport { matchShortcut, type KeyStroke } from '@embedpdf/core-ui';\nimport { ShellToken } from '@embedpdf/plugin-shell/contract';\n\nimport type {\n CommandContext,\n CommandDef,\n CommandExecutedEvent,\n CommandExecutionFailedEvent,\n CommandFamily,\n CommandsSettings,\n ExecuteOptions,\n ExecuteResult,\n IconAccent,\n RegisterCommandOptions,\n ResolvedCommand,\n} from './contract';\nimport type { CommandsHostCapability, ShortcutMatch } from './host-contract';\nimport {\n configuredCommands,\n registeredCommand,\n type ConfiguredCommands,\n type RegisteredCommand,\n} from './registry';\nimport {\n createAvailability,\n labelOf,\n lockedMessage,\n notAllowedMessage,\n} from './services/availability';\nimport { createTurningOff } from './write/turning-off';\n\nconst panelTarget = (\n definition: CommandDef,\n): { id: string; exclusive?: string; focus?: boolean } | null =>\n definition.panel === undefined\n ? null\n : typeof definition.panel === 'string'\n ? { id: definition.panel }\n : definition.panel;\n\n/**\n * One command's live derivations for a document, as values a memo can\n * compare: the entry, label, accent colors, the enabled/active/visible flags,\n * and why it's disabled when the scope doesn't allow it.\n */\ntype Derivations = readonly [\n entry: RegisteredCommand | null,\n label: string,\n accentPrimary: string | undefined,\n accentSecondary: string | undefined,\n enabled: boolean,\n active: boolean,\n visible: boolean,\n disabledReason: string | undefined,\n];\n\nconst NOT_REGISTERED: Derivations = [\n null,\n '',\n undefined,\n undefined,\n false,\n false,\n false,\n undefined,\n];\nconst NO_NAMES: readonly string[] = [];\n\nconst accentOf = (primary?: string, secondary?: string): IconAccent | undefined =>\n primary === undefined && secondary === undefined\n ? undefined\n : {\n ...(primary !== undefined ? { primary } : {}),\n ...(secondary !== undefined ? { secondary } : {}),\n };\n\n/** The memo key of a resolution: the command id and the document named, if any. */\nconst resolutionKey = (id: string, documentId: string | undefined): string =>\n JSON.stringify([id, documentId ?? null]);\n\nexport function createCommandsController(ctx: PluginContext<void, CommandsSettings>) {\n const settings = ctx.settings();\n\n /** Commands added while the app runs, in the order they were added. */\n const registered = new Map<string, RegisteredCommand>();\n /** Bumped on every change to `registered`: the input of the reads built from it. */\n let registeredVersion = 0;\n const registeredChanged = (): void => {\n registeredVersion += 1;\n ctx.notify();\n };\n\n /** The commands the settings define, rebuilt when the setting changes. */\n const configured = memo(\n () => [settings.get().commands],\n (items): ConfiguredCommands => configuredCommands(items),\n );\n\n const executed = ctx.events.source<CommandExecutedEvent>();\n const executionFailed = ctx.events.source<CommandExecutionFailedEvent>();\n\n /** Capabilities for the command's document: the one named, else the active one. */\n const commandContext = (\n documentId?: string,\n call: { args?: unknown; signal?: AbortSignal } = {},\n ): CommandContext => {\n const target = documentId ?? ctx.get(DocumentsToken).getActiveId();\n const get = <T>(token: CapabilityToken<T>): T =>\n target ? ctx.forDocument(token, target) : ctx.get(token);\n return {\n documentId: target,\n appState: settings.get().appState,\n ...(call.args === undefined ? {} : { args: call.args }),\n ...(call.signal ? { signal: call.signal } : {}),\n get,\n tryGet: <T>(token: CapabilityToken<T>): T | null => {\n try {\n return get(token);\n } catch {\n return null;\n }\n },\n };\n };\n\n /** A family's command for one name, made once so it keeps its identity. */\n const familyCommands = new WeakMap<CommandFamily, Map<string, RegisteredCommand>>();\n const familyCommand = (family: CommandFamily, name: string): RegisteredCommand => {\n let byName = familyCommands.get(family);\n if (!byName) {\n byName = new Map();\n familyCommands.set(family, byName);\n }\n let entry = byName.get(name);\n if (!entry) {\n entry = registeredCommand({ ...family.command(name), id: `${family.prefix}${name}` });\n byName.set(name, entry);\n }\n return entry;\n };\n\n /** The command with this id: one added while the app runs, else the settings', else a family's. */\n const entryOf = (id: string): RegisteredCommand | null => {\n const { commands, families } = configured();\n const entry = registered.get(id) ?? commands.get(id);\n if (entry) return entry;\n const family = families.find(\n (candidate) => id.startsWith(candidate.prefix) && id.length > candidate.prefix.length,\n );\n return family ? familyCommand(family, id.slice(family.prefix.length)) : null;\n };\n\n /** Every command with its own definition (not a family's), each id once. */\n const definedCommands = memo(\n () => [registeredVersion, configured()],\n (_version, { commands }) => {\n const entries = new Map(commands);\n for (const [id, entry] of registered) entries.set(id, entry);\n return [...entries.values()];\n },\n );\n\n // Derivations run against live state: without one, the command is what\n // `absent` says; one that throws (it needs a document and none is open, say)\n // says no, so the button renders disabled, not pressed or hidden instead of\n // breaking.\n const derive = (\n derivation: ((context: CommandContext) => boolean) | undefined,\n context: CommandContext,\n absent: boolean,\n ): boolean => {\n if (!derivation) return absent;\n try {\n return derivation(context);\n } catch {\n return false;\n }\n };\n const deriveAccent = (\n derivation: ((context: CommandContext) => IconAccent | null) | undefined,\n context: CommandContext,\n ): IconAccent | undefined => {\n if (!derivation) return undefined;\n try {\n return derivation(context) ?? undefined;\n } catch {\n return undefined;\n }\n };\n const namesOf = (family: CommandFamily, context: CommandContext): readonly string[] => {\n try {\n return family.names(context);\n } catch {\n return NO_NAMES;\n }\n };\n\n const { isTurnedOff, notAllowedKeyOf, lockOf, refusalOf } = createAvailability(ctx, settings);\n\n const derivationsOf = (entry: RegisteredCommand, documentId?: string): Derivations => {\n const { definition } = entry;\n const context = commandContext(documentId);\n const label = labelOf(definition, context);\n // Turned off hides it; not allowed hides it, or disables it with the reason; a lock on the\n // setting it changes disables it with the lock's reason, whatever `notAllowed` says.\n const turnedOff = isTurnedOff(definition);\n const notAllowed = turnedOff ? null : notAllowedKeyOf(definition, context);\n const shownWhenNotAllowed = settings.get().notAllowed === 'disable';\n const lock = turnedOff || notAllowed !== null ? null : lockOf(definition, context);\n const ruledOut = turnedOff || notAllowed !== null || lock !== null;\n // A command that opens something is active while it's open, unless it says otherwise.\n let active: boolean;\n if (definition.active) {\n active = derive(definition.active, context, false);\n } else {\n const shell = context.tryGet(ShellToken);\n const panel = panelTarget(definition);\n active = shell\n ? definition.menu\n ? shell.isMenuOpen(definition.menu)\n : panel\n ? shell.isOpen(panel.id)\n : definition.modal\n ? shell.isOpen(definition.modal)\n : false\n : false;\n }\n const accent = deriveAccent(definition.iconAccent, context);\n return [\n entry,\n label,\n accent?.primary,\n accent?.secondary,\n !ruledOut && derive(definition.enabled, context, true),\n active,\n !turnedOff &&\n (notAllowed === null || shownWhenNotAllowed) &&\n derive(definition.visible, context, true),\n notAllowed !== null && shownWhenNotAllowed\n ? notAllowedMessage(notAllowed, label, context)\n : lock !== null\n ? lockedMessage(lock, label, context)\n : undefined,\n ];\n };\n\n /** A resolved command, the same object until one of its derivations or its entry changes. */\n const resolvedByKey = memoByKey(\n (key: string): Derivations => {\n const [id, documentId] = JSON.parse(key) as [string, string | null];\n const entry = entryOf(id);\n return entry ? derivationsOf(entry, documentId ?? undefined) : NOT_REGISTERED;\n },\n (\n _key,\n entry,\n label,\n accentPrimary,\n accentSecondary,\n enabled,\n active,\n visible,\n disabledReason,\n ): ResolvedCommand | null =>\n entry && {\n id: entry.definition.id,\n label,\n icon: entry.definition.icon,\n iconAccent: accentOf(accentPrimary, accentSecondary),\n shortcuts: entry.shortcuts,\n menu: entry.definition.menu,\n enabled,\n active,\n visible,\n categories: entry.definition.categories ?? [],\n ...(disabledReason === undefined ? {} : { disabledReason }),\n },\n );\n const resolveCommand = (id: string, documentId?: string): ResolvedCommand | null =>\n entryOf(id) ? resolvedByKey(resolutionKey(id, documentId)) : null;\n\n /**\n * Every command's id for a document (`''` is the active one): the defined ones in the order\n * they were added, then each family's names that no defined command took.\n */\n const idsByDocument = memoByKey(\n (documentKey: string): readonly unknown[] => {\n const config = configured();\n const context = commandContext(documentKey || undefined);\n return [\n definedCommands(),\n config,\n ...config.families.map((family) => namesOf(family, context)),\n ];\n },\n (_documentKey, ...inputs): readonly string[] => {\n const [defined, { families }, ...names] = inputs as [\n readonly RegisteredCommand[],\n ConfiguredCommands,\n ...(readonly string[])[],\n ];\n const ids = defined.map((entry) => entry.definition.id);\n const taken = new Set(ids);\n families.forEach((family, index) => {\n for (const name of names[index] ?? NO_NAMES) {\n const id = `${family.prefix}${name}`;\n if (taken.has(id)) continue;\n taken.add(id);\n ids.push(id);\n }\n });\n return ids;\n },\n );\n const commandsByDocument = memoByKey(\n (documentKey: string) =>\n idsByDocument(documentKey).map((id) => resolveCommand(id, documentKey || undefined)),\n (_documentKey, ...resolved) =>\n resolved.filter((command): command is ResolvedCommand => command !== null),\n );\n const listCommands = (documentId?: string): readonly ResolvedCommand[] =>\n commandsByDocument(documentId ?? '');\n\n const listShortcuts = memo(\n () => [definedCommands()],\n (entries) =>\n entries.flatMap((entry) =>\n entry.shortcuts.map((shortcut) => ({ commandId: entry.definition.id, shortcut })),\n ),\n );\n\n /** What running a command does: its `run`, or opening what it opens. */\n const runCommand = async (definition: CommandDef, context: CommandContext): Promise<void> => {\n if (definition.run) {\n await definition.run(context);\n return;\n }\n const shell = context.tryGet(ShellToken);\n const panel = panelTarget(definition);\n if (!shell) return;\n if (definition.menu) shell.toggleMenu(definition.menu);\n else if (panel) shell.toggle(panel.id, { exclusive: panel.exclusive, focus: panel.focus });\n else if (definition.modal) shell.toggle(definition.modal, { exclusive: 'modal' });\n };\n\n const execute = async (id: string, options: ExecuteOptions = {}): Promise<ExecuteResult> => {\n const { signal, documentId, args } = options;\n if (signal?.aborted) {\n throw new PluginError('operation-cancelled', 'commands', 'operation cancelled');\n }\n const entry = entryOf(id);\n if (!entry) return { status: 'rejected', reason: 'not-found' };\n const resolved = resolveCommand(id, documentId);\n if (!resolved?.visible) return { status: 'rejected', reason: 'hidden' };\n if (!resolved.enabled) return { status: 'rejected', reason: 'disabled' };\n const context = commandContext(documentId, { args, signal });\n try {\n await ctx.cancellable(signal, runCommand(entry.definition, context));\n } catch (error) {\n // The caller cancelling isn't the command failing.\n if (signal?.aborted && isPluginError(error, 'operation-cancelled')) throw error;\n const failure = toPluginError('commands', error);\n executionFailed.emit({\n commandId: id,\n documentId: context.documentId,\n error: toPluginErrorInfo(failure),\n });\n throw failure;\n } finally {\n // A run may change what the commands read outside the viewer (your app's state): every\n // button asks its command again, so the one just pressed shows what it did.\n ctx.notify();\n }\n executed.emit({ commandId: id, documentId: context.documentId, args });\n return { status: 'executed' };\n };\n\n const registerOne = (definition: CommandDef, options?: RegisterCommandOptions): Unsubscribe => {\n const taken = registered.has(definition.id) || configured().commands.has(definition.id);\n if (taken && !options?.replace) {\n throw new PluginError('conflict', 'commands', `duplicate command '${definition.id}'`);\n }\n const entry = registeredCommand(definition);\n registered.set(definition.id, entry);\n registeredChanged();\n return () => {\n // Own this registration only: a later replacement is not ours to remove.\n if (registered.get(definition.id) !== entry) return;\n registered.delete(definition.id);\n registeredChanged();\n };\n };\n\n const turningOff = createTurningOff(\n settings,\n (id) => entryOf(id)?.definition ?? null,\n isTurnedOff,\n );\n\n const api: CommandsHostCapability = {\n ...settings.api,\n registerCommand: registerOne,\n registerCommands: (definitions, options) => {\n const removers = definitions.map((definition) => registerOne(definition, options));\n return () => removers.forEach((remove) => remove());\n },\n hasCommand: (id) => entryOf(id) !== null,\n getCommand: (id) => entryOf(id)?.definition ?? null,\n listCommandIds: () => idsByDocument(''),\n resolveCommand,\n listCommands,\n searchCommands: (query, documentId) => {\n const needle = query.trim().toLowerCase();\n return listCommands(documentId).filter(\n (command) =>\n command.visible &&\n (needle === '' ||\n command.label.toLowerCase().includes(needle) ||\n command.id.includes(needle)),\n );\n },\n listShortcuts,\n execute,\n canExecute: (id, documentId) => {\n const resolved = resolveCommand(id, documentId);\n return !!resolved && resolved.enabled && resolved.visible;\n },\n getRefusal: (id, documentId) => {\n const entry = entryOf(id);\n return entry ? refusalOf(entry.definition, commandContext(documentId)) : null;\n },\n ...turningOff,\n onExecuted: executed.on,\n onExecutionFailed: executionFailed.on,\n // ── host lens ──\n matchStroke: (stroke: KeyStroke, options) => {\n let refused: ShortcutMatch | null = null;\n for (const entry of definedCommands()) {\n if (options.inTextField && !entry.definition.shortcutInTextFields) continue;\n if (!entry.parsed.some((shortcut) => matchShortcut(shortcut, stroke, options))) continue;\n const context = commandContext();\n const refusal = refusalOf(entry.definition, context);\n if (!refusal) return { commandId: entry.definition.id, refusal: null };\n // A refused command takes its keys only where it would show: Delete with nothing\n // selected stays the page's, even where deleting is turned off.\n if (!derive(entry.definition.visible, context, true)) continue;\n refused ??= { commandId: entry.definition.id, refusal };\n }\n return refused;\n },\n getMenuTarget: (id) => {\n const entry = entryOf(id);\n return entry ? { menu: entry.definition.menu } : null;\n },\n };\n\n return { api };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { I18nToken } from '@embedpdf/plugin-i18n/contract';\nimport { ShellToken } from '@embedpdf/plugin-shell/contract';\n\nimport { COMMANDS_DEFAULTS, type CommandsConfig } from './contract';\nimport { createCommandsController } from './controller';\nimport { CommandsToken } from './host-contract';\n\n/**\n * The commands: one set for the whole workspace, each resolved and run for a\n * document (the one named, else the document in scope, else the active one).\n * Definitions are settings and app content, never state, since they hold\n * functions. `config` is the settings the app registers, over\n * {@link COMMANDS_DEFAULTS}.\n */\nexport const commandsPlugin = <AppState = any>(config?: CommandsConfig<AppState>) =>\n definePlugin({\n id: 'commands',\n scope: 'workspace',\n token: CommandsToken,\n // Labels come from i18n, and commands that open a panel, menu or dialog\n // go through shell; without them a label is the command's own, and those\n // commands open nothing.\n optional: [I18nToken, ShellToken],\n // Command definitions come from the app and may use any capability.\n resolvesAnyCapability: true,\n // Your app's state is replaced whole, never merged: a new value is the whole new state.\n settings: {\n defaults: COMMANDS_DEFAULTS,\n registered: config as CommandsConfig | undefined,\n whole: ['appState'],\n },\n create: createCommandsController,\n // Inside a document's scope, a call that leaves out the document is for that one.\n inScope: (commands, documentId) => ({\n ...commands,\n resolveCommand: (id, target = documentId) => commands.resolveCommand(id, target),\n listCommands: (target = documentId) => commands.listCommands(target),\n searchCommands: (query, target = documentId) => commands.searchCommands(query, target),\n execute: (id, options) =>\n commands.execute(id, { ...options, documentId: options?.documentId ?? documentId }),\n canExecute: (id, target = documentId) => commands.canExecute(id, target),\n getRefusal: (id, target = documentId) => commands.getRefusal(id, target),\n }),\n });\n"],"mappings":";;;;;;;;;AAWA,MAAa,qBAAqB,eAA8C;CAC9E,MAAM,YACJ,WAAW,aAAa,KAAA,IAAY,CAAC,IAAK,CAAC,CAAC,CAAc,OAAO,WAAW,QAAQ;CACtF,OAAO;EAAE;EAAY;E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IAAI,YACZ,SAAS,QAAQ,IAAI;GAAE,GAAG;GAAS,YAAY,SAAS,cAAc;EAAW,CAAC;EACpF,aAAa,IAAI,SAAS,eAAe,SAAS,WAAW,IAAI,MAAM;EACvE,aAAa,IAAI,SAAS,eAAe,SAAS,WAAW,IAAI,MAAM;CACzE;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["parseShortcut","I18nToken","DocumentsToken","ShellToken","PluginError","CommandsToken","I18nToken","ShellToken","COMMANDS_DEFAULTS"],"sources":["../src/registry.ts","../src/services/availability.ts","../src/write/turning-off.ts","../src/controller.ts","../src/commands.plugin.ts"],"sourcesContent":["/** A command definition with its shortcuts parsed once, and how the registry tells a family apart. */\nimport { parseShortcut, type ParsedShortcut } from '@embedpdf/core-ui';\n\nimport type { CommandDef, CommandFamily } from './contract';\n\nexport interface RegisteredCommand {\n readonly definition: CommandDef;\n readonly shortcuts: readonly string[];\n readonly parsed: readonly ParsedShortcut[];\n}\n\nexport const registeredCommand = (definition: CommandDef): RegisteredCommand => {\n const shortcuts =\n definition.shortcut === undefined ? [] : ([] as string[]).concat(definition.shortcut);\n return { definition, shortcuts, parsed: shortcuts.map(parseShortcut) };\n};\n\nexport const isCommandFamily = (item: CommandDef | CommandFamily): item is CommandFamily =>\n 'prefix' in item;\n\n/** The commands the settings define, by id (a later id replaces an earlier one), and their families. */\nexport interface ConfiguredCommands {\n readonly commands: ReadonlyMap<string, RegisteredCommand>;\n readonly families: readonly CommandFamily[];\n}\n\nexport function configuredCommands(\n items: readonly (CommandDef | CommandFamily)[],\n): ConfiguredCommands {\n const commands = new Map<string, RegisteredCommand>();\n const families: CommandFamily[] = [];\n for (const item of items) {\n if (isCommandFamily(item)) families.push(item);\n else commands.set(item.id, registeredCommand(item));\n }\n return { commands, families };\n}\n","/**\n * Whether a command is there at all, apart from what it says about the\n * moment (`enabled`, `visible`): turned off in this viewer (its id, or one of\n * its categories), not allowed for its document (the scope's `requires`, or\n * the plugins' checks in `allowed`), or held by a lock on the setting it\n * changes (`locked`), and the sentence that says why, translated when the\n * i18n plugin is there.\n */\nimport type {\n DocumentHandle,\n Permission,\n PluginContext,\n SettingLock,\n Settings,\n} from '@embedpdf/core';\nimport { I18nToken } from '@embedpdf/plugin-i18n/contract';\n\nimport type { CommandContext, CommandDef, CommandRefusal, CommandsSettings } from '../contract';\n\n/**\n * Whether a category is off: it, or a category it's under, is in the list. Parts are whole\n * dotted segments, so `annotations` covers `annotations.highlight` and not `annotationsExtra`.\n */\nexport const isCategoryOff = (category: string, disabled: readonly string[]): boolean =>\n disabled.some((off) => category === off || category.startsWith(`${off}.`));\n\n/**\n * The label: a language's string under the command's id, else under its `labelKey` (the current\n * language, then the fallback one), else `label`, else the id. So a string for\n * `'document:download'` relabels that one command, whichever key its label is under.\n */\nexport const labelOf = (definition: CommandDef, context: CommandContext): string => {\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return definition.label ?? definition.labelKey ?? definition.id;\n const fallbackKey = definition.labelKey ? { fallbackKey: definition.labelKey } : {};\n // A command with a key and no label of its own warns once when no language has the key.\n return definition.label === undefined && definition.labelKey\n ? i18n.t(definition.id, fallbackKey)\n : i18n.t(definition.id, { ...fallbackKey, fallback: definition.label ?? definition.id });\n};\n\n/**\n * Whether a document's session holds a permission: what `ctx.allows` answers for a\n * document-scoped plugin, asked here of the command's document, since the commands are one\n * set for the whole workspace.\n */\nconst sessionHolds = (security: DocumentHandle['security'], permission: Permission): boolean =>\n permission === 'annotations:create'\n ? security.allowsAnnotation('create')\n : security.allows(permission);\n\n/** Where a language keeps the sentence for a permission: `commands.notAllowed.doc-text-copy`. */\nconst permissionKeyOf = (permission: Permission): string =>\n `commands.notAllowed.${permission.replace(/[.:]/g, '-')}`;\n\n/** The general sentence's key: `{label} isn't allowed`. */\nconst DEFAULT_NOT_ALLOWED_KEY = 'commands.notAllowed.default';\n\n/** The sentence for a command the session may not run, under `key`, else the general one. */\nexport const notAllowedMessage = (key: string, label: string, context: CommandContext): string => {\n const fallback = `${label} isn't allowed`;\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return fallback;\n const params = { label };\n return i18n.t(key, {\n params,\n fallback: i18n.t(DEFAULT_NOT_ALLOWED_KEY, { params, fallback }),\n });\n};\n\n/** The general locked sentence's key: `{label} can't be changed in this document`. */\nconst DEFAULT_LOCKED_KEY = 'commands.locked.default';\n\n/** The sentence for a command whose setting a lock holds: its `reasonKey`, else the general one. */\nexport const lockedMessage = (\n lock: SettingLock,\n label: string,\n context: CommandContext,\n): string => {\n const fallback = `${label} can't be changed in this document`;\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return fallback;\n const params = { label };\n const general = i18n.t(DEFAULT_LOCKED_KEY, { params, fallback });\n return lock.reasonKey === undefined\n ? general\n : i18n.t(lock.reasonKey, { params, fallback: general });\n};\n\n/** The sentence for a command that's turned off. */\nconst turnedOffMessage = (label: string, context: CommandContext): string => {\n const i18n = context.tryGet(I18nToken);\n return i18n\n ? i18n.t('commands.turnedOff', { params: { label }, fallback: \"{label} isn't available\" })\n : `${label} isn't available`;\n};\n\nexport function createAvailability(\n ctx: PluginContext<void, CommandsSettings>,\n settings: Settings<CommandsSettings>,\n) {\n /** Whether a command is turned off: by its id, or through one of its categories. */\n const isTurnedOff = (definition: CommandDef): boolean => {\n const { disabledCategories, disabledCommands } = settings.get();\n return (\n disabledCommands.includes(definition.id) ||\n (definition.categories ?? []).some((category) => isCategoryOff(category, disabledCategories))\n );\n };\n\n /** Whether a command's `allowed` check says yes; one that throws allows it. */\n const passesCheck = (definition: CommandDef, context: CommandContext): boolean => {\n if (!definition.allowed) return true;\n try {\n return definition.allowed(context);\n } catch {\n return true;\n }\n };\n\n /** The lock on the setting a command changes, or `null`; a `locked` that throws is no lock. */\n const lockOf = (definition: CommandDef, context: CommandContext): SettingLock | null => {\n if (!definition.locked) return null;\n try {\n return definition.locked(context);\n } catch {\n return null;\n }\n };\n\n /**\n * Why its document's session may not run a command, as the key of the sentence that says\n * so, or `null` when it may: the first permission `requires` names that the session doesn't\n * hold (`commands.notAllowed.doc-print`), else its `allowed` check saying no (its\n * `notAllowedKey`). With no document open there is no session to ask, and nothing is refused.\n */\n const notAllowedKeyOf = (definition: CommandDef, context: CommandContext): string | null => {\n if (!definition.requires?.length && !definition.allowed) return null;\n const handle = context.documentId === null ? null : ctx.documentHandle(context.documentId);\n if (!handle) return null;\n const missing = definition.requires?.find(\n (permission) => !sessionHolds(handle.security, permission),\n );\n if (missing !== undefined) return permissionKeyOf(missing);\n return passesCheck(definition, context)\n ? null\n : (definition.notAllowedKey ?? DEFAULT_NOT_ALLOWED_KEY);\n };\n\n /** Why a command won't run whatever the moment, or `null` when it may run. */\n const refusalOf = (definition: CommandDef, context: CommandContext): CommandRefusal | null => {\n if (isTurnedOff(definition)) {\n return {\n reason: 'turned-off',\n message: turnedOffMessage(labelOf(definition, context), context),\n };\n }\n const notAllowed = notAllowedKeyOf(definition, context);\n if (notAllowed !== null) {\n return {\n reason: 'not-allowed',\n message: notAllowedMessage(notAllowed, labelOf(definition, context), context),\n };\n }\n const lock = lockOf(definition, context);\n return lock === null\n ? null\n : { reason: 'locked', message: lockedMessage(lock, labelOf(definition, context), context) };\n };\n\n return { isTurnedOff, notAllowedKeyOf, lockOf, refusalOf };\n}\n","/**\n * Turning commands off and on: by category, with every category under it, and\n * one by one. Both lists are settings, so they change live and\n * `resetSettings()` restores what the app registered.\n */\nimport type { Settings } from '@embedpdf/core';\n\nimport type { CommandDef, CommandsCapability, CommandsSettings } from '../contract';\nimport { isCategoryOff } from '../services/availability';\n\ntype OffList = 'disabledCategories' | 'disabledCommands';\n\nexport function createTurningOff(\n settings: Settings<CommandsSettings>,\n definitionOf: (id: string) => CommandDef | null,\n isTurnedOff: (definition: CommandDef) => boolean,\n) {\n const listOf = (list: OffList): readonly string[] => settings.get()[list];\n const replace = (list: OffList, names: readonly string[]): void =>\n settings.api.updateSettings(\n list === 'disabledCategories'\n ? { disabledCategories: [...names] }\n : { disabledCommands: [...names] },\n );\n // Adding a name that's there, or removing one that isn't, changes nothing and fires nothing.\n const add = (list: OffList, name: string): void => {\n const current = listOf(list);\n if (!current.includes(name)) replace(list, [...current, name]);\n };\n const remove = (list: OffList, name: string): void => {\n const current = listOf(list);\n if (current.includes(name))\n replace(\n list,\n current.filter((other) => other !== name),\n );\n };\n\n return {\n getDisabledCategories: () => listOf('disabledCategories'),\n isCategoryDisabled: (category) => isCategoryOff(category, listOf('disabledCategories')),\n disableCategory: (category) => add('disabledCategories', category),\n enableCategory: (category) => remove('disabledCategories', category),\n setDisabledCategories: (categories) => replace('disabledCategories', categories),\n getDisabledCommands: () => listOf('disabledCommands'),\n isCommandDisabled: (id) => {\n const definition = definitionOf(id);\n return definition ? isTurnedOff(definition) : listOf('disabledCommands').includes(id);\n },\n disableCommand: (id) => add('disabledCommands', id),\n enableCommand: (id) => remove('disabledCommands', id),\n setDisabledCommands: (ids) => replace('disabledCommands', ids),\n } satisfies Partial<CommandsCapability>;\n}\n","/**\n * The commands controller: the commands (from the settings, added while the\n * app runs, and from families), resolution for a document (derivations over\n * live state, safe to throw), the one way to run a command, turning commands\n * off (by category and one by one), what the session may run (the scope's\n * `requires`, the plugins' checks in `allowed`), and the host-only keystroke\n * matcher.\n *\n * Definitions hold functions, so the commands added while the app runs are a\n * map outside state; every change to it calls `ctx.notify()` so readers read\n * again.\n */\nimport {\n DocumentsToken,\n isPluginError,\n memo,\n memoByKey,\n PluginError,\n toPluginError,\n toPluginErrorInfo,\n type CapabilityToken,\n type PluginContext,\n type Unsubscribe,\n} from '@embedpdf/core';\nimport { matchShortcut, type KeyStroke } from '@embedpdf/core-ui';\nimport { ShellToken } from '@embedpdf/plugin-shell/contract';\n\nimport type {\n CommandContext,\n CommandDef,\n CommandExecutedEvent,\n CommandExecutionFailedEvent,\n CommandFamily,\n CommandsSettings,\n ExecuteOptions,\n ExecuteResult,\n IconAccent,\n RegisterCommandOptions,\n ResolvedCommand,\n} from './contract';\nimport type { CommandsHostCapability, ShortcutMatch } from './host-contract';\nimport {\n configuredCommands,\n registeredCommand,\n type ConfiguredCommands,\n type RegisteredCommand,\n} from './registry';\nimport {\n createAvailability,\n labelOf,\n lockedMessage,\n notAllowedMessage,\n} from './services/availability';\nimport { createTurningOff } from './write/turning-off';\n\nconst panelTarget = (\n definition: CommandDef,\n): { id: string; exclusive?: string; focus?: boolean } | null =>\n definition.panel === undefined\n ? null\n : typeof definition.panel === 'string'\n ? { id: definition.panel }\n : definition.panel;\n\n/**\n * One command's live derivations for a document, as values a memo can\n * compare: the entry, label, accent colors, the enabled/active/visible flags,\n * and why it's disabled when the scope doesn't allow it.\n */\ntype Derivations = readonly [\n entry: RegisteredCommand | null,\n label: string,\n accentPrimary: string | undefined,\n accentSecondary: string | undefined,\n enabled: boolean,\n active: boolean,\n visible: boolean,\n disabledReason: string | undefined,\n];\n\nconst NOT_REGISTERED: Derivations = [\n null,\n '',\n undefined,\n undefined,\n false,\n false,\n false,\n undefined,\n];\nconst NO_NAMES: readonly string[] = [];\n\nconst accentOf = (primary?: string, secondary?: string): IconAccent | undefined =>\n primary === undefined && secondary === undefined\n ? undefined\n : {\n ...(primary !== undefined ? { primary } : {}),\n ...(secondary !== undefined ? { secondary } : {}),\n };\n\n/** The memo key of a resolution: the command id and the document named, if any. */\nconst resolutionKey = (id: string, documentId: string | undefined): string =>\n JSON.stringify([id, documentId ?? null]);\n\nexport function createCommandsController(ctx: PluginContext<void, CommandsSettings>) {\n const settings = ctx.settings();\n\n /** Commands added while the app runs, in the order they were added. */\n const registered = new Map<string, RegisteredCommand>();\n /** Bumped on every change to `registered`: the input of the reads built from it. */\n let registeredVersion = 0;\n const registeredChanged = (): void => {\n registeredVersion += 1;\n ctx.notify();\n };\n\n /** The commands the settings define, rebuilt when the setting changes. */\n const configured = memo(\n () => [settings.get().commands],\n (items): ConfiguredCommands => configuredCommands(items),\n );\n\n const executed = ctx.events.source<CommandExecutedEvent>();\n const executionFailed = ctx.events.source<CommandExecutionFailedEvent>();\n\n /** Capabilities for the command's document: the one named, else the active one. */\n const commandContext = (\n documentId?: string,\n call: { args?: unknown; signal?: AbortSignal } = {},\n ): CommandContext => {\n const target = documentId ?? ctx.get(DocumentsToken).getActiveId();\n const get = <T>(token: CapabilityToken<T>): T =>\n target ? ctx.forDocument(token, target) : ctx.get(token);\n return {\n documentId: target,\n appState: settings.get().appState,\n ...(call.args === undefined ? {} : { args: call.args }),\n ...(call.signal ? { signal: call.signal } : {}),\n get,\n tryGet: <T>(token: CapabilityToken<T>): T | null => {\n try {\n return get(token);\n } catch {\n return null;\n }\n },\n };\n };\n\n /** A family's command for one name, made once so it keeps its identity. */\n const familyCommands = new WeakMap<CommandFamily, Map<string, RegisteredCommand>>();\n const familyCommand = (family: CommandFamily, name: string): RegisteredCommand => {\n let byName = familyCommands.get(family);\n if (!byName) {\n byName = new Map();\n familyCommands.set(family, byName);\n }\n let entry = byName.get(name);\n if (!entry) {\n entry = registeredCommand({ ...family.command(name), id: `${family.prefix}${name}` });\n byName.set(name, entry);\n }\n return entry;\n };\n\n /** The command with this id: one added while the app runs, else the settings', else a family's. */\n const entryOf = (id: string): RegisteredCommand | null => {\n const { commands, families } = configured();\n const entry = registered.get(id) ?? commands.get(id);\n if (entry) return entry;\n const family = families.find(\n (candidate) => id.startsWith(candidate.prefix) && id.length > candidate.prefix.length,\n );\n return family ? familyCommand(family, id.slice(family.prefix.length)) : null;\n };\n\n /** Every command with its own definition (not a family's), each id once. */\n const definedCommands = memo(\n () => [registeredVersion, configured()],\n (_version, { commands }) => {\n const entries = new Map(commands);\n for (const [id, entry] of registered) entries.set(id, entry);\n return [...entries.values()];\n },\n );\n\n // Derivations run against live state: without one, the command is what\n // `absent` says; one that throws (it needs a document and none is open, say)\n // says no, so the button renders disabled, not pressed or hidden instead of\n // breaking.\n const derive = (\n derivation: ((context: CommandContext) => boolean) | undefined,\n context: CommandContext,\n absent: boolean,\n ): boolean => {\n if (!derivation) return absent;\n try {\n return derivation(context);\n } catch {\n return false;\n }\n };\n const deriveAccent = (\n derivation: ((context: CommandContext) => IconAccent | null) | undefined,\n context: CommandContext,\n ): IconAccent | undefined => {\n if (!derivation) return undefined;\n try {\n return derivation(context) ?? undefined;\n } catch {\n return undefined;\n }\n };\n const namesOf = (family: CommandFamily, context: CommandContext): readonly string[] => {\n try {\n return family.names(context);\n } catch {\n return NO_NAMES;\n }\n };\n\n const { isTurnedOff, notAllowedKeyOf, lockOf, refusalOf } = createAvailability(ctx, settings);\n\n const derivationsOf = (entry: RegisteredCommand, documentId?: string): Derivations => {\n const { definition } = entry;\n const context = commandContext(documentId);\n const label = labelOf(definition, context);\n // Turned off hides it; not allowed hides it, or disables it with the reason; a lock on the\n // setting it changes disables it with the lock's reason, whatever `notAllowed` says.\n const turnedOff = isTurnedOff(definition);\n const notAllowed = turnedOff ? null : notAllowedKeyOf(definition, context);\n const shownWhenNotAllowed = settings.get().notAllowed === 'disable';\n const lock = turnedOff || notAllowed !== null ? null : lockOf(definition, context);\n const ruledOut = turnedOff || notAllowed !== null || lock !== null;\n // A command that opens something is active while it's open, unless it says otherwise.\n let active: boolean;\n if (definition.active) {\n active = derive(definition.active, context, false);\n } else {\n const shell = context.tryGet(ShellToken);\n const panel = panelTarget(definition);\n active = shell\n ? definition.menu\n ? shell.isMenuOpen(definition.menu)\n : panel\n ? shell.isOpen(panel.id)\n : definition.modal\n ? shell.isOpen(definition.modal)\n : false\n : false;\n }\n const accent = deriveAccent(definition.iconAccent, context);\n return [\n entry,\n label,\n accent?.primary,\n accent?.secondary,\n !ruledOut && derive(definition.enabled, context, true),\n active,\n !turnedOff &&\n (notAllowed === null || shownWhenNotAllowed) &&\n derive(definition.visible, context, true),\n notAllowed !== null && shownWhenNotAllowed\n ? notAllowedMessage(notAllowed, label, context)\n : lock !== null\n ? lockedMessage(lock, label, context)\n : undefined,\n ];\n };\n\n /** A resolved command, the same object until one of its derivations or its entry changes. */\n const resolvedByKey = memoByKey(\n (key: string): Derivations => {\n const [id, documentId] = JSON.parse(key) as [string, string | null];\n const entry = entryOf(id);\n return entry ? derivationsOf(entry, documentId ?? undefined) : NOT_REGISTERED;\n },\n (\n _key,\n entry,\n label,\n accentPrimary,\n accentSecondary,\n enabled,\n active,\n visible,\n disabledReason,\n ): ResolvedCommand | null =>\n entry && {\n id: entry.definition.id,\n label,\n icon: entry.definition.icon,\n iconAccent: accentOf(accentPrimary, accentSecondary),\n shortcuts: entry.shortcuts,\n menu: entry.definition.menu,\n enabled,\n active,\n visible,\n categories: entry.definition.categories ?? [],\n ...(disabledReason === undefined ? {} : { disabledReason }),\n },\n );\n const resolveCommand = (id: string, documentId?: string): ResolvedCommand | null =>\n entryOf(id) ? resolvedByKey(resolutionKey(id, documentId)) : null;\n\n /**\n * Every command's id for a document (`''` is the active one): the defined ones in the order\n * they were added, then each family's names that no defined command took.\n */\n const idsByDocument = memoByKey(\n (documentKey: string): readonly unknown[] => {\n const config = configured();\n const context = commandContext(documentKey || undefined);\n return [\n definedCommands(),\n config,\n ...config.families.map((family) => namesOf(family, context)),\n ];\n },\n (_documentKey, ...inputs): readonly string[] => {\n const [defined, { families }, ...names] = inputs as [\n readonly RegisteredCommand[],\n ConfiguredCommands,\n ...(readonly string[])[],\n ];\n const ids = defined.map((entry) => entry.definition.id);\n const taken = new Set(ids);\n families.forEach((family, index) => {\n for (const name of names[index] ?? NO_NAMES) {\n const id = `${family.prefix}${name}`;\n if (taken.has(id)) continue;\n taken.add(id);\n ids.push(id);\n }\n });\n return ids;\n },\n );\n const commandsByDocument = memoByKey(\n (documentKey: string) =>\n idsByDocument(documentKey).map((id) => resolveCommand(id, documentKey || undefined)),\n (_documentKey, ...resolved) =>\n resolved.filter((command): command is ResolvedCommand => command !== null),\n );\n const listCommands = (documentId?: string): readonly ResolvedCommand[] =>\n commandsByDocument(documentId ?? '');\n\n const listShortcuts = memo(\n () => [definedCommands()],\n (entries) =>\n entries.flatMap((entry) =>\n entry.shortcuts.map((shortcut) => ({ commandId: entry.definition.id, shortcut })),\n ),\n );\n\n /** What running a command does: its `run`, or opening what it opens. */\n const runCommand = async (definition: CommandDef, context: CommandContext): Promise<void> => {\n if (definition.run) {\n await definition.run(context);\n return;\n }\n const shell = context.tryGet(ShellToken);\n const panel = panelTarget(definition);\n if (!shell) return;\n if (definition.menu) shell.toggleMenu(definition.menu);\n else if (panel) shell.toggle(panel.id, { exclusive: panel.exclusive, focus: panel.focus });\n else if (definition.modal) shell.toggle(definition.modal, { exclusive: 'modal' });\n };\n\n const execute = async (id: string, options: ExecuteOptions = {}): Promise<ExecuteResult> => {\n const { signal, documentId, args } = options;\n if (signal?.aborted) {\n throw new PluginError('operation-cancelled', 'commands', 'operation cancelled');\n }\n const entry = entryOf(id);\n if (!entry) return { status: 'rejected', reason: 'not-found' };\n const resolved = resolveCommand(id, documentId);\n if (!resolved?.visible) return { status: 'rejected', reason: 'hidden' };\n if (!resolved.enabled) return { status: 'rejected', reason: 'disabled' };\n const context = commandContext(documentId, { args, signal });\n try {\n await ctx.cancellable(signal, runCommand(entry.definition, context));\n } catch (error) {\n // The caller cancelling isn't the command failing.\n if (signal?.aborted && isPluginError(error, 'operation-cancelled')) throw error;\n const failure = toPluginError('commands', error);\n executionFailed.emit({\n commandId: id,\n documentId: context.documentId,\n error: toPluginErrorInfo(failure),\n });\n throw failure;\n } finally {\n // A run may change what the commands read outside the viewer (your app's state): every\n // button asks its command again, so the one just pressed shows what it did.\n ctx.notify();\n }\n executed.emit({ commandId: id, documentId: context.documentId, args });\n return { status: 'executed' };\n };\n\n const registerOne = (definition: CommandDef, options?: RegisterCommandOptions): Unsubscribe => {\n const taken = registered.has(definition.id) || configured().commands.has(definition.id);\n if (taken && !options?.replace) {\n throw new PluginError('conflict', 'commands', `duplicate command '${definition.id}'`);\n }\n const entry = registeredCommand(definition);\n registered.set(definition.id, entry);\n registeredChanged();\n return () => {\n // Own this registration only: a later replacement is not ours to remove.\n if (registered.get(definition.id) !== entry) return;\n registered.delete(definition.id);\n registeredChanged();\n };\n };\n\n const turningOff = createTurningOff(\n settings,\n (id) => entryOf(id)?.definition ?? null,\n isTurnedOff,\n );\n\n const api: CommandsHostCapability = {\n ...settings.api,\n registerCommand: registerOne,\n registerCommands: (definitions, options) => {\n const removers = definitions.map((definition) => registerOne(definition, options));\n return () => removers.forEach((remove) => remove());\n },\n hasCommand: (id) => entryOf(id) !== null,\n getCommand: (id) => entryOf(id)?.definition ?? null,\n listCommandIds: () => idsByDocument(''),\n resolveCommand,\n listCommands,\n searchCommands: (query, documentId) => {\n const needle = query.trim().toLowerCase();\n return listCommands(documentId).filter(\n (command) =>\n command.visible &&\n (needle === '' ||\n command.label.toLowerCase().includes(needle) ||\n command.id.includes(needle)),\n );\n },\n listShortcuts,\n execute,\n canExecute: (id, documentId) => {\n const resolved = resolveCommand(id, documentId);\n return !!resolved && resolved.enabled && resolved.visible;\n },\n getRefusal: (id, documentId) => {\n const entry = entryOf(id);\n return entry ? refusalOf(entry.definition, commandContext(documentId)) : null;\n },\n ...turningOff,\n onExecuted: executed.on,\n onExecutionFailed: executionFailed.on,\n // ── host lens ──\n matchStroke: (stroke: KeyStroke, options) => {\n let waiting: ShortcutMatch | null = null;\n let refused: ShortcutMatch | null = null;\n for (const entry of definedCommands()) {\n if (options.inTextField && !entry.definition.shortcutInTextFields) continue;\n if (!entry.parsed.some((shortcut) => matchShortcut(shortcut, stroke, options))) continue;\n const context = commandContext();\n const refusal = refusalOf(entry.definition, context);\n const visible = derive(entry.definition.visible, context, true);\n if (!refusal) {\n // Commands that share keys take turns: Escape cancels a drawing while there is one,\n // and lets a snapshot go while there is one.\n if (visible && derive(entry.definition.enabled, context, true)) {\n return { commandId: entry.definition.id, refusal: null };\n }\n waiting ??= { commandId: entry.definition.id, refusal: null };\n continue;\n }\n // A refused command takes its keys only where it would show: Delete with nothing\n // selected stays the page's, even where deleting is turned off.\n if (!visible) continue;\n refused ??= { commandId: entry.definition.id, refusal };\n }\n return waiting ?? refused;\n },\n getMenuTarget: (id) => {\n const entry = entryOf(id);\n return entry ? { menu: entry.definition.menu } : null;\n },\n };\n\n return { api };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { I18nToken } from '@embedpdf/plugin-i18n/contract';\nimport { ShellToken } from '@embedpdf/plugin-shell/contract';\n\nimport { COMMANDS_DEFAULTS, type CommandsConfig } from './contract';\nimport { createCommandsController } from './controller';\nimport { CommandsToken } from './host-contract';\n\n/**\n * The commands: one set for the whole workspace, each resolved and run for a\n * document (the one named, else the document in scope, else the active one).\n * Definitions are settings and app content, never state, since they hold\n * functions. `config` is the settings the app registers, over\n * {@link COMMANDS_DEFAULTS}.\n */\nexport const commandsPlugin = <AppState = any>(config?: CommandsConfig<AppState>) =>\n definePlugin({\n id: 'commands',\n scope: 'workspace',\n token: CommandsToken,\n // Labels come from i18n, and commands that open a panel, menu or dialog\n // go through shell; without them a label is the command's own, and those\n // commands open nothing.\n optional: [I18nToken, ShellToken],\n // Command definitions come from the app and may use any capability.\n resolvesAnyCapability: true,\n // Your app's state is replaced whole, never merged: a new value is the whole new state.\n settings: {\n defaults: COMMANDS_DEFAULTS,\n registered: config as CommandsConfig | undefined,\n whole: ['appState'],\n },\n create: createCommandsController,\n // Inside a document's scope, a call that leaves out the document is for that one.\n inScope: (commands, documentId) => ({\n ...commands,\n resolveCommand: (id, target = documentId) => commands.resolveCommand(id, target),\n listCommands: (target = documentId) => commands.listCommands(target),\n searchCommands: (query, target = documentId) => commands.searchCommands(query, target),\n execute: (id, options) =>\n commands.execute(id, { ...options, documentId: options?.documentId ?? documentId }),\n canExecute: (id, target = documentId) => commands.canExecute(id, target),\n getRefusal: (id, target = documentId) => commands.getRefusal(id, target),\n }),\n });\n"],"mappings":";;;;;;;;;AAWA,MAAa,qBAAqB,eAA8C;CAC9E,MAAM,YACJ,WAAW,aAAa,KAAA,IAAY,CAAC,IAAK,CAAC,CAAC,CAAc,OAAO,WAAW,QAAQ;CACtF,OAAO;EAAE;EAAY;EAAW,QAAQ,UAAU,IAAIA,kBAAAA,aAAa;CAAE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SAAS,eAAe,IAAI,MAAM;EAC/E,eAAe,SAAS,eAAe,SAAS,aAAa,MAAM;EACnE,iBAAiB,OAAO,SAAS,eAAe,SAAS,eAAe,OAAO,MAAM;EACrF,UAAU,IAAI,YACZ,SAAS,QAAQ,IAAI;GAAE,GAAG;GAAS,YAAY,SAAS,cAAc;EAAW,CAAC;EACpF,aAAa,IAAI,SAAS,eAAe,SAAS,WAAW,IAAI,MAAM;EACvE,aAAa,IAAI,SAAS,eAAe,SAAS,WAAW,IAAI,MAAM;CACzE;AACF,CAAC"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { C as CommandsToken, S as unregisteredCommand, _ as RegisterCommandOptions, a as CommandExecutedEvent, b as resolvedCommandsEqual, c as CommandId, d as CommandsConfig, f as CommandsSettings, g as NotAllowedMode, h as IconAccent, i as CommandDef, l as CommandRefusal, m as ExecuteResult, n as COMMANDS_DEFAULTS, o as CommandExecutionFailedEvent, p as ExecuteOptions, r as CommandContext, s as CommandFamily, t as BoundCommand, u as CommandsCapability, v as ResolvedCommand, x as unknownCommandWarning, y as boundCommandOf } from "./contract-lGfvyWMG.cjs";
|
|
2
|
-
import { t as CommandsHostCapability } from "./host-contract-
|
|
2
|
+
import { t as CommandsHostCapability } from "./host-contract-Db4TZ_JI.cjs";
|
|
3
3
|
//#region src/commands.plugin.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* The commands: one set for the whole workspace, each resolved and run for a
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { C as CommandsToken, S as unregisteredCommand, _ as RegisterCommandOptions, a as CommandExecutedEvent, b as resolvedCommandsEqual, c as CommandId, d as CommandsConfig, f as CommandsSettings, g as NotAllowedMode, h as IconAccent, i as CommandDef, l as CommandRefusal, m as ExecuteResult, n as COMMANDS_DEFAULTS, o as CommandExecutionFailedEvent, p as ExecuteOptions, r as CommandContext, s as CommandFamily, t as BoundCommand, u as CommandsCapability, v as ResolvedCommand, x as unknownCommandWarning, y as boundCommandOf } from "./contract-lGfvyWMG.js";
|
|
2
|
-
import { t as CommandsHostCapability } from "./host-contract-
|
|
2
|
+
import { t as CommandsHostCapability } from "./host-contract-B58WiZ-H.js";
|
|
3
3
|
//#region src/commands.plugin.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* The commands: one set for the whole workspace, each resolved and run for a
|
package/dist/index.js
CHANGED
|
@@ -486,23 +486,32 @@ function createCommandsController(ctx) {
|
|
|
486
486
|
onExecuted: executed.on,
|
|
487
487
|
onExecutionFailed: executionFailed.on,
|
|
488
488
|
matchStroke: (stroke, options) => {
|
|
489
|
+
let waiting = null;
|
|
489
490
|
let refused = null;
|
|
490
491
|
for (const entry of definedCommands()) {
|
|
491
492
|
if (options.inTextField && !entry.definition.shortcutInTextFields) continue;
|
|
492
493
|
if (!entry.parsed.some((shortcut) => matchShortcut(shortcut, stroke, options))) continue;
|
|
493
494
|
const context = commandContext();
|
|
494
495
|
const refusal = refusalOf(entry.definition, context);
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
496
|
+
const visible = derive(entry.definition.visible, context, true);
|
|
497
|
+
if (!refusal) {
|
|
498
|
+
if (visible && derive(entry.definition.enabled, context, true)) return {
|
|
499
|
+
commandId: entry.definition.id,
|
|
500
|
+
refusal: null
|
|
501
|
+
};
|
|
502
|
+
waiting ?? (waiting = {
|
|
503
|
+
commandId: entry.definition.id,
|
|
504
|
+
refusal: null
|
|
505
|
+
});
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
if (!visible) continue;
|
|
500
509
|
refused ?? (refused = {
|
|
501
510
|
commandId: entry.definition.id,
|
|
502
511
|
refusal
|
|
503
512
|
});
|
|
504
513
|
}
|
|
505
|
-
return refused;
|
|
514
|
+
return waiting ?? refused;
|
|
506
515
|
},
|
|
507
516
|
getMenuTarget: (id) => {
|
|
508
517
|
const entry = entryOf(id);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["CommandsToken"],"sources":["../src/registry.ts","../src/services/availability.ts","../src/write/turning-off.ts","../src/controller.ts","../src/commands.plugin.ts"],"sourcesContent":["/** A command definition with its shortcuts parsed once, and how the registry tells a family apart. */\nimport { parseShortcut, type ParsedShortcut } from '@embedpdf/core-ui';\n\nimport type { CommandDef, CommandFamily } from './contract';\n\nexport interface RegisteredCommand {\n readonly definition: CommandDef;\n readonly shortcuts: readonly string[];\n readonly parsed: readonly ParsedShortcut[];\n}\n\nexport const registeredCommand = (definition: CommandDef): RegisteredCommand => {\n const shortcuts =\n definition.shortcut === undefined ? [] : ([] as string[]).concat(definition.shortcut);\n return { definition, shortcuts, parsed: shortcuts.map(parseShortcut) };\n};\n\nexport const isCommandFamily = (item: CommandDef | CommandFamily): item is CommandFamily =>\n 'prefix' in item;\n\n/** The commands the settings define, by id (a later id replaces an earlier one), and their families. */\nexport interface ConfiguredCommands {\n readonly commands: ReadonlyMap<string, RegisteredCommand>;\n readonly families: readonly CommandFamily[];\n}\n\nexport function configuredCommands(\n items: readonly (CommandDef | CommandFamily)[],\n): ConfiguredCommands {\n const commands = new Map<string, RegisteredCommand>();\n const families: CommandFamily[] = [];\n for (const item of items) {\n if (isCommandFamily(item)) families.push(item);\n else commands.set(item.id, registeredCommand(item));\n }\n return { commands, families };\n}\n","/**\n * Whether a command is there at all, apart from what it says about the\n * moment (`enabled`, `visible`): turned off in this viewer (its id, or one of\n * its categories), not allowed for its document (the scope's `requires`, or\n * the plugins' checks in `allowed`), or held by a lock on the setting it\n * changes (`locked`), and the sentence that says why, translated when the\n * i18n plugin is there.\n */\nimport type {\n DocumentHandle,\n Permission,\n PluginContext,\n SettingLock,\n Settings,\n} from '@embedpdf/core';\nimport { I18nToken } from '@embedpdf/plugin-i18n/contract';\n\nimport type { CommandContext, CommandDef, CommandRefusal, CommandsSettings } from '../contract';\n\n/**\n * Whether a category is off: it, or a category it's under, is in the list. Parts are whole\n * dotted segments, so `annotations` covers `annotations.highlight` and not `annotationsExtra`.\n */\nexport const isCategoryOff = (category: string, disabled: readonly string[]): boolean =>\n disabled.some((off) => category === off || category.startsWith(`${off}.`));\n\n/**\n * The label: a language's string under the command's id, else under its `labelKey` (the current\n * language, then the fallback one), else `label`, else the id. So a string for\n * `'document:download'` relabels that one command, whichever key its label is under.\n */\nexport const labelOf = (definition: CommandDef, context: CommandContext): string => {\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return definition.label ?? definition.labelKey ?? definition.id;\n const fallbackKey = definition.labelKey ? { fallbackKey: definition.labelKey } : {};\n // A command with a key and no label of its own warns once when no language has the key.\n return definition.label === undefined && definition.labelKey\n ? i18n.t(definition.id, fallbackKey)\n : i18n.t(definition.id, { ...fallbackKey, fallback: definition.label ?? definition.id });\n};\n\n/**\n * Whether a document's session holds a permission: what `ctx.allows` answers for a\n * document-scoped plugin, asked here of the command's document, since the commands are one\n * set for the whole workspace.\n */\nconst sessionHolds = (security: DocumentHandle['security'], permission: Permission): boolean =>\n permission === 'annotations:create'\n ? security.allowsAnnotation('create')\n : security.allows(permission);\n\n/** Where a language keeps the sentence for a permission: `commands.notAllowed.doc-text-copy`. */\nconst permissionKeyOf = (permission: Permission): string =>\n `commands.notAllowed.${permission.replace(/[.:]/g, '-')}`;\n\n/** The general sentence's key: `{label} isn't allowed`. */\nconst DEFAULT_NOT_ALLOWED_KEY = 'commands.notAllowed.default';\n\n/** The sentence for a command the session may not run, under `key`, else the general one. */\nexport const notAllowedMessage = (key: string, label: string, context: CommandContext): string => {\n const fallback = `${label} isn't allowed`;\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return fallback;\n const params = { label };\n return i18n.t(key, {\n params,\n fallback: i18n.t(DEFAULT_NOT_ALLOWED_KEY, { params, fallback }),\n });\n};\n\n/** The general locked sentence's key: `{label} can't be changed in this document`. */\nconst DEFAULT_LOCKED_KEY = 'commands.locked.default';\n\n/** The sentence for a command whose setting a lock holds: its `reasonKey`, else the general one. */\nexport const lockedMessage = (\n lock: SettingLock,\n label: string,\n context: CommandContext,\n): string => {\n const fallback = `${label} can't be changed in this document`;\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return fallback;\n const params = { label };\n const general = i18n.t(DEFAULT_LOCKED_KEY, { params, fallback });\n return lock.reasonKey === undefined\n ? general\n : i18n.t(lock.reasonKey, { params, fallback: general });\n};\n\n/** The sentence for a command that's turned off. */\nconst turnedOffMessage = (label: string, context: CommandContext): string => {\n const i18n = context.tryGet(I18nToken);\n return i18n\n ? i18n.t('commands.turnedOff', { params: { label }, fallback: \"{label} isn't available\" })\n : `${label} isn't available`;\n};\n\nexport function createAvailability(\n ctx: PluginContext<void, CommandsSettings>,\n settings: Settings<CommandsSettings>,\n) {\n /** Whether a command is turned off: by its id, or through one of its categories. */\n const isTurnedOff = (definition: CommandDef): boolean => {\n const { disabledCategories, disabledCommands } = settings.get();\n return (\n disabledCommands.includes(definition.id) ||\n (definition.categories ?? []).some((category) => isCategoryOff(category, disabledCategories))\n );\n };\n\n /** Whether a command's `allowed` check says yes; one that throws allows it. */\n const passesCheck = (definition: CommandDef, context: CommandContext): boolean => {\n if (!definition.allowed) return true;\n try {\n return definition.allowed(context);\n } catch {\n return true;\n }\n };\n\n /** The lock on the setting a command changes, or `null`; a `locked` that throws is no lock. */\n const lockOf = (definition: CommandDef, context: CommandContext): SettingLock | null => {\n if (!definition.locked) return null;\n try {\n return definition.locked(context);\n } catch {\n return null;\n }\n };\n\n /**\n * Why its document's session may not run a command, as the key of the sentence that says\n * so, or `null` when it may: the first permission `requires` names that the session doesn't\n * hold (`commands.notAllowed.doc-print`), else its `allowed` check saying no (its\n * `notAllowedKey`). With no document open there is no session to ask, and nothing is refused.\n */\n const notAllowedKeyOf = (definition: CommandDef, context: CommandContext): string | null => {\n if (!definition.requires?.length && !definition.allowed) return null;\n const handle = context.documentId === null ? null : ctx.documentHandle(context.documentId);\n if (!handle) return null;\n const missing = definition.requires?.find(\n (permission) => !sessionHolds(handle.security, permission),\n );\n if (missing !== undefined) return permissionKeyOf(missing);\n return passesCheck(definition, context)\n ? null\n : (definition.notAllowedKey ?? DEFAULT_NOT_ALLOWED_KEY);\n };\n\n /** Why a command won't run whatever the moment, or `null` when it may run. */\n const refusalOf = (definition: CommandDef, context: CommandContext): CommandRefusal | null => {\n if (isTurnedOff(definition)) {\n return {\n reason: 'turned-off',\n message: turnedOffMessage(labelOf(definition, context), context),\n };\n }\n const notAllowed = notAllowedKeyOf(definition, context);\n if (notAllowed !== null) {\n return {\n reason: 'not-allowed',\n message: notAllowedMessage(notAllowed, labelOf(definition, context), context),\n };\n }\n const lock = lockOf(definition, context);\n return lock === null\n ? null\n : { reason: 'locked', message: lockedMessage(lock, labelOf(definition, context), context) };\n };\n\n return { isTurnedOff, notAllowedKeyOf, lockOf, refusalOf };\n}\n","/**\n * Turning commands off and on: by category, with every category under it, and\n * one by one. Both lists are settings, so they change live and\n * `resetSettings()` restores what the app registered.\n */\nimport type { Settings } from '@embedpdf/core';\n\nimport type { CommandDef, CommandsCapability, CommandsSettings } from '../contract';\nimport { isCategoryOff } from '../services/availability';\n\ntype OffList = 'disabledCategories' | 'disabledCommands';\n\nexport function createTurningOff(\n settings: Settings<CommandsSettings>,\n definitionOf: (id: string) => CommandDef | null,\n isTurnedOff: (definition: CommandDef) => boolean,\n) {\n const listOf = (list: OffList): readonly string[] => settings.get()[list];\n const replace = (list: OffList, names: readonly string[]): void =>\n settings.api.updateSettings(\n list === 'disabledCategories'\n ? { disabledCategories: [...names] }\n : { disabledCommands: [...names] },\n );\n // Adding a name that's there, or removing one that isn't, changes nothing and fires nothing.\n const add = (list: OffList, name: string): void => {\n const current = listOf(list);\n if (!current.includes(name)) replace(list, [...current, name]);\n };\n const remove = (list: OffList, name: string): void => {\n const current = listOf(list);\n if (current.includes(name))\n replace(\n list,\n current.filter((other) => other !== name),\n );\n };\n\n return {\n getDisabledCategories: () => listOf('disabledCategories'),\n isCategoryDisabled: (category) => isCategoryOff(category, listOf('disabledCategories')),\n disableCategory: (category) => add('disabledCategories', category),\n enableCategory: (category) => remove('disabledCategories', category),\n setDisabledCategories: (categories) => replace('disabledCategories', categories),\n getDisabledCommands: () => listOf('disabledCommands'),\n isCommandDisabled: (id) => {\n const definition = definitionOf(id);\n return definition ? isTurnedOff(definition) : listOf('disabledCommands').includes(id);\n },\n disableCommand: (id) => add('disabledCommands', id),\n enableCommand: (id) => remove('disabledCommands', id),\n setDisabledCommands: (ids) => replace('disabledCommands', ids),\n } satisfies Partial<CommandsCapability>;\n}\n","/**\n * The commands controller: the commands (from the settings, added while the\n * app runs, and from families), resolution for a document (derivations over\n * live state, safe to throw), the one way to run a command, turning commands\n * off (by category and one by one), what the session may run (the scope's\n * `requires`, the plugins' checks in `allowed`), and the host-only keystroke\n * matcher.\n *\n * Definitions hold functions, so the commands added while the app runs are a\n * map outside state; every change to it calls `ctx.notify()` so readers read\n * again.\n */\nimport {\n DocumentsToken,\n isPluginError,\n memo,\n memoByKey,\n PluginError,\n toPluginError,\n toPluginErrorInfo,\n type CapabilityToken,\n type PluginContext,\n type Unsubscribe,\n} from '@embedpdf/core';\nimport { matchShortcut, type KeyStroke } from '@embedpdf/core-ui';\nimport { ShellToken } from '@embedpdf/plugin-shell/contract';\n\nimport type {\n CommandContext,\n CommandDef,\n CommandExecutedEvent,\n CommandExecutionFailedEvent,\n CommandFamily,\n CommandsSettings,\n ExecuteOptions,\n ExecuteResult,\n IconAccent,\n RegisterCommandOptions,\n ResolvedCommand,\n} from './contract';\nimport type { CommandsHostCapability, ShortcutMatch } from './host-contract';\nimport {\n configuredCommands,\n registeredCommand,\n type ConfiguredCommands,\n type RegisteredCommand,\n} from './registry';\nimport {\n createAvailability,\n labelOf,\n lockedMessage,\n notAllowedMessage,\n} from './services/availability';\nimport { createTurningOff } from './write/turning-off';\n\nconst panelTarget = (\n definition: CommandDef,\n): { id: string; exclusive?: string; focus?: boolean } | null =>\n definition.panel === undefined\n ? null\n : typeof definition.panel === 'string'\n ? { id: definition.panel }\n : definition.panel;\n\n/**\n * One command's live derivations for a document, as values a memo can\n * compare: the entry, label, accent colors, the enabled/active/visible flags,\n * and why it's disabled when the scope doesn't allow it.\n */\ntype Derivations = readonly [\n entry: RegisteredCommand | null,\n label: string,\n accentPrimary: string | undefined,\n accentSecondary: string | undefined,\n enabled: boolean,\n active: boolean,\n visible: boolean,\n disabledReason: string | undefined,\n];\n\nconst NOT_REGISTERED: Derivations = [\n null,\n '',\n undefined,\n undefined,\n false,\n false,\n false,\n undefined,\n];\nconst NO_NAMES: readonly string[] = [];\n\nconst accentOf = (primary?: string, secondary?: string): IconAccent | undefined =>\n primary === undefined && secondary === undefined\n ? undefined\n : {\n ...(primary !== undefined ? { primary } : {}),\n ...(secondary !== undefined ? { secondary } : {}),\n };\n\n/** The memo key of a resolution: the command id and the document named, if any. */\nconst resolutionKey = (id: string, documentId: string | undefined): string =>\n JSON.stringify([id, documentId ?? null]);\n\nexport function createCommandsController(ctx: PluginContext<void, CommandsSettings>) {\n const settings = ctx.settings();\n\n /** Commands added while the app runs, in the order they were added. */\n const registered = new Map<string, RegisteredCommand>();\n /** Bumped on every change to `registered`: the input of the reads built from it. */\n let registeredVersion = 0;\n const registeredChanged = (): void => {\n registeredVersion += 1;\n ctx.notify();\n };\n\n /** The commands the settings define, rebuilt when the setting changes. */\n const configured = memo(\n () => [settings.get().commands],\n (items): ConfiguredCommands => configuredCommands(items),\n );\n\n const executed = ctx.events.source<CommandExecutedEvent>();\n const executionFailed = ctx.events.source<CommandExecutionFailedEvent>();\n\n /** Capabilities for the command's document: the one named, else the active one. */\n const commandContext = (\n documentId?: string,\n call: { args?: unknown; signal?: AbortSignal } = {},\n ): CommandContext => {\n const target = documentId ?? ctx.get(DocumentsToken).getActiveId();\n const get = <T>(token: CapabilityToken<T>): T =>\n target ? ctx.forDocument(token, target) : ctx.get(token);\n return {\n documentId: target,\n appState: settings.get().appState,\n ...(call.args === undefined ? {} : { args: call.args }),\n ...(call.signal ? { signal: call.signal } : {}),\n get,\n tryGet: <T>(token: CapabilityToken<T>): T | null => {\n try {\n return get(token);\n } catch {\n return null;\n }\n },\n };\n };\n\n /** A family's command for one name, made once so it keeps its identity. */\n const familyCommands = new WeakMap<CommandFamily, Map<string, RegisteredCommand>>();\n const familyCommand = (family: CommandFamily, name: string): RegisteredCommand => {\n let byName = familyCommands.get(family);\n if (!byName) {\n byName = new Map();\n familyCommands.set(family, byName);\n }\n let entry = byName.get(name);\n if (!entry) {\n entry = registeredCommand({ ...family.command(name), id: `${family.prefix}${name}` });\n byName.set(name, entry);\n }\n return entry;\n };\n\n /** The command with this id: one added while the app runs, else the settings', else a family's. */\n const entryOf = (id: string): RegisteredCommand | null => {\n const { commands, families } = configured();\n const entry = registered.get(id) ?? commands.get(id);\n if (entry) return entry;\n const family = families.find(\n (candidate) => id.startsWith(candidate.prefix) && id.length > candidate.prefix.length,\n );\n return family ? familyCommand(family, id.slice(family.prefix.length)) : null;\n };\n\n /** Every command with its own definition (not a family's), each id once. */\n const definedCommands = memo(\n () => [registeredVersion, configured()],\n (_version, { commands }) => {\n const entries = new Map(commands);\n for (const [id, entry] of registered) entries.set(id, entry);\n return [...entries.values()];\n },\n );\n\n // Derivations run against live state: without one, the command is what\n // `absent` says; one that throws (it needs a document and none is open, say)\n // says no, so the button renders disabled, not pressed or hidden instead of\n // breaking.\n const derive = (\n derivation: ((context: CommandContext) => boolean) | undefined,\n context: CommandContext,\n absent: boolean,\n ): boolean => {\n if (!derivation) return absent;\n try {\n return derivation(context);\n } catch {\n return false;\n }\n };\n const deriveAccent = (\n derivation: ((context: CommandContext) => IconAccent | null) | undefined,\n context: CommandContext,\n ): IconAccent | undefined => {\n if (!derivation) return undefined;\n try {\n return derivation(context) ?? undefined;\n } catch {\n return undefined;\n }\n };\n const namesOf = (family: CommandFamily, context: CommandContext): readonly string[] => {\n try {\n return family.names(context);\n } catch {\n return NO_NAMES;\n }\n };\n\n const { isTurnedOff, notAllowedKeyOf, lockOf, refusalOf } = createAvailability(ctx, settings);\n\n const derivationsOf = (entry: RegisteredCommand, documentId?: string): Derivations => {\n const { definition } = entry;\n const context = commandContext(documentId);\n const label = labelOf(definition, context);\n // Turned off hides it; not allowed hides it, or disables it with the reason; a lock on the\n // setting it changes disables it with the lock's reason, whatever `notAllowed` says.\n const turnedOff = isTurnedOff(definition);\n const notAllowed = turnedOff ? null : notAllowedKeyOf(definition, context);\n const shownWhenNotAllowed = settings.get().notAllowed === 'disable';\n const lock = turnedOff || notAllowed !== null ? null : lockOf(definition, context);\n const ruledOut = turnedOff || notAllowed !== null || lock !== null;\n // A command that opens something is active while it's open, unless it says otherwise.\n let active: boolean;\n if (definition.active) {\n active = derive(definition.active, context, false);\n } else {\n const shell = context.tryGet(ShellToken);\n const panel = panelTarget(definition);\n active = shell\n ? definition.menu\n ? shell.isMenuOpen(definition.menu)\n : panel\n ? shell.isOpen(panel.id)\n : definition.modal\n ? shell.isOpen(definition.modal)\n : false\n : false;\n }\n const accent = deriveAccent(definition.iconAccent, context);\n return [\n entry,\n label,\n accent?.primary,\n accent?.secondary,\n !ruledOut && derive(definition.enabled, context, true),\n active,\n !turnedOff &&\n (notAllowed === null || shownWhenNotAllowed) &&\n derive(definition.visible, context, true),\n notAllowed !== null && shownWhenNotAllowed\n ? notAllowedMessage(notAllowed, label, context)\n : lock !== null\n ? lockedMessage(lock, label, context)\n : undefined,\n ];\n };\n\n /** A resolved command, the same object until one of its derivations or its entry changes. */\n const resolvedByKey = memoByKey(\n (key: string): Derivations => {\n const [id, documentId] = JSON.parse(key) as [string, string | null];\n const entry = entryOf(id);\n return entry ? derivationsOf(entry, documentId ?? undefined) : NOT_REGISTERED;\n },\n (\n _key,\n entry,\n label,\n accentPrimary,\n accentSecondary,\n enabled,\n active,\n visible,\n disabledReason,\n ): ResolvedCommand | null =>\n entry && {\n id: entry.definition.id,\n label,\n icon: entry.definition.icon,\n iconAccent: accentOf(accentPrimary, accentSecondary),\n shortcuts: entry.shortcuts,\n menu: entry.definition.menu,\n enabled,\n active,\n visible,\n categories: entry.definition.categories ?? [],\n ...(disabledReason === undefined ? {} : { disabledReason }),\n },\n );\n const resolveCommand = (id: string, documentId?: string): ResolvedCommand | null =>\n entryOf(id) ? resolvedByKey(resolutionKey(id, documentId)) : null;\n\n /**\n * Every command's id for a document (`''` is the active one): the defined ones in the order\n * they were added, then each family's names that no defined command took.\n */\n const idsByDocument = memoByKey(\n (documentKey: string): readonly unknown[] => {\n const config = configured();\n const context = commandContext(documentKey || undefined);\n return [\n definedCommands(),\n config,\n ...config.families.map((family) => namesOf(family, context)),\n ];\n },\n (_documentKey, ...inputs): readonly string[] => {\n const [defined, { families }, ...names] = inputs as [\n readonly RegisteredCommand[],\n ConfiguredCommands,\n ...(readonly string[])[],\n ];\n const ids = defined.map((entry) => entry.definition.id);\n const taken = new Set(ids);\n families.forEach((family, index) => {\n for (const name of names[index] ?? NO_NAMES) {\n const id = `${family.prefix}${name}`;\n if (taken.has(id)) continue;\n taken.add(id);\n ids.push(id);\n }\n });\n return ids;\n },\n );\n const commandsByDocument = memoByKey(\n (documentKey: string) =>\n idsByDocument(documentKey).map((id) => resolveCommand(id, documentKey || undefined)),\n (_documentKey, ...resolved) =>\n resolved.filter((command): command is ResolvedCommand => command !== null),\n );\n const listCommands = (documentId?: string): readonly ResolvedCommand[] =>\n commandsByDocument(documentId ?? '');\n\n const listShortcuts = memo(\n () => [definedCommands()],\n (entries) =>\n entries.flatMap((entry) =>\n entry.shortcuts.map((shortcut) => ({ commandId: entry.definition.id, shortcut })),\n ),\n );\n\n /** What running a command does: its `run`, or opening what it opens. */\n const runCommand = async (definition: CommandDef, context: CommandContext): Promise<void> => {\n if (definition.run) {\n await definition.run(context);\n return;\n }\n const shell = context.tryGet(ShellToken);\n const panel = panelTarget(definition);\n if (!shell) return;\n if (definition.menu) shell.toggleMenu(definition.menu);\n else if (panel) shell.toggle(panel.id, { exclusive: panel.exclusive, focus: panel.focus });\n else if (definition.modal) shell.toggle(definition.modal, { exclusive: 'modal' });\n };\n\n const execute = async (id: string, options: ExecuteOptions = {}): Promise<ExecuteResult> => {\n const { signal, documentId, args } = options;\n if (signal?.aborted) {\n throw new PluginError('operation-cancelled', 'commands', 'operation cancelled');\n }\n const entry = entryOf(id);\n if (!entry) return { status: 'rejected', reason: 'not-found' };\n const resolved = resolveCommand(id, documentId);\n if (!resolved?.visible) return { status: 'rejected', reason: 'hidden' };\n if (!resolved.enabled) return { status: 'rejected', reason: 'disabled' };\n const context = commandContext(documentId, { args, signal });\n try {\n await ctx.cancellable(signal, runCommand(entry.definition, context));\n } catch (error) {\n // The caller cancelling isn't the command failing.\n if (signal?.aborted && isPluginError(error, 'operation-cancelled')) throw error;\n const failure = toPluginError('commands', error);\n executionFailed.emit({\n commandId: id,\n documentId: context.documentId,\n error: toPluginErrorInfo(failure),\n });\n throw failure;\n } finally {\n // A run may change what the commands read outside the viewer (your app's state): every\n // button asks its command again, so the one just pressed shows what it did.\n ctx.notify();\n }\n executed.emit({ commandId: id, documentId: context.documentId, args });\n return { status: 'executed' };\n };\n\n const registerOne = (definition: CommandDef, options?: RegisterCommandOptions): Unsubscribe => {\n const taken = registered.has(definition.id) || configured().commands.has(definition.id);\n if (taken && !options?.replace) {\n throw new PluginError('conflict', 'commands', `duplicate command '${definition.id}'`);\n }\n const entry = registeredCommand(definition);\n registered.set(definition.id, entry);\n registeredChanged();\n return () => {\n // Own this registration only: a later replacement is not ours to remove.\n if (registered.get(definition.id) !== entry) return;\n registered.delete(definition.id);\n registeredChanged();\n };\n };\n\n const turningOff = createTurningOff(\n settings,\n (id) => entryOf(id)?.definition ?? null,\n isTurnedOff,\n );\n\n const api: CommandsHostCapability = {\n ...settings.api,\n registerCommand: registerOne,\n registerCommands: (definitions, options) => {\n const removers = definitions.map((definition) => registerOne(definition, options));\n return () => removers.forEach((remove) => remove());\n },\n hasCommand: (id) => entryOf(id) !== null,\n getCommand: (id) => entryOf(id)?.definition ?? null,\n listCommandIds: () => idsByDocument(''),\n resolveCommand,\n listCommands,\n searchCommands: (query, documentId) => {\n const needle = query.trim().toLowerCase();\n return listCommands(documentId).filter(\n (command) =>\n command.visible &&\n (needle === '' ||\n command.label.toLowerCase().includes(needle) ||\n command.id.includes(needle)),\n );\n },\n listShortcuts,\n execute,\n canExecute: (id, documentId) => {\n const resolved = resolveCommand(id, documentId);\n return !!resolved && resolved.enabled && resolved.visible;\n },\n getRefusal: (id, documentId) => {\n const entry = entryOf(id);\n return entry ? refusalOf(entry.definition, commandContext(documentId)) : null;\n },\n ...turningOff,\n onExecuted: executed.on,\n onExecutionFailed: executionFailed.on,\n // ── host lens ──\n matchStroke: (stroke: KeyStroke, options) => {\n let refused: ShortcutMatch | null = null;\n for (const entry of definedCommands()) {\n if (options.inTextField && !entry.definition.shortcutInTextFields) continue;\n if (!entry.parsed.some((shortcut) => matchShortcut(shortcut, stroke, options))) continue;\n const context = commandContext();\n const refusal = refusalOf(entry.definition, context);\n if (!refusal) return { commandId: entry.definition.id, refusal: null };\n // A refused command takes its keys only where it would show: Delete with nothing\n // selected stays the page's, even where deleting is turned off.\n if (!derive(entry.definition.visible, context, true)) continue;\n refused ??= { commandId: entry.definition.id, refusal };\n }\n return refused;\n },\n getMenuTarget: (id) => {\n const entry = entryOf(id);\n return entry ? { menu: entry.definition.menu } : null;\n },\n };\n\n return { api };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { I18nToken } from '@embedpdf/plugin-i18n/contract';\nimport { ShellToken } from '@embedpdf/plugin-shell/contract';\n\nimport { COMMANDS_DEFAULTS, type CommandsConfig } from './contract';\nimport { createCommandsController } from './controller';\nimport { CommandsToken } from './host-contract';\n\n/**\n * The commands: one set for the whole workspace, each resolved and run for a\n * document (the one named, else the document in scope, else the active one).\n * Definitions are settings and app content, never state, since they hold\n * functions. `config` is the settings the app registers, over\n * {@link COMMANDS_DEFAULTS}.\n */\nexport const commandsPlugin = <AppState = any>(config?: CommandsConfig<AppState>) =>\n definePlugin({\n id: 'commands',\n scope: 'workspace',\n token: CommandsToken,\n // Labels come from i18n, and commands that open a panel, menu or dialog\n // go through shell; without them a label is the command's own, and those\n // commands open nothing.\n optional: [I18nToken, ShellToken],\n // Command definitions come from the app and may use any capability.\n resolvesAnyCapability: true,\n // Your app's state is replaced whole, never merged: a new value is the whole new state.\n settings: {\n defaults: COMMANDS_DEFAULTS,\n registered: config as CommandsConfig | undefined,\n whole: ['appState'],\n },\n create: createCommandsController,\n // Inside a document's scope, a call that leaves out the document is for that one.\n inScope: (commands, documentId) => ({\n ...commands,\n resolveCommand: (id, target = documentId) => commands.resolveCommand(id, target),\n listCommands: (target = documentId) => commands.listCommands(target),\n searchCommands: (query, target = documentId) => commands.searchCommands(query, target),\n execute: (id, options) =>\n commands.execute(id, { ...options, documentId: options?.documentId ?? documentId }),\n canExecute: (id, target = documentId) => commands.canExecute(id, target),\n getRefusal: (id, target = documentId) => commands.getRefusal(id, target),\n }),\n });\n"],"mappings":";;;;;;;;AAWA,MAAa,qBAAqB,eAA8C;CAC9E,MAAM,YACJ,WAAW,aAAa,KAAA,IAAY,CAAC,IAAK,CAAC,CAAC,CAAc,OAAO,WAAW,QAAQ;CACtF,OAAO;EAAE;EAAY;EAAW,QAAQ,UAAU,IAAI,aAAa;CAAE;AACvE;AAEA,MAAa,mBAAmB,SAC9B,YAAY;AAQd,SAAgB,mBACd,OACoB;CACpB,MAAM,2BAAW,IAAI,IAA+B;CACpD,MAAM,WAA4B,CAAC;CACnC,KAAK,MAAM,QAAQ,OACjB,IAAI,gBAAgB,IAAI,GAAG,SAAS,KAAK,IAAI;MACxC,SAAS,IAAI,KAAK,IAAI,kBAAkB,IAAI,CAAC;CAEpD,OAAO;EAAE;EAAU;CAAS;AAC9B;;;;;;;ACbA,MAAa,iBAAiB,UAAkB,aAC9C,SAAS,MAAM,QAAQ,aAAa,OAAO,SAAS,WAAW,GAAG,IAAI,EAAE,CAAC;;;;;;AAO3E,MAAa,WAAW,YAAwB,YAAoC;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AK,IAAI;EACnD;CAGS,EAAE;AACf;;;;;;;;;;ACldA,MAAa,kBAAkC,WAC7C,aAAa;CACX,IAAI;CACJ,OAAO;CACP,OAAOA;CAIP,UAAU,CAAC,WAAW,UAAU;CAEhC,uBAAuB;CAEvB,UAAU;EACR,UAAU;EACV,YAAY;EACZ,OAAO,CAAC,UAAU;CACpB;CACA,QAAQ;CAER,UAAU,UAAU,gBAAgB;EAClC,GAAG;EACH,iBAAiB,IAAI,SAAS,eAAe,SAAS,eAAe,IAAI,MAAM;EAC/E,eAAe,SAAS,eAAe,SAAS,aAAa,MAAM;EACnE,iBAAiB,OAAO,SAAS,eAAe,SAAS,eAAe,OAAO,MAAM;EACrF,UAAU,IAAI,YACZ,SAAS,QAAQ,IAAI;GAAE,GAAG;GAAS,YAAY,SAAS,cAAc;EAAW,CAAC;EACpF,aAAa,IAAI,SAAS,eAAe,SAAS,WAAW,IAAI,MAAM;EACvE,aAAa,IAAI,SAAS,eAAe,SAAS,WAAW,IAAI,MAAM;CACzE;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["CommandsToken"],"sources":["../src/registry.ts","../src/services/availability.ts","../src/write/turning-off.ts","../src/controller.ts","../src/commands.plugin.ts"],"sourcesContent":["/** A command definition with its shortcuts parsed once, and how the registry tells a family apart. */\nimport { parseShortcut, type ParsedShortcut } from '@embedpdf/core-ui';\n\nimport type { CommandDef, CommandFamily } from './contract';\n\nexport interface RegisteredCommand {\n readonly definition: CommandDef;\n readonly shortcuts: readonly string[];\n readonly parsed: readonly ParsedShortcut[];\n}\n\nexport const registeredCommand = (definition: CommandDef): RegisteredCommand => {\n const shortcuts =\n definition.shortcut === undefined ? [] : ([] as string[]).concat(definition.shortcut);\n return { definition, shortcuts, parsed: shortcuts.map(parseShortcut) };\n};\n\nexport const isCommandFamily = (item: CommandDef | CommandFamily): item is CommandFamily =>\n 'prefix' in item;\n\n/** The commands the settings define, by id (a later id replaces an earlier one), and their families. */\nexport interface ConfiguredCommands {\n readonly commands: ReadonlyMap<string, RegisteredCommand>;\n readonly families: readonly CommandFamily[];\n}\n\nexport function configuredCommands(\n items: readonly (CommandDef | CommandFamily)[],\n): ConfiguredCommands {\n const commands = new Map<string, RegisteredCommand>();\n const families: CommandFamily[] = [];\n for (const item of items) {\n if (isCommandFamily(item)) families.push(item);\n else commands.set(item.id, registeredCommand(item));\n }\n return { commands, families };\n}\n","/**\n * Whether a command is there at all, apart from what it says about the\n * moment (`enabled`, `visible`): turned off in this viewer (its id, or one of\n * its categories), not allowed for its document (the scope's `requires`, or\n * the plugins' checks in `allowed`), or held by a lock on the setting it\n * changes (`locked`), and the sentence that says why, translated when the\n * i18n plugin is there.\n */\nimport type {\n DocumentHandle,\n Permission,\n PluginContext,\n SettingLock,\n Settings,\n} from '@embedpdf/core';\nimport { I18nToken } from '@embedpdf/plugin-i18n/contract';\n\nimport type { CommandContext, CommandDef, CommandRefusal, CommandsSettings } from '../contract';\n\n/**\n * Whether a category is off: it, or a category it's under, is in the list. Parts are whole\n * dotted segments, so `annotations` covers `annotations.highlight` and not `annotationsExtra`.\n */\nexport const isCategoryOff = (category: string, disabled: readonly string[]): boolean =>\n disabled.some((off) => category === off || category.startsWith(`${off}.`));\n\n/**\n * The label: a language's string under the command's id, else under its `labelKey` (the current\n * language, then the fallback one), else `label`, else the id. So a string for\n * `'document:download'` relabels that one command, whichever key its label is under.\n */\nexport const labelOf = (definition: CommandDef, context: CommandContext): string => {\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return definition.label ?? definition.labelKey ?? definition.id;\n const fallbackKey = definition.labelKey ? { fallbackKey: definition.labelKey } : {};\n // A command with a key and no label of its own warns once when no language has the key.\n return definition.label === undefined && definition.labelKey\n ? i18n.t(definition.id, fallbackKey)\n : i18n.t(definition.id, { ...fallbackKey, fallback: definition.label ?? definition.id });\n};\n\n/**\n * Whether a document's session holds a permission: what `ctx.allows` answers for a\n * document-scoped plugin, asked here of the command's document, since the commands are one\n * set for the whole workspace.\n */\nconst sessionHolds = (security: DocumentHandle['security'], permission: Permission): boolean =>\n permission === 'annotations:create'\n ? security.allowsAnnotation('create')\n : security.allows(permission);\n\n/** Where a language keeps the sentence for a permission: `commands.notAllowed.doc-text-copy`. */\nconst permissionKeyOf = (permission: Permission): string =>\n `commands.notAllowed.${permission.replace(/[.:]/g, '-')}`;\n\n/** The general sentence's key: `{label} isn't allowed`. */\nconst DEFAULT_NOT_ALLOWED_KEY = 'commands.notAllowed.default';\n\n/** The sentence for a command the session may not run, under `key`, else the general one. */\nexport const notAllowedMessage = (key: string, label: string, context: CommandContext): string => {\n const fallback = `${label} isn't allowed`;\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return fallback;\n const params = { label };\n return i18n.t(key, {\n params,\n fallback: i18n.t(DEFAULT_NOT_ALLOWED_KEY, { params, fallback }),\n });\n};\n\n/** The general locked sentence's key: `{label} can't be changed in this document`. */\nconst DEFAULT_LOCKED_KEY = 'commands.locked.default';\n\n/** The sentence for a command whose setting a lock holds: its `reasonKey`, else the general one. */\nexport const lockedMessage = (\n lock: SettingLock,\n label: string,\n context: CommandContext,\n): string => {\n const fallback = `${label} can't be changed in this document`;\n const i18n = context.tryGet(I18nToken);\n if (!i18n) return fallback;\n const params = { label };\n const general = i18n.t(DEFAULT_LOCKED_KEY, { params, fallback });\n return lock.reasonKey === undefined\n ? general\n : i18n.t(lock.reasonKey, { params, fallback: general });\n};\n\n/** The sentence for a command that's turned off. */\nconst turnedOffMessage = (label: string, context: CommandContext): string => {\n const i18n = context.tryGet(I18nToken);\n return i18n\n ? i18n.t('commands.turnedOff', { params: { label }, fallback: \"{label} isn't available\" })\n : `${label} isn't available`;\n};\n\nexport function createAvailability(\n ctx: PluginContext<void, CommandsSettings>,\n settings: Settings<CommandsSettings>,\n) {\n /** Whether a command is turned off: by its id, or through one of its categories. */\n const isTurnedOff = (definition: CommandDef): boolean => {\n const { disabledCategories, disabledCommands } = settings.get();\n return (\n disabledCommands.includes(definition.id) ||\n (definition.categories ?? []).some((category) => isCategoryOff(category, disabledCategories))\n );\n };\n\n /** Whether a command's `allowed` check says yes; one that throws allows it. */\n const passesCheck = (definition: CommandDef, context: CommandContext): boolean => {\n if (!definition.allowed) return true;\n try {\n return definition.allowed(context);\n } catch {\n return true;\n }\n };\n\n /** The lock on the setting a command changes, or `null`; a `locked` that throws is no lock. */\n const lockOf = (definition: CommandDef, context: CommandContext): SettingLock | null => {\n if (!definition.locked) return null;\n try {\n return definition.locked(context);\n } catch {\n return null;\n }\n };\n\n /**\n * Why its document's session may not run a command, as the key of the sentence that says\n * so, or `null` when it may: the first permission `requires` names that the session doesn't\n * hold (`commands.notAllowed.doc-print`), else its `allowed` check saying no (its\n * `notAllowedKey`). With no document open there is no session to ask, and nothing is refused.\n */\n const notAllowedKeyOf = (definition: CommandDef, context: CommandContext): string | null => {\n if (!definition.requires?.length && !definition.allowed) return null;\n const handle = context.documentId === null ? null : ctx.documentHandle(context.documentId);\n if (!handle) return null;\n const missing = definition.requires?.find(\n (permission) => !sessionHolds(handle.security, permission),\n );\n if (missing !== undefined) return permissionKeyOf(missing);\n return passesCheck(definition, context)\n ? null\n : (definition.notAllowedKey ?? DEFAULT_NOT_ALLOWED_KEY);\n };\n\n /** Why a command won't run whatever the moment, or `null` when it may run. */\n const refusalOf = (definition: CommandDef, context: CommandContext): CommandRefusal | null => {\n if (isTurnedOff(definition)) {\n return {\n reason: 'turned-off',\n message: turnedOffMessage(labelOf(definition, context), context),\n };\n }\n const notAllowed = notAllowedKeyOf(definition, context);\n if (notAllowed !== null) {\n return {\n reason: 'not-allowed',\n message: notAllowedMessage(notAllowed, labelOf(definition, context), context),\n };\n }\n const lock = lockOf(definition, context);\n return lock === null\n ? null\n : { reason: 'locked', message: lockedMessage(lock, labelOf(definition, context), context) };\n };\n\n return { isTurnedOff, notAllowedKeyOf, lockOf, refusalOf };\n}\n","/**\n * Turning commands off and on: by category, with every category under it, and\n * one by one. Both lists are settings, so they change live and\n * `resetSettings()` restores what the app registered.\n */\nimport type { Settings } from '@embedpdf/core';\n\nimport type { CommandDef, CommandsCapability, CommandsSettings } from '../contract';\nimport { isCategoryOff } from '../services/availability';\n\ntype OffList = 'disabledCategories' | 'disabledCommands';\n\nexport function createTurningOff(\n settings: Settings<CommandsSettings>,\n definitionOf: (id: string) => CommandDef | null,\n isTurnedOff: (definition: CommandDef) => boolean,\n) {\n const listOf = (list: OffList): readonly string[] => settings.get()[list];\n const replace = (list: OffList, names: readonly string[]): void =>\n settings.api.updateSettings(\n list === 'disabledCategories'\n ? { disabledCategories: [...names] }\n : { disabledCommands: [...names] },\n );\n // Adding a name that's there, or removing one that isn't, changes nothing and fires nothing.\n const add = (list: OffList, name: string): void => {\n const current = listOf(list);\n if (!current.includes(name)) replace(list, [...current, name]);\n };\n const remove = (list: OffList, name: string): void => {\n const current = listOf(list);\n if (current.includes(name))\n replace(\n list,\n current.filter((other) => other !== name),\n );\n };\n\n return {\n getDisabledCategories: () => listOf('disabledCategories'),\n isCategoryDisabled: (category) => isCategoryOff(category, listOf('disabledCategories')),\n disableCategory: (category) => add('disabledCategories', category),\n enableCategory: (category) => remove('disabledCategories', category),\n setDisabledCategories: (categories) => replace('disabledCategories', categories),\n getDisabledCommands: () => listOf('disabledCommands'),\n isCommandDisabled: (id) => {\n const definition = definitionOf(id);\n return definition ? isTurnedOff(definition) : listOf('disabledCommands').includes(id);\n },\n disableCommand: (id) => add('disabledCommands', id),\n enableCommand: (id) => remove('disabledCommands', id),\n setDisabledCommands: (ids) => replace('disabledCommands', ids),\n } satisfies Partial<CommandsCapability>;\n}\n","/**\n * The commands controller: the commands (from the settings, added while the\n * app runs, and from families), resolution for a document (derivations over\n * live state, safe to throw), the one way to run a command, turning commands\n * off (by category and one by one), what the session may run (the scope's\n * `requires`, the plugins' checks in `allowed`), and the host-only keystroke\n * matcher.\n *\n * Definitions hold functions, so the commands added while the app runs are a\n * map outside state; every change to it calls `ctx.notify()` so readers read\n * again.\n */\nimport {\n DocumentsToken,\n isPluginError,\n memo,\n memoByKey,\n PluginError,\n toPluginError,\n toPluginErrorInfo,\n type CapabilityToken,\n type PluginContext,\n type Unsubscribe,\n} from '@embedpdf/core';\nimport { matchShortcut, type KeyStroke } from '@embedpdf/core-ui';\nimport { ShellToken } from '@embedpdf/plugin-shell/contract';\n\nimport type {\n CommandContext,\n CommandDef,\n CommandExecutedEvent,\n CommandExecutionFailedEvent,\n CommandFamily,\n CommandsSettings,\n ExecuteOptions,\n ExecuteResult,\n IconAccent,\n RegisterCommandOptions,\n ResolvedCommand,\n} from './contract';\nimport type { CommandsHostCapability, ShortcutMatch } from './host-contract';\nimport {\n configuredCommands,\n registeredCommand,\n type ConfiguredCommands,\n type RegisteredCommand,\n} from './registry';\nimport {\n createAvailability,\n labelOf,\n lockedMessage,\n notAllowedMessage,\n} from './services/availability';\nimport { createTurningOff } from './write/turning-off';\n\nconst panelTarget = (\n definition: CommandDef,\n): { id: string; exclusive?: string; focus?: boolean } | null =>\n definition.panel === undefined\n ? null\n : typeof definition.panel === 'string'\n ? { id: definition.panel }\n : definition.panel;\n\n/**\n * One command's live derivations for a document, as values a memo can\n * compare: the entry, label, accent colors, the enabled/active/visible flags,\n * and why it's disabled when the scope doesn't allow it.\n */\ntype Derivations = readonly [\n entry: RegisteredCommand | null,\n label: string,\n accentPrimary: string | undefined,\n accentSecondary: string | undefined,\n enabled: boolean,\n active: boolean,\n visible: boolean,\n disabledReason: string | undefined,\n];\n\nconst NOT_REGISTERED: Derivations = [\n null,\n '',\n undefined,\n undefined,\n false,\n false,\n false,\n undefined,\n];\nconst NO_NAMES: readonly string[] = [];\n\nconst accentOf = (primary?: string, secondary?: string): IconAccent | undefined =>\n primary === undefined && secondary === undefined\n ? undefined\n : {\n ...(primary !== undefined ? { primary } : {}),\n ...(secondary !== undefined ? { secondary } : {}),\n };\n\n/** The memo key of a resolution: the command id and the document named, if any. */\nconst resolutionKey = (id: string, documentId: string | undefined): string =>\n JSON.stringify([id, documentId ?? null]);\n\nexport function createCommandsController(ctx: PluginContext<void, CommandsSettings>) {\n const settings = ctx.settings();\n\n /** Commands added while the app runs, in the order they were added. */\n const registered = new Map<string, RegisteredCommand>();\n /** Bumped on every change to `registered`: the input of the reads built from it. */\n let registeredVersion = 0;\n const registeredChanged = (): void => {\n registeredVersion += 1;\n ctx.notify();\n };\n\n /** The commands the settings define, rebuilt when the setting changes. */\n const configured = memo(\n () => [settings.get().commands],\n (items): ConfiguredCommands => configuredCommands(items),\n );\n\n const executed = ctx.events.source<CommandExecutedEvent>();\n const executionFailed = ctx.events.source<CommandExecutionFailedEvent>();\n\n /** Capabilities for the command's document: the one named, else the active one. */\n const commandContext = (\n documentId?: string,\n call: { args?: unknown; signal?: AbortSignal } = {},\n ): CommandContext => {\n const target = documentId ?? ctx.get(DocumentsToken).getActiveId();\n const get = <T>(token: CapabilityToken<T>): T =>\n target ? ctx.forDocument(token, target) : ctx.get(token);\n return {\n documentId: target,\n appState: settings.get().appState,\n ...(call.args === undefined ? {} : { args: call.args }),\n ...(call.signal ? { signal: call.signal } : {}),\n get,\n tryGet: <T>(token: CapabilityToken<T>): T | null => {\n try {\n return get(token);\n } catch {\n return null;\n }\n },\n };\n };\n\n /** A family's command for one name, made once so it keeps its identity. */\n const familyCommands = new WeakMap<CommandFamily, Map<string, RegisteredCommand>>();\n const familyCommand = (family: CommandFamily, name: string): RegisteredCommand => {\n let byName = familyCommands.get(family);\n if (!byName) {\n byName = new Map();\n familyCommands.set(family, byName);\n }\n let entry = byName.get(name);\n if (!entry) {\n entry = registeredCommand({ ...family.command(name), id: `${family.prefix}${name}` });\n byName.set(name, entry);\n }\n return entry;\n };\n\n /** The command with this id: one added while the app runs, else the settings', else a family's. */\n const entryOf = (id: string): RegisteredCommand | null => {\n const { commands, families } = configured();\n const entry = registered.get(id) ?? commands.get(id);\n if (entry) return entry;\n const family = families.find(\n (candidate) => id.startsWith(candidate.prefix) && id.length > candidate.prefix.length,\n );\n return family ? familyCommand(family, id.slice(family.prefix.length)) : null;\n };\n\n /** Every command with its own definition (not a family's), each id once. */\n const definedCommands = memo(\n () => [registeredVersion, configured()],\n (_version, { commands }) => {\n const entries = new Map(commands);\n for (const [id, entry] of registered) entries.set(id, entry);\n return [...entries.values()];\n },\n );\n\n // Derivations run against live state: without one, the command is what\n // `absent` says; one that throws (it needs a document and none is open, say)\n // says no, so the button renders disabled, not pressed or hidden instead of\n // breaking.\n const derive = (\n derivation: ((context: CommandContext) => boolean) | undefined,\n context: CommandContext,\n absent: boolean,\n ): boolean => {\n if (!derivation) return absent;\n try {\n return derivation(context);\n } catch {\n return false;\n }\n };\n const deriveAccent = (\n derivation: ((context: CommandContext) => IconAccent | null) | undefined,\n context: CommandContext,\n ): IconAccent | undefined => {\n if (!derivation) return undefined;\n try {\n return derivation(context) ?? undefined;\n } catch {\n return undefined;\n }\n };\n const namesOf = (family: CommandFamily, context: CommandContext): readonly string[] => {\n try {\n return family.names(context);\n } catch {\n return NO_NAMES;\n }\n };\n\n const { isTurnedOff, notAllowedKeyOf, lockOf, refusalOf } = createAvailability(ctx, settings);\n\n const derivationsOf = (entry: RegisteredCommand, documentId?: string): Derivations => {\n const { definition } = entry;\n const context = commandContext(documentId);\n const label = labelOf(definition, context);\n // Turned off hides it; not allowed hides it, or disables it with the reason; a lock on the\n // setting it changes disables it with the lock's reason, whatever `notAllowed` says.\n const turnedOff = isTurnedOff(definition);\n const notAllowed = turnedOff ? null : notAllowedKeyOf(definition, context);\n const shownWhenNotAllowed = settings.get().notAllowed === 'disable';\n const lock = turnedOff || notAllowed !== null ? null : lockOf(definition, context);\n const ruledOut = turnedOff || notAllowed !== null || lock !== null;\n // A command that opens something is active while it's open, unless it says otherwise.\n let active: boolean;\n if (definition.active) {\n active = derive(definition.active, context, false);\n } else {\n const shell = context.tryGet(ShellToken);\n const panel = panelTarget(definition);\n active = shell\n ? definition.menu\n ? shell.isMenuOpen(definition.menu)\n : panel\n ? shell.isOpen(panel.id)\n : definition.modal\n ? shell.isOpen(definition.modal)\n : false\n : false;\n }\n const accent = deriveAccent(definition.iconAccent, context);\n return [\n entry,\n label,\n accent?.primary,\n accent?.secondary,\n !ruledOut && derive(definition.enabled, context, true),\n active,\n !turnedOff &&\n (notAllowed === null || shownWhenNotAllowed) &&\n derive(definition.visible, context, true),\n notAllowed !== null && shownWhenNotAllowed\n ? notAllowedMessage(notAllowed, label, context)\n : lock !== null\n ? lockedMessage(lock, label, context)\n : undefined,\n ];\n };\n\n /** A resolved command, the same object until one of its derivations or its entry changes. */\n const resolvedByKey = memoByKey(\n (key: string): Derivations => {\n const [id, documentId] = JSON.parse(key) as [string, string | null];\n const entry = entryOf(id);\n return entry ? derivationsOf(entry, documentId ?? undefined) : NOT_REGISTERED;\n },\n (\n _key,\n entry,\n label,\n accentPrimary,\n accentSecondary,\n enabled,\n active,\n visible,\n disabledReason,\n ): ResolvedCommand | null =>\n entry && {\n id: entry.definition.id,\n label,\n icon: entry.definition.icon,\n iconAccent: accentOf(accentPrimary, accentSecondary),\n shortcuts: entry.shortcuts,\n menu: entry.definition.menu,\n enabled,\n active,\n visible,\n categories: entry.definition.categories ?? [],\n ...(disabledReason === undefined ? {} : { disabledReason }),\n },\n );\n const resolveCommand = (id: string, documentId?: string): ResolvedCommand | null =>\n entryOf(id) ? resolvedByKey(resolutionKey(id, documentId)) : null;\n\n /**\n * Every command's id for a document (`''` is the active one): the defined ones in the order\n * they were added, then each family's names that no defined command took.\n */\n const idsByDocument = memoByKey(\n (documentKey: string): readonly unknown[] => {\n const config = configured();\n const context = commandContext(documentKey || undefined);\n return [\n definedCommands(),\n config,\n ...config.families.map((family) => namesOf(family, context)),\n ];\n },\n (_documentKey, ...inputs): readonly string[] => {\n const [defined, { families }, ...names] = inputs as [\n readonly RegisteredCommand[],\n ConfiguredCommands,\n ...(readonly string[])[],\n ];\n const ids = defined.map((entry) => entry.definition.id);\n const taken = new Set(ids);\n families.forEach((family, index) => {\n for (const name of names[index] ?? NO_NAMES) {\n const id = `${family.prefix}${name}`;\n if (taken.has(id)) continue;\n taken.add(id);\n ids.push(id);\n }\n });\n return ids;\n },\n );\n const commandsByDocument = memoByKey(\n (documentKey: string) =>\n idsByDocument(documentKey).map((id) => resolveCommand(id, documentKey || undefined)),\n (_documentKey, ...resolved) =>\n resolved.filter((command): command is ResolvedCommand => command !== null),\n );\n const listCommands = (documentId?: string): readonly ResolvedCommand[] =>\n commandsByDocument(documentId ?? '');\n\n const listShortcuts = memo(\n () => [definedCommands()],\n (entries) =>\n entries.flatMap((entry) =>\n entry.shortcuts.map((shortcut) => ({ commandId: entry.definition.id, shortcut })),\n ),\n );\n\n /** What running a command does: its `run`, or opening what it opens. */\n const runCommand = async (definition: CommandDef, context: CommandContext): Promise<void> => {\n if (definition.run) {\n await definition.run(context);\n return;\n }\n const shell = context.tryGet(ShellToken);\n const panel = panelTarget(definition);\n if (!shell) return;\n if (definition.menu) shell.toggleMenu(definition.menu);\n else if (panel) shell.toggle(panel.id, { exclusive: panel.exclusive, focus: panel.focus });\n else if (definition.modal) shell.toggle(definition.modal, { exclusive: 'modal' });\n };\n\n const execute = async (id: string, options: ExecuteOptions = {}): Promise<ExecuteResult> => {\n const { signal, documentId, args } = options;\n if (signal?.aborted) {\n throw new PluginError('operation-cancelled', 'commands', 'operation cancelled');\n }\n const entry = entryOf(id);\n if (!entry) return { status: 'rejected', reason: 'not-found' };\n const resolved = resolveCommand(id, documentId);\n if (!resolved?.visible) return { status: 'rejected', reason: 'hidden' };\n if (!resolved.enabled) return { status: 'rejected', reason: 'disabled' };\n const context = commandContext(documentId, { args, signal });\n try {\n await ctx.cancellable(signal, runCommand(entry.definition, context));\n } catch (error) {\n // The caller cancelling isn't the command failing.\n if (signal?.aborted && isPluginError(error, 'operation-cancelled')) throw error;\n const failure = toPluginError('commands', error);\n executionFailed.emit({\n commandId: id,\n documentId: context.documentId,\n error: toPluginErrorInfo(failure),\n });\n throw failure;\n } finally {\n // A run may change what the commands read outside the viewer (your app's state): every\n // button asks its command again, so the one just pressed shows what it did.\n ctx.notify();\n }\n executed.emit({ commandId: id, documentId: context.documentId, args });\n return { status: 'executed' };\n };\n\n const registerOne = (definition: CommandDef, options?: RegisterCommandOptions): Unsubscribe => {\n const taken = registered.has(definition.id) || configured().commands.has(definition.id);\n if (taken && !options?.replace) {\n throw new PluginError('conflict', 'commands', `duplicate command '${definition.id}'`);\n }\n const entry = registeredCommand(definition);\n registered.set(definition.id, entry);\n registeredChanged();\n return () => {\n // Own this registration only: a later replacement is not ours to remove.\n if (registered.get(definition.id) !== entry) return;\n registered.delete(definition.id);\n registeredChanged();\n };\n };\n\n const turningOff = createTurningOff(\n settings,\n (id) => entryOf(id)?.definition ?? null,\n isTurnedOff,\n );\n\n const api: CommandsHostCapability = {\n ...settings.api,\n registerCommand: registerOne,\n registerCommands: (definitions, options) => {\n const removers = definitions.map((definition) => registerOne(definition, options));\n return () => removers.forEach((remove) => remove());\n },\n hasCommand: (id) => entryOf(id) !== null,\n getCommand: (id) => entryOf(id)?.definition ?? null,\n listCommandIds: () => idsByDocument(''),\n resolveCommand,\n listCommands,\n searchCommands: (query, documentId) => {\n const needle = query.trim().toLowerCase();\n return listCommands(documentId).filter(\n (command) =>\n command.visible &&\n (needle === '' ||\n command.label.toLowerCase().includes(needle) ||\n command.id.includes(needle)),\n );\n },\n listShortcuts,\n execute,\n canExecute: (id, documentId) => {\n const resolved = resolveCommand(id, documentId);\n return !!resolved && resolved.enabled && resolved.visible;\n },\n getRefusal: (id, documentId) => {\n const entry = entryOf(id);\n return entry ? refusalOf(entry.definition, commandContext(documentId)) : null;\n },\n ...turningOff,\n onExecuted: executed.on,\n onExecutionFailed: executionFailed.on,\n // ── host lens ──\n matchStroke: (stroke: KeyStroke, options) => {\n let waiting: ShortcutMatch | null = null;\n let refused: ShortcutMatch | null = null;\n for (const entry of definedCommands()) {\n if (options.inTextField && !entry.definition.shortcutInTextFields) continue;\n if (!entry.parsed.some((shortcut) => matchShortcut(shortcut, stroke, options))) continue;\n const context = commandContext();\n const refusal = refusalOf(entry.definition, context);\n const visible = derive(entry.definition.visible, context, true);\n if (!refusal) {\n // Commands that share keys take turns: Escape cancels a drawing while there is one,\n // and lets a snapshot go while there is one.\n if (visible && derive(entry.definition.enabled, context, true)) {\n return { commandId: entry.definition.id, refusal: null };\n }\n waiting ??= { commandId: entry.definition.id, refusal: null };\n continue;\n }\n // A refused command takes its keys only where it would show: Delete with nothing\n // selected stays the page's, even where deleting is turned off.\n if (!visible) continue;\n refused ??= { commandId: entry.definition.id, refusal };\n }\n return waiting ?? refused;\n },\n getMenuTarget: (id) => {\n const entry = entryOf(id);\n return entry ? { menu: entry.definition.menu } : null;\n },\n };\n\n return { api };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { I18nToken } from '@embedpdf/plugin-i18n/contract';\nimport { ShellToken } from '@embedpdf/plugin-shell/contract';\n\nimport { COMMANDS_DEFAULTS, type CommandsConfig } from './contract';\nimport { createCommandsController } from './controller';\nimport { CommandsToken } from './host-contract';\n\n/**\n * The commands: one set for the whole workspace, each resolved and run for a\n * document (the one named, else the document in scope, else the active one).\n * Definitions are settings and app content, never state, since they hold\n * functions. `config` is the settings the app registers, over\n * {@link COMMANDS_DEFAULTS}.\n */\nexport const commandsPlugin = <AppState = any>(config?: CommandsConfig<AppState>) =>\n definePlugin({\n id: 'commands',\n scope: 'workspace',\n token: CommandsToken,\n // Labels come from i18n, and commands that open a panel, menu or dialog\n // go through shell; without them a label is the command's own, and those\n // commands open nothing.\n optional: [I18nToken, ShellToken],\n // Command definitions come from the app and may use any capability.\n resolvesAnyCapability: true,\n // Your app's state is replaced whole, never merged: a new value is the whole new state.\n settings: {\n defaults: COMMANDS_DEFAULTS,\n registered: config as CommandsConfig | undefined,\n whole: ['appState'],\n },\n create: createCommandsController,\n // Inside a document's scope, a call that leaves out the document is for that one.\n inScope: (commands, documentId) => ({\n ...commands,\n resolveCommand: (id, target = documentId) => commands.resolveCommand(id, target),\n listCommands: (target = documentId) => commands.listCommands(target),\n searchCommands: (query, target = documentId) => commands.searchCommands(query, target),\n execute: (id, options) =>\n commands.execute(id, { ...options, documentId: options?.documentId ?? documentId }),\n canExecute: (id, target = documentId) => commands.canExecute(id, target),\n getRefusal: (id, target = documentId) => commands.getRefusal(id, target),\n }),\n });\n"],"mappings":";;;;;;;;AAWA,MAAa,qBAAqB,eAA8C;CAC9E,MAAM,YACJ,WAAW,aAAa,KAAA,IAAY,CAAC,IAAK,CAAC,CAAC,CAAc,OAAO,WAAW,QAAQ;CACtF,OAAO;EAAE;EAAY;EAAW,QAAQ,UAAU,IAAI,aAAa;CAAE;AACvE;AAEA,MAAa,mBAAmB,SAC9B,YAAY;AAQd,SAAgB,mBACd,OACoB;CACpB,MAAM,2BAAW,IAAI,IAA+B;CACpD,MAAM,WAA4B,CAAC;CACnC,KAAK,MAAM,QAAQ,OACjB,IAAI,gBAAgB,IAAI,GAAG,SAAS,KAAK,IAAI;MACxC,SAAS,IAAI,KAAK,IAAI,kBAAkB,IAAI,CAAC;CAEpD,OAAO;EAAE;EAAU;CAAS;AAC9B;;;;;;;ACbA,MAAa,iBAAiB,UAAkB,aAC9C,SAAS,MAAM,QAAQ,aAAa,OAAO,SAAS,WAAW,GAAG,IAAI,EAAE,CAAC;;;;;;AAO3E,MAAa,WAAW,YAAwB,YAAoC;CAClF,MAAM,OAAO,QAAQ,OAAO,SAAS;CACrC,IAAI,CAAC,MAAM,OAAO,WAAW,SAAS,WAAW,YAAY,WAAW;CACxE,MAAM,cAAc,WAAW,WAAW,EAAE,aAAa,WAAW,SAAS,IAAI,CAAC;CAElF,OAAO,WAAW,UAAU,KAAA,KAAa,WAAW,WAChD,KAAK,EAAE,WAAW,IAAI,WAAW,IACjC,KAAK,EAAE,WAAW,IAAI;EAAE,GAAG;EAAa,UAAU,WAAW,SAAS,WAAW;CAAG,CAAC;AAC3F;;;;;;AAOA,MAAM,gBAAgB,UAAsC,eAC1D,eAAe,uBACX,SAAS,iBAAiB,QAAQ,IAClC,SAAS,OAAO,UAAU;;AAGhC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;EAClC,GAAG;EACH,iBAAiB,IAAI,SAAS,eAAe,SAAS,eAAe,IAAI,MAAM;EAC/E,eAAe,SAAS,eAAe,SAAS,aAAa,MAAM;EACnE,iBAAiB,OAAO,SAAS,eAAe,SAAS,eAAe,OAAO,MAAM;EACrF,UAAU,IAAI,YACZ,SAAS,QAAQ,IAAI;GAAE,GAAG;GAAS,YAAY,SAAS,cAAc;EAAW,CAAC;EACpF,aAAa,IAAI,SAAS,eAAe,SAAS,WAAW,IAAI,MAAM;EACvE,aAAa,IAAI,SAAS,eAAe,SAAS,WAAW,IAAI,MAAM;CACzE;AACF,CAAC"}
|
package/dist/standard.cjs
CHANGED
|
@@ -2,19 +2,22 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
let _embedpdf_core = require("@embedpdf/core");
|
|
3
3
|
let _embedpdf_plugin_annotation_contract = require("@embedpdf/plugin-annotation/contract");
|
|
4
4
|
let _embedpdf_plugin_interaction_contract = require("@embedpdf/plugin-interaction/contract");
|
|
5
|
+
let _embedpdf_plugin_render_contract = require("@embedpdf/plugin-render/contract");
|
|
5
6
|
let _embedpdf_plugin_selection_contract = require("@embedpdf/plugin-selection/contract");
|
|
6
7
|
let _embedpdf_plugin_stage_contract = require("@embedpdf/plugin-stage/contract");
|
|
7
8
|
//#region src/standard.ts
|
|
8
9
|
/**
|
|
9
10
|
* @embedpdf/plugin-commands/standard — the commands every viewer has: zoom,
|
|
10
|
-
* pages, view rotation, a command for every tool, copy, delete,
|
|
11
|
-
* print, with shortcuts, and labels in EmbedPDF's eight
|
|
12
|
-
* plugin has the strings).
|
|
13
|
-
* file download), which plugins never touch, so each
|
|
14
|
-
* builds them with its platform: that is the
|
|
15
|
-
* imports. Print goes through the kernel, which has
|
|
11
|
+
* pages, view rotation, a command for every tool, copy, the snapshot, delete,
|
|
12
|
+
* download and print, with shortcuts, and labels in EmbedPDF's eight
|
|
13
|
+
* languages (the i18n plugin has the strings). Some of them reach the browser
|
|
14
|
+
* (the clipboard, a file download), which plugins never touch, so each
|
|
15
|
+
* framework's `/commands` builds them with its platform: that is the
|
|
16
|
+
* `standardCommands` an app imports. Print goes through the kernel, which has
|
|
17
|
+
* the host's printer.
|
|
16
18
|
*/
|
|
17
19
|
const stageOf = (context) => context.tryGet(_embedpdf_plugin_stage_contract.StageToken);
|
|
20
|
+
const snapshotOf = (context) => context.tryGet(_embedpdf_plugin_render_contract.RenderToken)?.getSnapshot() ?? null;
|
|
18
21
|
const interactionOf = (context) => context.tryGet(_embedpdf_plugin_interaction_contract.InteractionToken);
|
|
19
22
|
/** Enabled while the document has a Stage. */
|
|
20
23
|
const hasStage = (context) => stageOf(context) !== null;
|
|
@@ -172,6 +175,12 @@ function createStandardCommands(platform) {
|
|
|
172
175
|
id: "tool:zoom",
|
|
173
176
|
shortcut: "Z"
|
|
174
177
|
},
|
|
178
|
+
{
|
|
179
|
+
...toolCommand(_embedpdf_plugin_render_contract.SNAPSHOT_TOOL),
|
|
180
|
+
id: "tool:snapshot",
|
|
181
|
+
allowed: (context) => context.tryGet(_embedpdf_plugin_render_contract.RenderToken)?.canSnapshot() ?? true,
|
|
182
|
+
notAllowedKey: "commands.notAllowed.doc-content-copy"
|
|
183
|
+
},
|
|
175
184
|
toolCommands,
|
|
176
185
|
{
|
|
177
186
|
id: "selection:copy",
|
|
@@ -201,6 +210,45 @@ function createStandardCommands(platform) {
|
|
|
201
210
|
return selected.length > 0 && selected.every(({ ref }) => annotation.canDelete(ref) && annotation.isEditable(ref));
|
|
202
211
|
}
|
|
203
212
|
},
|
|
213
|
+
{
|
|
214
|
+
id: "snapshot:copy",
|
|
215
|
+
labelKey: "commands.snapshot.copy",
|
|
216
|
+
label: "Copy",
|
|
217
|
+
icon: "copy",
|
|
218
|
+
shortcut: "Mod+C",
|
|
219
|
+
categories: ["snapshot"],
|
|
220
|
+
run: (context) => {
|
|
221
|
+
const snapshot = snapshotOf(context);
|
|
222
|
+
return snapshot ? platform.copyImage(snapshot.image) : void 0;
|
|
223
|
+
},
|
|
224
|
+
enabled: (context) => snapshotOf(context) !== null
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
id: "snapshot:save",
|
|
228
|
+
labelKey: "commands.snapshot.save",
|
|
229
|
+
label: "Save image",
|
|
230
|
+
icon: "download",
|
|
231
|
+
categories: ["snapshot"],
|
|
232
|
+
run: async (context) => {
|
|
233
|
+
const snapshot = snapshotOf(context);
|
|
234
|
+
if (!snapshot) return;
|
|
235
|
+
const documents = context.get(_embedpdf_core.DocumentsToken);
|
|
236
|
+
const id = context.documentId ?? void 0;
|
|
237
|
+
const blob = await (await snapshot.image).blob();
|
|
238
|
+
const number = documents.listPages(id).findIndex((page) => page.ref.objectNumber === snapshot.page.objectNumber) + 1;
|
|
239
|
+
platform.saveFile(blob, snapshotFileNameOf(documents.get(id)?.name, number), "image/png");
|
|
240
|
+
},
|
|
241
|
+
enabled: (context) => snapshotOf(context) !== null
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
id: "snapshot:clear",
|
|
245
|
+
labelKey: "commands.snapshot.clear",
|
|
246
|
+
label: "Clear snapshot",
|
|
247
|
+
shortcut: "Escape",
|
|
248
|
+
categories: ["snapshot"],
|
|
249
|
+
run: (context) => context.get(_embedpdf_plugin_render_contract.RenderToken).clearSnapshot(),
|
|
250
|
+
enabled: (context) => snapshotOf(context) !== null
|
|
251
|
+
},
|
|
204
252
|
{
|
|
205
253
|
id: "document:download",
|
|
206
254
|
labelKey: "commands.document.download",
|
|
@@ -214,7 +262,7 @@ function createStandardCommands(platform) {
|
|
|
214
262
|
const documents = context.get(_embedpdf_core.DocumentsToken);
|
|
215
263
|
const id = context.documentId ?? void 0;
|
|
216
264
|
const bytes = await documents.download(id, { signal: context.signal });
|
|
217
|
-
platform.saveFile(bytes, fileNameOf(documents.get(id)?.name));
|
|
265
|
+
platform.saveFile(bytes, fileNameOf(documents.get(id)?.name), "application/pdf");
|
|
218
266
|
},
|
|
219
267
|
enabled: (context) => context.documentId !== null
|
|
220
268
|
},
|
|
@@ -239,6 +287,10 @@ function fileNameOf(name) {
|
|
|
239
287
|
if (!name) return "document.pdf";
|
|
240
288
|
return /\.pdf$/i.test(name) ? name : `${name}.pdf`;
|
|
241
289
|
}
|
|
290
|
+
/** A snapshot's file name: the document's name and the page's number, as a PNG (`Report p3.png`). */
|
|
291
|
+
function snapshotFileNameOf(name, pageNumber) {
|
|
292
|
+
return `${(name ?? "document").replace(/\.pdf$/i, "")} p${pageNumber}.png`;
|
|
293
|
+
}
|
|
242
294
|
//#endregion
|
|
243
295
|
exports.createStandardCommands = createStandardCommands;
|
|
244
296
|
|
package/dist/standard.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"standard.cjs","names":["StageToken","InteractionToken","AnnotationToken","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, delete, download and\n * print, with shortcuts, and labels in EmbedPDF's eight languages (the i18n\n * plugin has the strings). Two of them reach the browser (the clipboard, a\n * file download), which plugins never touch, so each framework's `/commands`\n * builds them with its platform: that is the `standardCommands` an app\n * imports. Print goes through the kernel, which has 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 { 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 /** Give the user the bytes as a file download. */\n saveFile(bytes: Uint8Array, fileName: string): void;\n}\n\nconst stageOf = (context: CommandContext) => context.tryGet(StageToken);\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 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 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));\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"],"mappings":";;;;;;;;;;;;;;;;AAyBA,MAAM,WAAW,YAA4B,QAAQ,OAAOA,gCAAAA,UAAU;AACtE,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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,UAAU,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC;GAC9D;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,OAAOA,eAAAA,cAAc,CAAC,EAAE,SAAS,KAAK;GACpE,eAAe;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"}
|
|
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,IAA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eAAAA,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,OAAOA,eAAAA,cAAc,CAAC,EAAE,SAAS,KAAK;GACpE,eAAe;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,12 +1,18 @@
|
|
|
1
1
|
import { i as CommandDef, s as CommandFamily } from "./contract-lGfvyWMG.cjs";
|
|
2
|
+
import { PageImage } from "@embedpdf/plugin-render/contract";
|
|
2
3
|
import { SelectionCapability } from "@embedpdf/plugin-selection/contract";
|
|
3
4
|
//#region src/standard.d.ts
|
|
4
5
|
/** What the standard commands need from the browser. */
|
|
5
6
|
interface StandardCommandsPlatform {
|
|
6
7
|
/** Copy the selected text to the clipboard. */
|
|
7
8
|
copySelection(selection: SelectionCapability): Promise<unknown>;
|
|
8
|
-
/**
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Copy an image to the clipboard. Called in the press or key itself, before
|
|
11
|
+
* the image is there: a browser may take the clipboard only then.
|
|
12
|
+
*/
|
|
13
|
+
copyImage(image: Promise<PageImage>): Promise<unknown>;
|
|
14
|
+
/** Give the user the bytes as a file download, of the given content type. */
|
|
15
|
+
saveFile(bytes: Uint8Array | Blob, fileName: string, contentType: string): void;
|
|
10
16
|
}
|
|
11
17
|
/** The standard commands, with the browser's part from `platform`. */
|
|
12
18
|
declare function createStandardCommands(platform: StandardCommandsPlatform): readonly (CommandDef | CommandFamily)[];
|
package/dist/standard.d.ts
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import { i as CommandDef, s as CommandFamily } from "./contract-lGfvyWMG.js";
|
|
2
|
+
import { PageImage } from "@embedpdf/plugin-render/contract";
|
|
2
3
|
import { SelectionCapability } from "@embedpdf/plugin-selection/contract";
|
|
3
4
|
//#region src/standard.d.ts
|
|
4
5
|
/** What the standard commands need from the browser. */
|
|
5
6
|
interface StandardCommandsPlatform {
|
|
6
7
|
/** Copy the selected text to the clipboard. */
|
|
7
8
|
copySelection(selection: SelectionCapability): Promise<unknown>;
|
|
8
|
-
/**
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Copy an image to the clipboard. Called in the press or key itself, before
|
|
11
|
+
* the image is there: a browser may take the clipboard only then.
|
|
12
|
+
*/
|
|
13
|
+
copyImage(image: Promise<PageImage>): Promise<unknown>;
|
|
14
|
+
/** Give the user the bytes as a file download, of the given content type. */
|
|
15
|
+
saveFile(bytes: Uint8Array | Blob, fileName: string, contentType: string): void;
|
|
10
16
|
}
|
|
11
17
|
/** The standard commands, with the browser's part from `platform`. */
|
|
12
18
|
declare function createStandardCommands(platform: StandardCommandsPlatform): readonly (CommandDef | CommandFamily)[];
|
package/dist/standard.js
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
import { DocumentsToken } from "@embedpdf/core";
|
|
2
2
|
import { AnnotationToken } from "@embedpdf/plugin-annotation/contract";
|
|
3
3
|
import { InteractionToken } from "@embedpdf/plugin-interaction/contract";
|
|
4
|
+
import { RenderToken, SNAPSHOT_TOOL } from "@embedpdf/plugin-render/contract";
|
|
4
5
|
import { SelectionToken } from "@embedpdf/plugin-selection/contract";
|
|
5
6
|
import { StageToken } from "@embedpdf/plugin-stage/contract";
|
|
6
7
|
//#region src/standard.ts
|
|
7
8
|
/**
|
|
8
9
|
* @embedpdf/plugin-commands/standard — the commands every viewer has: zoom,
|
|
9
|
-
* pages, view rotation, a command for every tool, copy, delete,
|
|
10
|
-
* print, with shortcuts, and labels in EmbedPDF's eight
|
|
11
|
-
* plugin has the strings).
|
|
12
|
-
* file download), which plugins never touch, so each
|
|
13
|
-
* builds them with its platform: that is the
|
|
14
|
-
* imports. Print goes through the kernel, which has
|
|
10
|
+
* pages, view rotation, a command for every tool, copy, the snapshot, delete,
|
|
11
|
+
* download and print, with shortcuts, and labels in EmbedPDF's eight
|
|
12
|
+
* languages (the i18n plugin has the strings). Some of them reach the browser
|
|
13
|
+
* (the clipboard, a file download), which plugins never touch, so each
|
|
14
|
+
* framework's `/commands` builds them with its platform: that is the
|
|
15
|
+
* `standardCommands` an app imports. Print goes through the kernel, which has
|
|
16
|
+
* the host's printer.
|
|
15
17
|
*/
|
|
16
18
|
const stageOf = (context) => context.tryGet(StageToken);
|
|
19
|
+
const snapshotOf = (context) => context.tryGet(RenderToken)?.getSnapshot() ?? null;
|
|
17
20
|
const interactionOf = (context) => context.tryGet(InteractionToken);
|
|
18
21
|
/** Enabled while the document has a Stage. */
|
|
19
22
|
const hasStage = (context) => stageOf(context) !== null;
|
|
@@ -171,6 +174,12 @@ function createStandardCommands(platform) {
|
|
|
171
174
|
id: "tool:zoom",
|
|
172
175
|
shortcut: "Z"
|
|
173
176
|
},
|
|
177
|
+
{
|
|
178
|
+
...toolCommand(SNAPSHOT_TOOL),
|
|
179
|
+
id: "tool:snapshot",
|
|
180
|
+
allowed: (context) => context.tryGet(RenderToken)?.canSnapshot() ?? true,
|
|
181
|
+
notAllowedKey: "commands.notAllowed.doc-content-copy"
|
|
182
|
+
},
|
|
174
183
|
toolCommands,
|
|
175
184
|
{
|
|
176
185
|
id: "selection:copy",
|
|
@@ -200,6 +209,45 @@ function createStandardCommands(platform) {
|
|
|
200
209
|
return selected.length > 0 && selected.every(({ ref }) => annotation.canDelete(ref) && annotation.isEditable(ref));
|
|
201
210
|
}
|
|
202
211
|
},
|
|
212
|
+
{
|
|
213
|
+
id: "snapshot:copy",
|
|
214
|
+
labelKey: "commands.snapshot.copy",
|
|
215
|
+
label: "Copy",
|
|
216
|
+
icon: "copy",
|
|
217
|
+
shortcut: "Mod+C",
|
|
218
|
+
categories: ["snapshot"],
|
|
219
|
+
run: (context) => {
|
|
220
|
+
const snapshot = snapshotOf(context);
|
|
221
|
+
return snapshot ? platform.copyImage(snapshot.image) : void 0;
|
|
222
|
+
},
|
|
223
|
+
enabled: (context) => snapshotOf(context) !== null
|
|
224
|
+
},
|
|
225
|
+
{
|
|
226
|
+
id: "snapshot:save",
|
|
227
|
+
labelKey: "commands.snapshot.save",
|
|
228
|
+
label: "Save image",
|
|
229
|
+
icon: "download",
|
|
230
|
+
categories: ["snapshot"],
|
|
231
|
+
run: async (context) => {
|
|
232
|
+
const snapshot = snapshotOf(context);
|
|
233
|
+
if (!snapshot) return;
|
|
234
|
+
const documents = context.get(DocumentsToken);
|
|
235
|
+
const id = context.documentId ?? void 0;
|
|
236
|
+
const blob = await (await snapshot.image).blob();
|
|
237
|
+
const number = documents.listPages(id).findIndex((page) => page.ref.objectNumber === snapshot.page.objectNumber) + 1;
|
|
238
|
+
platform.saveFile(blob, snapshotFileNameOf(documents.get(id)?.name, number), "image/png");
|
|
239
|
+
},
|
|
240
|
+
enabled: (context) => snapshotOf(context) !== null
|
|
241
|
+
},
|
|
242
|
+
{
|
|
243
|
+
id: "snapshot:clear",
|
|
244
|
+
labelKey: "commands.snapshot.clear",
|
|
245
|
+
label: "Clear snapshot",
|
|
246
|
+
shortcut: "Escape",
|
|
247
|
+
categories: ["snapshot"],
|
|
248
|
+
run: (context) => context.get(RenderToken).clearSnapshot(),
|
|
249
|
+
enabled: (context) => snapshotOf(context) !== null
|
|
250
|
+
},
|
|
203
251
|
{
|
|
204
252
|
id: "document:download",
|
|
205
253
|
labelKey: "commands.document.download",
|
|
@@ -213,7 +261,7 @@ function createStandardCommands(platform) {
|
|
|
213
261
|
const documents = context.get(DocumentsToken);
|
|
214
262
|
const id = context.documentId ?? void 0;
|
|
215
263
|
const bytes = await documents.download(id, { signal: context.signal });
|
|
216
|
-
platform.saveFile(bytes, fileNameOf(documents.get(id)?.name));
|
|
264
|
+
platform.saveFile(bytes, fileNameOf(documents.get(id)?.name), "application/pdf");
|
|
217
265
|
},
|
|
218
266
|
enabled: (context) => context.documentId !== null
|
|
219
267
|
},
|
|
@@ -238,6 +286,10 @@ function fileNameOf(name) {
|
|
|
238
286
|
if (!name) return "document.pdf";
|
|
239
287
|
return /\.pdf$/i.test(name) ? name : `${name}.pdf`;
|
|
240
288
|
}
|
|
289
|
+
/** A snapshot's file name: the document's name and the page's number, as a PNG (`Report p3.png`). */
|
|
290
|
+
function snapshotFileNameOf(name, pageNumber) {
|
|
291
|
+
return `${(name ?? "document").replace(/\.pdf$/i, "")} p${pageNumber}.png`;
|
|
292
|
+
}
|
|
241
293
|
//#endregion
|
|
242
294
|
export { createStandardCommands };
|
|
243
295
|
|
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, delete, download and\n * print, with shortcuts, and labels in EmbedPDF's eight languages (the i18n\n * plugin has the strings). Two of them reach the browser (the clipboard, a\n * file download), which plugins never touch, so each framework's `/commands`\n * builds them with its platform: that is the `standardCommands` an app\n * imports. Print goes through the kernel, which has 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 { 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 /** Give the user the bytes as a file download. */\n saveFile(bytes: Uint8Array, fileName: string): void;\n}\n\nconst stageOf = (context: CommandContext) => context.tryGet(StageToken);\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 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 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));\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"],"mappings":";;;;;;;;;;;;;;;AAyBA,MAAM,WAAW,YAA4B,QAAQ,OAAO,UAAU;AACtE,MAAM,iBAAiB,YAA4B,Q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AAG,CAAC;GAEvF;EACF;EAGA;GACE,IAAI;GACJ,UAAU;GACV,OAAO;GACP,MAAM;GACN,UAAU;GACV,YAAY,CAAC,UAAU;GACvB,UAAU,YAAY,QAAQ,OAAO,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,CAAC;GAC9D;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"}
|
|
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,W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O;GACP,MAAM;GACN,UAAU;GACV,YAAY,CAAC,UAAU;GACvB,UAAU,YAAY,QAAQ,OAAO,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.22",
|
|
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,14 +30,15 @@
|
|
|
30
30
|
"dist"
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@embedpdf/core": "3.0.0-next.
|
|
34
|
-
"@embedpdf/core-ui": "3.0.0-next.
|
|
35
|
-
"@embedpdf/plugin-annotation": "3.0.0-next.
|
|
36
|
-
"@embedpdf/plugin-i18n": "3.0.0-next.
|
|
37
|
-
"@embedpdf/plugin-
|
|
38
|
-
"@embedpdf/plugin-
|
|
39
|
-
"@embedpdf/plugin-shell": "3.0.0-next.
|
|
40
|
-
"@embedpdf/plugin-
|
|
33
|
+
"@embedpdf/core": "3.0.0-next.22",
|
|
34
|
+
"@embedpdf/core-ui": "3.0.0-next.22",
|
|
35
|
+
"@embedpdf/plugin-annotation": "3.0.0-next.22",
|
|
36
|
+
"@embedpdf/plugin-i18n": "3.0.0-next.22",
|
|
37
|
+
"@embedpdf/plugin-interaction": "3.0.0-next.22",
|
|
38
|
+
"@embedpdf/plugin-render": "3.0.0-next.22",
|
|
39
|
+
"@embedpdf/plugin-shell": "3.0.0-next.22",
|
|
40
|
+
"@embedpdf/plugin-stage": "3.0.0-next.22",
|
|
41
|
+
"@embedpdf/plugin-selection": "3.0.0-next.22"
|
|
41
42
|
},
|
|
42
43
|
"devDependencies": {
|
|
43
44
|
"typescript": "^5.0.0",
|