@embedpdf/plugin-commands 3.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contract-Cln8gHpa.js.map +1 -1
- package/dist/contract-DK9eNgkr.cjs.map +1 -1
- package/dist/index.cjs +145 -91
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +145 -91
- package/dist/index.js.map +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contract-Cln8gHpa.js","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it to the host capability. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { CommandsCapability } from './contract';\n\nexport const CommandsToken = createCapabilityToken<CommandsCapability>('commands', {\n hint: `add commandsPlugin() from '@embedpdf/plugin-commands' to your plugins list`,\n});\n","/**\n * @embedpdf/plugin-commands/contract — the commands that toolbars, menus,\n * shortcuts and a command palette all show and run.\n *\n * A command's state is read from live state: `resolveCommand` asks the other\n * capabilities when it's called, so every reader follows the kernel's one\n * change stream, with no events. Definitions hold functions, so they live in\n * the settings and the plugin's registry, never in state.\n */\nimport type {\n CapabilityToken,\n DeepPartial,\n EventHook,\n OperationOptions,\n Permission,\n PluginErrorInfo,\n SettingLock,\n SettingsApi,\n Unsubscribe,\n} from '@embedpdf/core';\nimport { didYouMean, formatShortcut } from '@embedpdf/core-ui';\n\nexport { CommandsToken } from './token';\n\nexport type CommandId = string;\n\n/**\n * What a command's derivations and `run` see: capabilities resolved for the command's document\n * (the one named, else the document in scope, else the active one), and your app's state.\n */\nexport interface CommandContext<AppState = any> {\n /** The command's document, or `null` when none is open. */\n readonly documentId: string | null;\n /** Your app's state, as the `appState` setting has it now: `any` until you give its type. */\n readonly appState: AppState;\n /** What the caller passed: `execute(id, { args })`. */\n readonly args?: unknown;\n /** Fires when the caller cancels `execute()`: pass it on to the calls `run` makes. */\n readonly signal?: AbortSignal;\n /** A capability, for the command's document when the plugin is document-scoped. Throws when it isn't available. */\n get<T>(token: CapabilityToken<T>): T;\n /** Like `get`, but `null` when the capability isn't available (no plugin, no document). */\n tryGet<T>(token: CapabilityToken<T>): T | null;\n}\n\n/**\n * Up to two colors that go with a command's icon, such as a tool's current color: data a\n * renderer may use (tint the icon, show a swatch), like `icon` itself.\n */\nexport interface IconAccent {\n /** The mark: a stroke, the markup or the text color. */\n readonly primary?: string;\n /** The fill, when there is one. */\n readonly secondary?: string;\n}\n\n/**\n * One command, as you define it. Its functions get your app's state as `AppState`; they're\n * methods, so a command typed for your state (`CommandDefinition<Review>`) goes wherever a command does.\n */\nexport interface CommandDefinition<AppState = any> {\n /** A unique name, by convention `area:action`: `'zoom:in'`, `'review:approve'`. */\n readonly id: string;\n /**\n * What the user sees. With `labelKey` too, it's what shows when no language has the key. Its\n * `{name}` slots take the values `labelParams` gives.\n */\n readonly label?: string;\n /**\n * A translation key for the label, read through the i18n plugin. Without the plugin, or a\n * string for the key, the command shows `label`, else the key. The string's `{name}` slots\n * take the values `labelParams` gives, and a number `count` picks its plural form.\n */\n readonly labelKey?: string;\n /** Your icon's name; your buttons turn it into an icon. */\n readonly icon?: string;\n /** Colors for the icon, read from live state like `active`. */\n iconAccent?(context: CommandContext<AppState>): IconAccent | null;\n /** A key such as `'Mod+K'` (`Mod` is Cmd on a Mac, Ctrl elsewhere), or a list of them. */\n readonly shortcut?: string | readonly string[];\n /**\n * Whether its shortcut also runs while the cursor is in a text field where the shortcuts\n * listen (a search box, a comment), as the viewer's Find does. Default false: a key typed in\n * a field is the field's.\n */\n readonly shortcutInTextFields?: boolean;\n /**\n * The features it belongs to, so turning one off turns it off: `['annotations.highlight']`.\n * Turning off a feature turns off every feature under it, on whole dotted parts: `annotations`\n * covers `annotations.highlight`, not `annotationsExtra`.\n */\n readonly categories?: readonly string[];\n /**\n * The scope permissions it needs, such as `'doc.annotate.modify'`, checked against its\n * document. Without them it's hidden, or shown disabled with its reason under the\n * `notAllowed: 'disable'` setting. With no document open there is nothing to check.\n */\n readonly requires?: readonly Permission[];\n /**\n * Whether the session may run it, from the plugins' `can*` checks\n * (`documents.canPrint()`), for a command whose permission is a plugin's to know. When it\n * says no, the command isn't allowed, as with `requires`. Asked only while a document is\n * open; one that throws allows it.\n */\n allowed?(context: CommandContext<AppState>): boolean;\n /**\n * The translation key of the sentence that says why `allowed` refused it, with `{label}` for\n * its label: `'commands.notAllowed.doc-print'`. Without it, or a string for it,\n * `commands.notAllowed.default`.\n */\n readonly notAllowedKey?: string;\n /**\n * The lock on the setting it changes, for a command that changes one\n * (`(context) => context.get(StageToken).getLock('spread')`), or `null`.\n * While a lock holds, it shows disabled, whatever the `notAllowed` setting\n * says, with the sentence under the lock's `reasonKey` (else\n * `commands.locked.default`) as its `disabledReason`; it stays `active` for\n * its own value. One that throws counts as unlocked.\n */\n locked?(context: CommandContext<AppState>): SettingLock | null;\n\n // ── what the command opens ───────────────────────────────────────────────\n // A command that opens a panel, menu or dialog says so instead of opening\n // it in `run`: it then needs no `run`, it shows as active while the surface\n // is open, and a button can show that it opens a menu.\n /** Opens and closes a menu of yours, by its id. */\n readonly menu?: string;\n /**\n * Opens and closes a panel, closing the others with the same `exclusive` tag. With `focus`,\n * opening it asks for the cursor (the shell's `open(id, { focus: true })`).\n */\n readonly panel?:\n | string\n | { readonly id: string; readonly exclusive?: string; readonly focus?: boolean };\n /** Opens and closes a dialog; one dialog is open at a time. */\n readonly modal?: string;\n\n // ── read from live state and your app's, again whenever either changes ──\n /** When it can run. Default: always. One that throws counts as false. */\n enabled?(context: CommandContext<AppState>): boolean;\n /** When it shows as pressed, such as the current tool. One that throws counts as false. */\n active?(context: CommandContext<AppState>): boolean;\n /** When it shows at all. Default: always. One that throws counts as false. */\n visible?(context: CommandContext<AppState>): boolean;\n /**\n * The values for its label's `{name}` slots, such as how many pages are selected:\n * `({ count: pageEdit.getSelected().length })`. A number `count` also picks the plural form of a\n * translated label. One that throws gives none, and the slots show as they are.\n */\n labelParams?(context: CommandContext<AppState>): Readonly<Record<string, string | number>>;\n\n /** What it does; `execute()` resolves once it has. Not needed for a `menu`, `panel` or `modal`. */\n run?(context: CommandContext<AppState>): void | Promise<unknown>;\n}\n\n/**\n * A command for each of a set of names, made from one definition, such as `tool:<id>` for every\n * tool a document has. Its commands resolve and run like any other, and `listCommands()` lists\n * one per name. A command defined with the same id wins over the family's.\n */\nexport interface CommandFamily {\n /** Where the commands' ids start: `'tool:'` makes `tool:highlight`. */\n readonly prefix: string;\n /** The names the command's document has, in order. Return the same array while nothing changed. */\n readonly names: (context: CommandContext) => readonly string[];\n /** The command for one name. A family's commands have no shortcuts. */\n readonly command: (name: string) => Omit<CommandDefinition, 'id' | 'shortcut'>;\n}\n\n/** A command as a button shows it: everything read for its document. */\nexport interface ResolvedCommand {\n readonly id: string;\n readonly label: string;\n readonly icon?: string;\n readonly iconAccent?: IconAccent;\n readonly shortcuts: readonly string[];\n readonly menu?: string;\n readonly enabled: boolean;\n readonly active: boolean;\n /**\n * Whether it's a toggle, pressed while `active`: it has an `active` of its own, or opens a panel.\n * Its button says `aria-pressed`, true or false; another button leaves it off. A command that\n * opens a menu or a dialog isn't one.\n */\n readonly pressable: boolean;\n readonly visible: boolean;\n readonly categories: readonly string[];\n /**\n * Why it's disabled, as a sentence for its tooltip: set when the scope doesn't allow it and\n * the `notAllowed` setting is `'disable'`, or when a lock holds the setting it changes.\n */\n readonly disabledReason?: string;\n}\n\n/**\n * Why a command won't run whatever the moment: it's turned off in this viewer\n * (`disabledCategories`, `disabledCommands`), the scope doesn't allow it (`requires`), or a lock\n * holds the setting it changes (`locked`). A command that only can't run right now (`enabled`,\n * `visible`) has no refusal.\n */\nexport interface CommandRefusal {\n readonly reason: 'turned-off' | 'not-allowed' | 'locked';\n /** A sentence for the user, translated through the i18n plugin when it's there. */\n readonly message: string;\n}\n\n/**\n * Whether two resolved commands show the same, for readers that compare what a command looks\n * like rather than which object holds it (a group of commands, or one command for two documents).\n */\nexport const resolvedCommandsEqual = (\n left: ResolvedCommand | null,\n right: ResolvedCommand | null,\n): boolean => {\n if (left === right) return true;\n if (!left || !right) return false;\n return (\n left.id === right.id &&\n left.label === right.label &&\n left.icon === right.icon &&\n left.iconAccent?.primary === right.iconAccent?.primary &&\n left.iconAccent?.secondary === right.iconAccent?.secondary &&\n left.menu === right.menu &&\n left.enabled === right.enabled &&\n left.active === right.active &&\n left.pressable === right.pressable &&\n left.visible === right.visible &&\n left.disabledReason === right.disabledReason &&\n left.shortcuts.length === right.shortcuts.length &&\n left.shortcuts.every((shortcut, index) => shortcut === right.shortcuts[index])\n );\n};\n\n/**\n * What a component or a toolbar draws for a command id no plugin registered: labelled with its\n * id, neither enabled nor visible, the way a turned-off command is.\n */\nexport const unregisteredCommand = (id: CommandId): ResolvedCommand => ({\n id,\n label: id,\n shortcuts: [],\n enabled: false,\n active: false,\n pressable: false,\n visible: false,\n categories: [],\n});\n\n/** What a component that asks for an id no plugin registered hears, in development. */\nexport const unknownCommandWarning = (id: CommandId, known: Iterable<CommandId>): string =>\n `no command \"${id}\"${didYouMean(id, known)}: it shows as neither visible nor enabled`;\n\n/** A command with everything a button needs: what it shows, `run`, and its shortcut for a tooltip. */\nexport interface BoundCommand extends ResolvedCommand {\n /** Run the command for the document it was read for. */\n readonly run: () => Promise<ExecuteResult>;\n /** Its first shortcut, formatted for the platform (`'⌘K'` on a Mac, `'Ctrl+K'` elsewhere), or `null`. */\n readonly shortcutLabel: string | null;\n}\n\n/**\n * A resolved command, bound for a button: `run` executes it through `execute`, and\n * `shortcutLabel` is its first shortcut formatted for the platform. Which platform is the\n * caller's to know (`isMacPlatform()` in `@embedpdf/web`).\n */\nexport function boundCommandOf(\n command: ResolvedCommand,\n execute: (id: CommandId) => Promise<ExecuteResult>,\n options: { readonly isMac: boolean },\n): BoundCommand {\n const [first] = command.shortcuts;\n return {\n ...command,\n run: () => execute(command.id),\n shortcutLabel: first === undefined ? null : formatShortcut(first, { isMac: options.isMac }),\n };\n}\n\n/**\n * The commands plugin's settings. `commandsPlugin(config)` registers them over\n * {@link COMMANDS_DEFAULTS}, and `updateSettings()` changes them while the app runs.\n */\nexport interface CommandsSettings {\n /** The commands your viewer has. A later definition with an id that's taken replaces the earlier one. */\n readonly commands: readonly (CommandDefinition | CommandFamily)[];\n /**\n * Your app's state, which every command's functions get as `appState`: values, and functions\n * that change them. A new value replaces the old one whole, and every command is asked again.\n */\n readonly appState: unknown;\n /**\n * Categories turned off, with every category under them: their commands are hidden and\n * refused wherever they appear.\n */\n readonly disabledCategories: readonly string[];\n /** Commands turned off one by one, by id: hidden and refused wherever they appear. */\n readonly disabledCommands: readonly CommandId[];\n /**\n * What a command the scope doesn't allow does: `'hide'` leaves it out, `'disable'` shows it\n * disabled, with the reason in its `disabledReason`.\n */\n readonly notAllowed: NotAllowedMode;\n}\n\n/** How a command shows when the scope doesn't allow it: hidden, or disabled with its reason. */\nexport type NotAllowedMode = 'hide' | 'disable';\n\n/** What the commands settings are when the app registers none. */\nexport const COMMANDS_DEFAULTS: CommandsSettings = {\n commands: [],\n appState: undefined,\n disabledCategories: [],\n disabledCommands: [],\n notAllowed: 'hide',\n};\n\n/** What `commandsPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type CommandsConfig<AppState = any> = Omit<\n DeepPartial<CommandsSettings>,\n 'commands' | 'appState'\n> & {\n readonly commands?: readonly (CommandDefinition<AppState> | CommandFamily)[];\n readonly appState?: AppState;\n};\n\nexport interface RegisterCommandOptions {\n /** Replace a command with the same id; without it, a taken id throws `conflict`. */\n replace?: boolean;\n}\n\nexport interface ExecuteOptions extends OperationOptions {\n /** The document to run it for; the document in scope, else the active one, when left out. */\n documentId?: string;\n /** Passed to the command's `run` and derivations as `args`. */\n args?: unknown;\n}\n\n/** How `execute()` went: it ran, or it was refused before running, and why. */\nexport type ExecuteResult =\n | { readonly status: 'executed' }\n | { readonly status: 'rejected'; readonly reason: 'not-found' | 'disabled' | 'hidden' };\n\n// ── events ──\nexport interface CommandExecutedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly args: unknown;\n}\nexport interface CommandExecutionFailedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly error: PluginErrorInfo;\n}\n\n/**\n * The commands. A call that leaves out the document is for the document in scope when the\n * capability was resolved for one (`ctx.forDocument`, a `<DocumentScope>`), and for the active\n * document otherwise.\n */\nexport interface CommandsCapability extends SettingsApi<CommandsSettings> {\n // ── the commands ──\n /**\n * Add a command while the app runs, and get a function that removes it. A taken id throws\n * `conflict` unless `replace`.\n */\n registerCommand(definition: CommandDefinition, options?: RegisterCommandOptions): Unsubscribe;\n /** `registerCommand` for several definitions; the function removes all of them. */\n registerCommands(\n definitions: readonly CommandDefinition[],\n options?: RegisterCommandOptions,\n ): Unsubscribe;\n /** Whether a command has this id; with a family, every id that starts with its prefix does. */\n hasCommand(id: CommandId): boolean;\n /** A command as you defined it, or `null`. */\n getCommand(id: CommandId): CommandDefinition | null;\n /** Every command's id for the active document, in the order they were added. The same array until one changes. */\n listCommandIds(): readonly CommandId[];\n\n // ── what a button shows ──\n /** A command as a button shows it, or `null` for an unknown id. The same object while nothing about it changed. */\n resolveCommand(id: CommandId, documentId?: string): ResolvedCommand | null;\n /** Every command, resolved, in the order they were added. The same array while nothing changed. */\n listCommands(documentId?: string): readonly ResolvedCommand[];\n /** The visible commands whose label or id contains the query, for a command palette. */\n searchCommands(query: string, documentId?: string): readonly ResolvedCommand[];\n /** Every shortcut with its command, for a keyboard help sheet. The same array until the commands change. */\n listShortcuts(): readonly { readonly commandId: CommandId; readonly shortcut: string }[];\n\n // ── running them ──\n /**\n * Run a command; resolves once its `run` has, with `{ status: 'executed' }` and\n * `onExecuted`, or `{ status: 'rejected', reason }` for a command that is unknown, hidden or\n * disabled (a command turned off is hidden). A `run` that throws fires `onExecutionFailed` and rejects with its `PluginError`;\n * the signal rejects `operation-cancelled`.\n */\n execute(id: CommandId, options?: ExecuteOptions): Promise<ExecuteResult>;\n /** Whether a command can run now: it exists, and is enabled and visible. */\n canExecute(id: CommandId, documentId?: string): boolean;\n /**\n * Why a command won't run whatever the moment: it's turned off, or not allowed for its\n * document. `null` when it may run (or only can't right now), and for an unknown id.\n */\n getRefusal(id: CommandId, documentId?: string): CommandRefusal | null;\n\n // ── turning commands off ──\n /** The categories turned off. */\n getDisabledCategories(): readonly string[];\n /** Whether a category is turned off: it, or a category it's under (`annotations` for `annotations.highlight`). */\n isCategoryDisabled(category: string): boolean;\n /** Turn a category off, with every category under it: the `disabledCategories` setting gains it. */\n disableCategory(category: string): void;\n /** Turn a category on again. */\n enableCategory(category: string): void;\n /** Replace the categories that are off. */\n setDisabledCategories(categories: readonly string[]): void;\n /** The commands turned off one by one. */\n getDisabledCommands(): readonly CommandId[];\n /** Whether a command is turned off: by its id, or through one of its categories. */\n isCommandDisabled(id: CommandId): boolean;\n /** Turn one command off: the `disabledCommands` setting gains it. */\n disableCommand(id: CommandId): void;\n /** Turn a command on again; it stays off while one of its categories is. */\n enableCommand(id: CommandId): void;\n /** Replace the commands that are off one by one. */\n setDisabledCommands(ids: readonly CommandId[]): void;\n\n // ── events ──\n /** A command ran. */\n readonly onExecuted: EventHook<CommandExecutedEvent>;\n /** A command's `run` threw; `execute` rejects with the same error. */\n readonly onExecutionFailed: EventHook<CommandExecutionFailedEvent>;\n}\n"],"mappings":";;;;;AAMA,MAAa,gBAAgB,sBAA0C,YAAY,EACjF,MAAM,6EACR,CAAC;;;;;;;AC0MD,MAAa,yBACX,MACA,UACY;CACZ,IAAI,SAAS,OAAO,OAAO;CAC3B,IAAI,CAAC,QAAQ,CAAC,OAAO,OAAO;CAC5B,OACE,KAAK,OAAO,MAAM,MAClB,KAAK,UAAU,MAAM,SACrB,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,YAAY,MAAM,YAAY,WAC/C,KAAK,YAAY,cAAc,MAAM,YAAY,aACjD,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,MAAM,WACvB,KAAK,WAAW,MAAM,UACtB,KAAK,cAAc,MAAM,aACzB,KAAK,YAAY,MAAM,WACvB,KAAK,mBAAmB,MAAM,kBAC9B,KAAK,UAAU,WAAW,MAAM,UAAU,UAC1C,KAAK,UAAU,OAAO,UAAU,UAAU,aAAa,MAAM,UAAU,MAAM;AAEjF;;;;;AAMA,MAAa,uBAAuB,QAAoC;CACtE;CACA,OAAO;CACP,WAAW,CAAC;CACZ,SAAS;CACT,QAAQ;CACR,WAAW;CACX,SAAS;CACT,YAAY,CAAC;AACf;;AAGA,MAAa,yBAAyB,IAAe,UACnD,eAAe,GAAG,GAAG,WAAW,IAAI,KAAK,EAAE;;;;;;AAe7C,SAAgB,eACd,SACA,SACA,SACc;CACd,MAAM,CAAC,SAAS,QAAQ;CACxB,OAAO;EACL,GAAG;EACH,WAAW,QAAQ,QAAQ,EAAE;EAC7B,eAAe,UAAU,KAAA,IAAY,OAAO,eAAe,OAAO,EAAE,OAAO,QAAQ,MAAM,CAAC;CAC5F;AACF;;AAgCA,MAAa,oBAAsC;CACjD,UAAU,CAAC;CACX,UAAU,KAAA;CACV,oBAAoB,CAAC;CACrB,kBAAkB,CAAC;CACnB,YAAY;AACd"}
|
|
1
|
+
{"version":3,"file":"contract-Cln8gHpa.js","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it to the host capability. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { CommandsCapability } from './contract';\n\nexport const CommandsToken = createCapabilityToken<CommandsCapability>('commands', {\n hint: `add commandsPlugin() from '@embedpdf/plugin-commands' to your plugins list`,\n});\n","/**\n * @embedpdf/plugin-commands/contract — the commands that toolbars, menus,\n * shortcuts and a command palette all show and run.\n *\n * A command's state is read from live state: `resolveCommand` asks the other\n * capabilities again after each store change (once, however many readers\n * ask), so every reader follows the kernel's one change stream, with no\n * events. Definitions hold functions, so they live in the settings and the\n * plugin's registry, never in state.\n */\nimport type {\n CapabilityToken,\n DeepPartial,\n EventHook,\n OperationOptions,\n Permission,\n PluginErrorInfo,\n SettingLock,\n SettingsApi,\n Unsubscribe,\n} from '@embedpdf/core';\nimport { didYouMean, formatShortcut } from '@embedpdf/core-ui';\n\nexport { CommandsToken } from './token';\n\nexport type CommandId = string;\n\n/**\n * What a command's derivations and `run` see: capabilities resolved for the command's document\n * (the one named, else the document in scope, else the active one), and your app's state.\n */\nexport interface CommandContext<AppState = any> {\n /** The command's document, or `null` when none is open. */\n readonly documentId: string | null;\n /** Your app's state, as the `appState` setting has it now: `any` until you give its type. */\n readonly appState: AppState;\n /** What the caller passed: `execute(id, { args })`. */\n readonly args?: unknown;\n /** Fires when the caller cancels `execute()`: pass it on to the calls `run` makes. */\n readonly signal?: AbortSignal;\n /** A capability, for the command's document when the plugin is document-scoped. Throws when it isn't available. */\n get<T>(token: CapabilityToken<T>): T;\n /** Like `get`, but `null` when the capability isn't available (no plugin, no document). */\n tryGet<T>(token: CapabilityToken<T>): T | null;\n}\n\n/**\n * Up to two colors that go with a command's icon, such as a tool's current color: data a\n * renderer may use (tint the icon, show a swatch), like `icon` itself.\n */\nexport interface IconAccent {\n /** The mark: a stroke, the markup or the text color. */\n readonly primary?: string;\n /** The fill, when there is one. */\n readonly secondary?: string;\n}\n\n/**\n * One command, as you define it. Its functions get your app's state as `AppState`; they're\n * methods, so a command typed for your state (`CommandDefinition<Review>`) goes wherever a command does.\n */\nexport interface CommandDefinition<AppState = any> {\n /** A unique name, by convention `area:action`: `'zoom:in'`, `'review:approve'`. */\n readonly id: string;\n /**\n * What the user sees. With `labelKey` too, it's what shows when no language has the key. Its\n * `{name}` slots take the values `labelParams` gives.\n */\n readonly label?: string;\n /**\n * A translation key for the label, read through the i18n plugin. Without the plugin, or a\n * string for the key, the command shows `label`, else the key. The string's `{name}` slots\n * take the values `labelParams` gives, and a number `count` picks its plural form.\n */\n readonly labelKey?: string;\n /** Your icon's name; your buttons turn it into an icon. */\n readonly icon?: string;\n /** Colors for the icon, read from live state like `active`. */\n iconAccent?(context: CommandContext<AppState>): IconAccent | null;\n /** A key such as `'Mod+K'` (`Mod` is Cmd on a Mac, Ctrl elsewhere), or a list of them. */\n readonly shortcut?: string | readonly string[];\n /**\n * Whether its shortcut also runs while the cursor is in a text field where the shortcuts\n * listen (a search box, a comment), as the viewer's Find does. Default false: a key typed in\n * a field is the field's.\n */\n readonly shortcutInTextFields?: boolean;\n /**\n * The features it belongs to, so turning one off turns it off: `['annotations.highlight']`.\n * Turning off a feature turns off every feature under it, on whole dotted parts: `annotations`\n * covers `annotations.highlight`, not `annotationsExtra`.\n */\n readonly categories?: readonly string[];\n /**\n * The scope permissions it needs, such as `'doc.annotate.modify'`, checked against its\n * document. Without them it's hidden, or shown disabled with its reason under the\n * `notAllowed: 'disable'` setting. With no document open there is nothing to check.\n */\n readonly requires?: readonly Permission[];\n /**\n * Whether the session may run it, from the plugins' `can*` checks\n * (`documents.canPrint()`), for a command whose permission is a plugin's to know. When it\n * says no, the command isn't allowed, as with `requires`. Asked only while a document is\n * open; one that throws allows it.\n */\n allowed?(context: CommandContext<AppState>): boolean;\n /**\n * The translation key of the sentence that says why `allowed` refused it, with `{label}` for\n * its label: `'commands.notAllowed.doc-print'`. Without it, or a string for it,\n * `commands.notAllowed.default`.\n */\n readonly notAllowedKey?: string;\n /**\n * The lock on the setting it changes, for a command that changes one\n * (`(context) => context.get(StageToken).getLock('spread')`), or `null`.\n * While a lock holds, it shows disabled, whatever the `notAllowed` setting\n * says, with the sentence under the lock's `reasonKey` (else\n * `commands.locked.default`) as its `disabledReason`; it stays `active` for\n * its own value. One that throws counts as unlocked.\n */\n locked?(context: CommandContext<AppState>): SettingLock | null;\n\n // ── what the command opens ───────────────────────────────────────────────\n // A command that opens a panel, menu or dialog says so instead of opening\n // it in `run`: it then needs no `run`, it shows as active while the surface\n // is open, and a button can show that it opens a menu.\n /** Opens and closes a menu of yours, by its id. */\n readonly menu?: string;\n /**\n * Opens and closes a panel, closing the others with the same `exclusive` tag. With `focus`,\n * opening it asks for the cursor (the shell's `open(id, { focus: true })`).\n */\n readonly panel?:\n | string\n | { readonly id: string; readonly exclusive?: string; readonly focus?: boolean };\n /** Opens and closes a dialog; one dialog is open at a time. */\n readonly modal?: string;\n\n // ── read from live state and your app's, again whenever either changes ──\n /** When it can run. Default: always. One that throws counts as false. */\n enabled?(context: CommandContext<AppState>): boolean;\n /** When it shows as pressed, such as the current tool. One that throws counts as false. */\n active?(context: CommandContext<AppState>): boolean;\n /** When it shows at all. Default: always. One that throws counts as false. */\n visible?(context: CommandContext<AppState>): boolean;\n /**\n * The values for its label's `{name}` slots, such as how many pages are selected:\n * `({ count: pageEdit.getSelected().length })`. A number `count` also picks the plural form of a\n * translated label. One that throws gives none, and the slots show as they are.\n */\n labelParams?(context: CommandContext<AppState>): Readonly<Record<string, string | number>>;\n\n /** What it does; `execute()` resolves once it has. Not needed for a `menu`, `panel` or `modal`. */\n run?(context: CommandContext<AppState>): void | Promise<unknown>;\n}\n\n/**\n * A command for each of a set of names, made from one definition, such as `tool:<id>` for every\n * tool a document has. Its commands resolve and run like any other, and `listCommands()` lists\n * one per name. A command defined with the same id wins over the family's.\n */\nexport interface CommandFamily {\n /** Where the commands' ids start: `'tool:'` makes `tool:highlight`. */\n readonly prefix: string;\n /** The names the command's document has, in order. Return the same array while nothing changed. */\n readonly names: (context: CommandContext) => readonly string[];\n /** The command for one name. A family's commands have no shortcuts. */\n readonly command: (name: string) => Omit<CommandDefinition, 'id' | 'shortcut'>;\n}\n\n/** A command as a button shows it: everything read for its document. */\nexport interface ResolvedCommand {\n readonly id: string;\n readonly label: string;\n readonly icon?: string;\n readonly iconAccent?: IconAccent;\n readonly shortcuts: readonly string[];\n readonly menu?: string;\n readonly enabled: boolean;\n readonly active: boolean;\n /**\n * Whether it's a toggle, pressed while `active`: it has an `active` of its own, or opens a panel.\n * Its button says `aria-pressed`, true or false; another button leaves it off. A command that\n * opens a menu or a dialog isn't one.\n */\n readonly pressable: boolean;\n readonly visible: boolean;\n readonly categories: readonly string[];\n /**\n * Why it's disabled, as a sentence for its tooltip: set when the scope doesn't allow it and\n * the `notAllowed` setting is `'disable'`, or when a lock holds the setting it changes.\n */\n readonly disabledReason?: string;\n}\n\n/**\n * Why a command won't run whatever the moment: it's turned off in this viewer\n * (`disabledCategories`, `disabledCommands`), the scope doesn't allow it (`requires`), or a lock\n * holds the setting it changes (`locked`). A command that only can't run right now (`enabled`,\n * `visible`) has no refusal.\n */\nexport interface CommandRefusal {\n readonly reason: 'turned-off' | 'not-allowed' | 'locked';\n /** A sentence for the user, translated through the i18n plugin when it's there. */\n readonly message: string;\n}\n\n/**\n * Whether two resolved commands show the same, for readers that compare what a command looks\n * like rather than which object holds it (a group of commands, or one command for two documents).\n */\nexport const resolvedCommandsEqual = (\n left: ResolvedCommand | null,\n right: ResolvedCommand | null,\n): boolean => {\n if (left === right) return true;\n if (!left || !right) return false;\n return (\n left.id === right.id &&\n left.label === right.label &&\n left.icon === right.icon &&\n left.iconAccent?.primary === right.iconAccent?.primary &&\n left.iconAccent?.secondary === right.iconAccent?.secondary &&\n left.menu === right.menu &&\n left.enabled === right.enabled &&\n left.active === right.active &&\n left.pressable === right.pressable &&\n left.visible === right.visible &&\n left.disabledReason === right.disabledReason &&\n left.shortcuts.length === right.shortcuts.length &&\n left.shortcuts.every((shortcut, index) => shortcut === right.shortcuts[index])\n );\n};\n\n/**\n * What a component or a toolbar draws for a command id no plugin registered: labelled with its\n * id, neither enabled nor visible, the way a turned-off command is.\n */\nexport const unregisteredCommand = (id: CommandId): ResolvedCommand => ({\n id,\n label: id,\n shortcuts: [],\n enabled: false,\n active: false,\n pressable: false,\n visible: false,\n categories: [],\n});\n\n/** What a component that asks for an id no plugin registered hears, in development. */\nexport const unknownCommandWarning = (id: CommandId, known: Iterable<CommandId>): string =>\n `no command \"${id}\"${didYouMean(id, known)}: it shows as neither visible nor enabled`;\n\n/** A command with everything a button needs: what it shows, `run`, and its shortcut for a tooltip. */\nexport interface BoundCommand extends ResolvedCommand {\n /** Run the command for the document it was read for. */\n readonly run: () => Promise<ExecuteResult>;\n /** Its first shortcut, formatted for the platform (`'⌘K'` on a Mac, `'Ctrl+K'` elsewhere), or `null`. */\n readonly shortcutLabel: string | null;\n}\n\n/**\n * A resolved command, bound for a button: `run` executes it through `execute`, and\n * `shortcutLabel` is its first shortcut formatted for the platform. Which platform is the\n * caller's to know (`isMacPlatform()` in `@embedpdf/web`).\n */\nexport function boundCommandOf(\n command: ResolvedCommand,\n execute: (id: CommandId) => Promise<ExecuteResult>,\n options: { readonly isMac: boolean },\n): BoundCommand {\n const [first] = command.shortcuts;\n return {\n ...command,\n run: () => execute(command.id),\n shortcutLabel: first === undefined ? null : formatShortcut(first, { isMac: options.isMac }),\n };\n}\n\n/**\n * The commands plugin's settings. `commandsPlugin(config)` registers them over\n * {@link COMMANDS_DEFAULTS}, and `updateSettings()` changes them while the app runs.\n */\nexport interface CommandsSettings {\n /** The commands your viewer has. A later definition with an id that's taken replaces the earlier one. */\n readonly commands: readonly (CommandDefinition | CommandFamily)[];\n /**\n * Your app's state, which every command's functions get as `appState`: values, and functions\n * that change them. A new value replaces the old one whole, and every command is asked again.\n */\n readonly appState: unknown;\n /**\n * Categories turned off, with every category under them: their commands are hidden and\n * refused wherever they appear.\n */\n readonly disabledCategories: readonly string[];\n /** Commands turned off one by one, by id: hidden and refused wherever they appear. */\n readonly disabledCommands: readonly CommandId[];\n /**\n * What a command the scope doesn't allow does: `'hide'` leaves it out, `'disable'` shows it\n * disabled, with the reason in its `disabledReason`.\n */\n readonly notAllowed: NotAllowedMode;\n}\n\n/** How a command shows when the scope doesn't allow it: hidden, or disabled with its reason. */\nexport type NotAllowedMode = 'hide' | 'disable';\n\n/** What the commands settings are when the app registers none. */\nexport const COMMANDS_DEFAULTS: CommandsSettings = {\n commands: [],\n appState: undefined,\n disabledCategories: [],\n disabledCommands: [],\n notAllowed: 'hide',\n};\n\n/** What `commandsPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type CommandsConfig<AppState = any> = Omit<\n DeepPartial<CommandsSettings>,\n 'commands' | 'appState'\n> & {\n readonly commands?: readonly (CommandDefinition<AppState> | CommandFamily)[];\n readonly appState?: AppState;\n};\n\nexport interface RegisterCommandOptions {\n /** Replace a command with the same id; without it, a taken id throws `conflict`. */\n replace?: boolean;\n}\n\nexport interface ExecuteOptions extends OperationOptions {\n /** The document to run it for; the document in scope, else the active one, when left out. */\n documentId?: string;\n /** Passed to the command's `run` and derivations as `args`. */\n args?: unknown;\n}\n\n/** How `execute()` went: it ran, or it was refused before running, and why. */\nexport type ExecuteResult =\n | { readonly status: 'executed' }\n | { readonly status: 'rejected'; readonly reason: 'not-found' | 'disabled' | 'hidden' };\n\n// ── events ──\nexport interface CommandExecutedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly args: unknown;\n}\nexport interface CommandExecutionFailedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly error: PluginErrorInfo;\n}\n\n/**\n * The commands. A call that leaves out the document is for the document in scope when the\n * capability was resolved for one (`ctx.forDocument`, a `<DocumentScope>`), and for the active\n * document otherwise.\n */\nexport interface CommandsCapability extends SettingsApi<CommandsSettings> {\n // ── the commands ──\n /**\n * Add a command while the app runs, and get a function that removes it. A taken id throws\n * `conflict` unless `replace`.\n */\n registerCommand(definition: CommandDefinition, options?: RegisterCommandOptions): Unsubscribe;\n /** `registerCommand` for several definitions; the function removes all of them. */\n registerCommands(\n definitions: readonly CommandDefinition[],\n options?: RegisterCommandOptions,\n ): Unsubscribe;\n /** Whether a command has this id; with a family, every id that starts with its prefix does. */\n hasCommand(id: CommandId): boolean;\n /** A command as you defined it, or `null`. */\n getCommand(id: CommandId): CommandDefinition | null;\n /** Every command's id for the active document, in the order they were added. The same array until one changes. */\n listCommandIds(): readonly CommandId[];\n\n // ── what a button shows ──\n /** A command as a button shows it, or `null` for an unknown id. The same object while nothing about it changed. */\n resolveCommand(id: CommandId, documentId?: string): ResolvedCommand | null;\n /** Every command, resolved, in the order they were added. The same array while nothing changed. */\n listCommands(documentId?: string): readonly ResolvedCommand[];\n /** The visible commands whose label or id contains the query, for a command palette. */\n searchCommands(query: string, documentId?: string): readonly ResolvedCommand[];\n /** Every shortcut with its command, for a keyboard help sheet. The same array until the commands change. */\n listShortcuts(): readonly { readonly commandId: CommandId; readonly shortcut: string }[];\n\n // ── running them ──\n /**\n * Run a command; resolves once its `run` has, with `{ status: 'executed' }` and\n * `onExecuted`, or `{ status: 'rejected', reason }` for a command that is unknown, hidden or\n * disabled (a command turned off is hidden). A `run` that throws fires `onExecutionFailed` and rejects with its `PluginError`;\n * the signal rejects `operation-cancelled`.\n */\n execute(id: CommandId, options?: ExecuteOptions): Promise<ExecuteResult>;\n /** Whether a command can run now: it exists, and is enabled and visible. */\n canExecute(id: CommandId, documentId?: string): boolean;\n /**\n * Why a command won't run whatever the moment: it's turned off, or not allowed for its\n * document. `null` when it may run (or only can't right now), and for an unknown id.\n */\n getRefusal(id: CommandId, documentId?: string): CommandRefusal | null;\n\n // ── turning commands off ──\n /** The categories turned off. */\n getDisabledCategories(): readonly string[];\n /** Whether a category is turned off: it, or a category it's under (`annotations` for `annotations.highlight`). */\n isCategoryDisabled(category: string): boolean;\n /** Turn a category off, with every category under it: the `disabledCategories` setting gains it. */\n disableCategory(category: string): void;\n /** Turn a category on again. */\n enableCategory(category: string): void;\n /** Replace the categories that are off. */\n setDisabledCategories(categories: readonly string[]): void;\n /** The commands turned off one by one. */\n getDisabledCommands(): readonly CommandId[];\n /** Whether a command is turned off: by its id, or through one of its categories. */\n isCommandDisabled(id: CommandId): boolean;\n /** Turn one command off: the `disabledCommands` setting gains it. */\n disableCommand(id: CommandId): void;\n /** Turn a command on again; it stays off while one of its categories is. */\n enableCommand(id: CommandId): void;\n /** Replace the commands that are off one by one. */\n setDisabledCommands(ids: readonly CommandId[]): void;\n\n // ── events ──\n /** A command ran. */\n readonly onExecuted: EventHook<CommandExecutedEvent>;\n /** A command's `run` threw; `execute` rejects with the same error. */\n readonly onExecutionFailed: EventHook<CommandExecutionFailedEvent>;\n}\n"],"mappings":";;;;;AAMA,MAAa,gBAAgB,sBAA0C,YAAY,EACjF,MAAM,6EACR,CAAC;;;;;;;AC2MD,MAAa,yBACX,MACA,UACY;CACZ,IAAI,SAAS,OAAO,OAAO;CAC3B,IAAI,CAAC,QAAQ,CAAC,OAAO,OAAO;CAC5B,OACE,KAAK,OAAO,MAAM,MAClB,KAAK,UAAU,MAAM,SACrB,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,YAAY,MAAM,YAAY,WAC/C,KAAK,YAAY,cAAc,MAAM,YAAY,aACjD,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,MAAM,WACvB,KAAK,WAAW,MAAM,UACtB,KAAK,cAAc,MAAM,aACzB,KAAK,YAAY,MAAM,WACvB,KAAK,mBAAmB,MAAM,kBAC9B,KAAK,UAAU,WAAW,MAAM,UAAU,UAC1C,KAAK,UAAU,OAAO,UAAU,UAAU,aAAa,MAAM,UAAU,MAAM;AAEjF;;;;;AAMA,MAAa,uBAAuB,QAAoC;CACtE;CACA,OAAO;CACP,WAAW,CAAC;CACZ,SAAS;CACT,QAAQ;CACR,WAAW;CACX,SAAS;CACT,YAAY,CAAC;AACf;;AAGA,MAAa,yBAAyB,IAAe,UACnD,eAAe,GAAG,GAAG,WAAW,IAAI,KAAK,EAAE;;;;;;AAe7C,SAAgB,eACd,SACA,SACA,SACc;CACd,MAAM,CAAC,SAAS,QAAQ;CACxB,OAAO;EACL,GAAG;EACH,WAAW,QAAQ,QAAQ,EAAE;EAC7B,eAAe,UAAU,KAAA,IAAY,OAAO,eAAe,OAAO,EAAE,OAAO,QAAQ,MAAM,CAAC;CAC5F;AACF;;AAgCA,MAAa,oBAAsC;CACjD,UAAU,CAAC;CACX,UAAU,KAAA;CACV,oBAAoB,CAAC;CACrB,kBAAkB,CAAC;CACnB,YAAY;AACd"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contract-DK9eNgkr.cjs","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it to the host capability. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { CommandsCapability } from './contract';\n\nexport const CommandsToken = createCapabilityToken<CommandsCapability>('commands', {\n hint: `add commandsPlugin() from '@embedpdf/plugin-commands' to your plugins list`,\n});\n","/**\n * @embedpdf/plugin-commands/contract — the commands that toolbars, menus,\n * shortcuts and a command palette all show and run.\n *\n * A command's state is read from live state: `resolveCommand` asks the other\n * capabilities when it's called, so every reader follows the kernel's one\n * change stream, with no events. Definitions hold functions, so they live in\n * the settings and the plugin's registry, never in state.\n */\nimport type {\n CapabilityToken,\n DeepPartial,\n EventHook,\n OperationOptions,\n Permission,\n PluginErrorInfo,\n SettingLock,\n SettingsApi,\n Unsubscribe,\n} from '@embedpdf/core';\nimport { didYouMean, formatShortcut } from '@embedpdf/core-ui';\n\nexport { CommandsToken } from './token';\n\nexport type CommandId = string;\n\n/**\n * What a command's derivations and `run` see: capabilities resolved for the command's document\n * (the one named, else the document in scope, else the active one), and your app's state.\n */\nexport interface CommandContext<AppState = any> {\n /** The command's document, or `null` when none is open. */\n readonly documentId: string | null;\n /** Your app's state, as the `appState` setting has it now: `any` until you give its type. */\n readonly appState: AppState;\n /** What the caller passed: `execute(id, { args })`. */\n readonly args?: unknown;\n /** Fires when the caller cancels `execute()`: pass it on to the calls `run` makes. */\n readonly signal?: AbortSignal;\n /** A capability, for the command's document when the plugin is document-scoped. Throws when it isn't available. */\n get<T>(token: CapabilityToken<T>): T;\n /** Like `get`, but `null` when the capability isn't available (no plugin, no document). */\n tryGet<T>(token: CapabilityToken<T>): T | null;\n}\n\n/**\n * Up to two colors that go with a command's icon, such as a tool's current color: data a\n * renderer may use (tint the icon, show a swatch), like `icon` itself.\n */\nexport interface IconAccent {\n /** The mark: a stroke, the markup or the text color. */\n readonly primary?: string;\n /** The fill, when there is one. */\n readonly secondary?: string;\n}\n\n/**\n * One command, as you define it. Its functions get your app's state as `AppState`; they're\n * methods, so a command typed for your state (`CommandDefinition<Review>`) goes wherever a command does.\n */\nexport interface CommandDefinition<AppState = any> {\n /** A unique name, by convention `area:action`: `'zoom:in'`, `'review:approve'`. */\n readonly id: string;\n /**\n * What the user sees. With `labelKey` too, it's what shows when no language has the key. Its\n * `{name}` slots take the values `labelParams` gives.\n */\n readonly label?: string;\n /**\n * A translation key for the label, read through the i18n plugin. Without the plugin, or a\n * string for the key, the command shows `label`, else the key. The string's `{name}` slots\n * take the values `labelParams` gives, and a number `count` picks its plural form.\n */\n readonly labelKey?: string;\n /** Your icon's name; your buttons turn it into an icon. */\n readonly icon?: string;\n /** Colors for the icon, read from live state like `active`. */\n iconAccent?(context: CommandContext<AppState>): IconAccent | null;\n /** A key such as `'Mod+K'` (`Mod` is Cmd on a Mac, Ctrl elsewhere), or a list of them. */\n readonly shortcut?: string | readonly string[];\n /**\n * Whether its shortcut also runs while the cursor is in a text field where the shortcuts\n * listen (a search box, a comment), as the viewer's Find does. Default false: a key typed in\n * a field is the field's.\n */\n readonly shortcutInTextFields?: boolean;\n /**\n * The features it belongs to, so turning one off turns it off: `['annotations.highlight']`.\n * Turning off a feature turns off every feature under it, on whole dotted parts: `annotations`\n * covers `annotations.highlight`, not `annotationsExtra`.\n */\n readonly categories?: readonly string[];\n /**\n * The scope permissions it needs, such as `'doc.annotate.modify'`, checked against its\n * document. Without them it's hidden, or shown disabled with its reason under the\n * `notAllowed: 'disable'` setting. With no document open there is nothing to check.\n */\n readonly requires?: readonly Permission[];\n /**\n * Whether the session may run it, from the plugins' `can*` checks\n * (`documents.canPrint()`), for a command whose permission is a plugin's to know. When it\n * says no, the command isn't allowed, as with `requires`. Asked only while a document is\n * open; one that throws allows it.\n */\n allowed?(context: CommandContext<AppState>): boolean;\n /**\n * The translation key of the sentence that says why `allowed` refused it, with `{label}` for\n * its label: `'commands.notAllowed.doc-print'`. Without it, or a string for it,\n * `commands.notAllowed.default`.\n */\n readonly notAllowedKey?: string;\n /**\n * The lock on the setting it changes, for a command that changes one\n * (`(context) => context.get(StageToken).getLock('spread')`), or `null`.\n * While a lock holds, it shows disabled, whatever the `notAllowed` setting\n * says, with the sentence under the lock's `reasonKey` (else\n * `commands.locked.default`) as its `disabledReason`; it stays `active` for\n * its own value. One that throws counts as unlocked.\n */\n locked?(context: CommandContext<AppState>): SettingLock | null;\n\n // ── what the command opens ───────────────────────────────────────────────\n // A command that opens a panel, menu or dialog says so instead of opening\n // it in `run`: it then needs no `run`, it shows as active while the surface\n // is open, and a button can show that it opens a menu.\n /** Opens and closes a menu of yours, by its id. */\n readonly menu?: string;\n /**\n * Opens and closes a panel, closing the others with the same `exclusive` tag. With `focus`,\n * opening it asks for the cursor (the shell's `open(id, { focus: true })`).\n */\n readonly panel?:\n | string\n | { readonly id: string; readonly exclusive?: string; readonly focus?: boolean };\n /** Opens and closes a dialog; one dialog is open at a time. */\n readonly modal?: string;\n\n // ── read from live state and your app's, again whenever either changes ──\n /** When it can run. Default: always. One that throws counts as false. */\n enabled?(context: CommandContext<AppState>): boolean;\n /** When it shows as pressed, such as the current tool. One that throws counts as false. */\n active?(context: CommandContext<AppState>): boolean;\n /** When it shows at all. Default: always. One that throws counts as false. */\n visible?(context: CommandContext<AppState>): boolean;\n /**\n * The values for its label's `{name}` slots, such as how many pages are selected:\n * `({ count: pageEdit.getSelected().length })`. A number `count` also picks the plural form of a\n * translated label. One that throws gives none, and the slots show as they are.\n */\n labelParams?(context: CommandContext<AppState>): Readonly<Record<string, string | number>>;\n\n /** What it does; `execute()` resolves once it has. Not needed for a `menu`, `panel` or `modal`. */\n run?(context: CommandContext<AppState>): void | Promise<unknown>;\n}\n\n/**\n * A command for each of a set of names, made from one definition, such as `tool:<id>` for every\n * tool a document has. Its commands resolve and run like any other, and `listCommands()` lists\n * one per name. A command defined with the same id wins over the family's.\n */\nexport interface CommandFamily {\n /** Where the commands' ids start: `'tool:'` makes `tool:highlight`. */\n readonly prefix: string;\n /** The names the command's document has, in order. Return the same array while nothing changed. */\n readonly names: (context: CommandContext) => readonly string[];\n /** The command for one name. A family's commands have no shortcuts. */\n readonly command: (name: string) => Omit<CommandDefinition, 'id' | 'shortcut'>;\n}\n\n/** A command as a button shows it: everything read for its document. */\nexport interface ResolvedCommand {\n readonly id: string;\n readonly label: string;\n readonly icon?: string;\n readonly iconAccent?: IconAccent;\n readonly shortcuts: readonly string[];\n readonly menu?: string;\n readonly enabled: boolean;\n readonly active: boolean;\n /**\n * Whether it's a toggle, pressed while `active`: it has an `active` of its own, or opens a panel.\n * Its button says `aria-pressed`, true or false; another button leaves it off. A command that\n * opens a menu or a dialog isn't one.\n */\n readonly pressable: boolean;\n readonly visible: boolean;\n readonly categories: readonly string[];\n /**\n * Why it's disabled, as a sentence for its tooltip: set when the scope doesn't allow it and\n * the `notAllowed` setting is `'disable'`, or when a lock holds the setting it changes.\n */\n readonly disabledReason?: string;\n}\n\n/**\n * Why a command won't run whatever the moment: it's turned off in this viewer\n * (`disabledCategories`, `disabledCommands`), the scope doesn't allow it (`requires`), or a lock\n * holds the setting it changes (`locked`). A command that only can't run right now (`enabled`,\n * `visible`) has no refusal.\n */\nexport interface CommandRefusal {\n readonly reason: 'turned-off' | 'not-allowed' | 'locked';\n /** A sentence for the user, translated through the i18n plugin when it's there. */\n readonly message: string;\n}\n\n/**\n * Whether two resolved commands show the same, for readers that compare what a command looks\n * like rather than which object holds it (a group of commands, or one command for two documents).\n */\nexport const resolvedCommandsEqual = (\n left: ResolvedCommand | null,\n right: ResolvedCommand | null,\n): boolean => {\n if (left === right) return true;\n if (!left || !right) return false;\n return (\n left.id === right.id &&\n left.label === right.label &&\n left.icon === right.icon &&\n left.iconAccent?.primary === right.iconAccent?.primary &&\n left.iconAccent?.secondary === right.iconAccent?.secondary &&\n left.menu === right.menu &&\n left.enabled === right.enabled &&\n left.active === right.active &&\n left.pressable === right.pressable &&\n left.visible === right.visible &&\n left.disabledReason === right.disabledReason &&\n left.shortcuts.length === right.shortcuts.length &&\n left.shortcuts.every((shortcut, index) => shortcut === right.shortcuts[index])\n );\n};\n\n/**\n * What a component or a toolbar draws for a command id no plugin registered: labelled with its\n * id, neither enabled nor visible, the way a turned-off command is.\n */\nexport const unregisteredCommand = (id: CommandId): ResolvedCommand => ({\n id,\n label: id,\n shortcuts: [],\n enabled: false,\n active: false,\n pressable: false,\n visible: false,\n categories: [],\n});\n\n/** What a component that asks for an id no plugin registered hears, in development. */\nexport const unknownCommandWarning = (id: CommandId, known: Iterable<CommandId>): string =>\n `no command \"${id}\"${didYouMean(id, known)}: it shows as neither visible nor enabled`;\n\n/** A command with everything a button needs: what it shows, `run`, and its shortcut for a tooltip. */\nexport interface BoundCommand extends ResolvedCommand {\n /** Run the command for the document it was read for. */\n readonly run: () => Promise<ExecuteResult>;\n /** Its first shortcut, formatted for the platform (`'⌘K'` on a Mac, `'Ctrl+K'` elsewhere), or `null`. */\n readonly shortcutLabel: string | null;\n}\n\n/**\n * A resolved command, bound for a button: `run` executes it through `execute`, and\n * `shortcutLabel` is its first shortcut formatted for the platform. Which platform is the\n * caller's to know (`isMacPlatform()` in `@embedpdf/web`).\n */\nexport function boundCommandOf(\n command: ResolvedCommand,\n execute: (id: CommandId) => Promise<ExecuteResult>,\n options: { readonly isMac: boolean },\n): BoundCommand {\n const [first] = command.shortcuts;\n return {\n ...command,\n run: () => execute(command.id),\n shortcutLabel: first === undefined ? null : formatShortcut(first, { isMac: options.isMac }),\n };\n}\n\n/**\n * The commands plugin's settings. `commandsPlugin(config)` registers them over\n * {@link COMMANDS_DEFAULTS}, and `updateSettings()` changes them while the app runs.\n */\nexport interface CommandsSettings {\n /** The commands your viewer has. A later definition with an id that's taken replaces the earlier one. */\n readonly commands: readonly (CommandDefinition | CommandFamily)[];\n /**\n * Your app's state, which every command's functions get as `appState`: values, and functions\n * that change them. A new value replaces the old one whole, and every command is asked again.\n */\n readonly appState: unknown;\n /**\n * Categories turned off, with every category under them: their commands are hidden and\n * refused wherever they appear.\n */\n readonly disabledCategories: readonly string[];\n /** Commands turned off one by one, by id: hidden and refused wherever they appear. */\n readonly disabledCommands: readonly CommandId[];\n /**\n * What a command the scope doesn't allow does: `'hide'` leaves it out, `'disable'` shows it\n * disabled, with the reason in its `disabledReason`.\n */\n readonly notAllowed: NotAllowedMode;\n}\n\n/** How a command shows when the scope doesn't allow it: hidden, or disabled with its reason. */\nexport type NotAllowedMode = 'hide' | 'disable';\n\n/** What the commands settings are when the app registers none. */\nexport const COMMANDS_DEFAULTS: CommandsSettings = {\n commands: [],\n appState: undefined,\n disabledCategories: [],\n disabledCommands: [],\n notAllowed: 'hide',\n};\n\n/** What `commandsPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type CommandsConfig<AppState = any> = Omit<\n DeepPartial<CommandsSettings>,\n 'commands' | 'appState'\n> & {\n readonly commands?: readonly (CommandDefinition<AppState> | CommandFamily)[];\n readonly appState?: AppState;\n};\n\nexport interface RegisterCommandOptions {\n /** Replace a command with the same id; without it, a taken id throws `conflict`. */\n replace?: boolean;\n}\n\nexport interface ExecuteOptions extends OperationOptions {\n /** The document to run it for; the document in scope, else the active one, when left out. */\n documentId?: string;\n /** Passed to the command's `run` and derivations as `args`. */\n args?: unknown;\n}\n\n/** How `execute()` went: it ran, or it was refused before running, and why. */\nexport type ExecuteResult =\n | { readonly status: 'executed' }\n | { readonly status: 'rejected'; readonly reason: 'not-found' | 'disabled' | 'hidden' };\n\n// ── events ──\nexport interface CommandExecutedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly args: unknown;\n}\nexport interface CommandExecutionFailedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly error: PluginErrorInfo;\n}\n\n/**\n * The commands. A call that leaves out the document is for the document in scope when the\n * capability was resolved for one (`ctx.forDocument`, a `<DocumentScope>`), and for the active\n * document otherwise.\n */\nexport interface CommandsCapability extends SettingsApi<CommandsSettings> {\n // ── the commands ──\n /**\n * Add a command while the app runs, and get a function that removes it. A taken id throws\n * `conflict` unless `replace`.\n */\n registerCommand(definition: CommandDefinition, options?: RegisterCommandOptions): Unsubscribe;\n /** `registerCommand` for several definitions; the function removes all of them. */\n registerCommands(\n definitions: readonly CommandDefinition[],\n options?: RegisterCommandOptions,\n ): Unsubscribe;\n /** Whether a command has this id; with a family, every id that starts with its prefix does. */\n hasCommand(id: CommandId): boolean;\n /** A command as you defined it, or `null`. */\n getCommand(id: CommandId): CommandDefinition | null;\n /** Every command's id for the active document, in the order they were added. The same array until one changes. */\n listCommandIds(): readonly CommandId[];\n\n // ── what a button shows ──\n /** A command as a button shows it, or `null` for an unknown id. The same object while nothing about it changed. */\n resolveCommand(id: CommandId, documentId?: string): ResolvedCommand | null;\n /** Every command, resolved, in the order they were added. The same array while nothing changed. */\n listCommands(documentId?: string): readonly ResolvedCommand[];\n /** The visible commands whose label or id contains the query, for a command palette. */\n searchCommands(query: string, documentId?: string): readonly ResolvedCommand[];\n /** Every shortcut with its command, for a keyboard help sheet. The same array until the commands change. */\n listShortcuts(): readonly { readonly commandId: CommandId; readonly shortcut: string }[];\n\n // ── running them ──\n /**\n * Run a command; resolves once its `run` has, with `{ status: 'executed' }` and\n * `onExecuted`, or `{ status: 'rejected', reason }` for a command that is unknown, hidden or\n * disabled (a command turned off is hidden). A `run` that throws fires `onExecutionFailed` and rejects with its `PluginError`;\n * the signal rejects `operation-cancelled`.\n */\n execute(id: CommandId, options?: ExecuteOptions): Promise<ExecuteResult>;\n /** Whether a command can run now: it exists, and is enabled and visible. */\n canExecute(id: CommandId, documentId?: string): boolean;\n /**\n * Why a command won't run whatever the moment: it's turned off, or not allowed for its\n * document. `null` when it may run (or only can't right now), and for an unknown id.\n */\n getRefusal(id: CommandId, documentId?: string): CommandRefusal | null;\n\n // ── turning commands off ──\n /** The categories turned off. */\n getDisabledCategories(): readonly string[];\n /** Whether a category is turned off: it, or a category it's under (`annotations` for `annotations.highlight`). */\n isCategoryDisabled(category: string): boolean;\n /** Turn a category off, with every category under it: the `disabledCategories` setting gains it. */\n disableCategory(category: string): void;\n /** Turn a category on again. */\n enableCategory(category: string): void;\n /** Replace the categories that are off. */\n setDisabledCategories(categories: readonly string[]): void;\n /** The commands turned off one by one. */\n getDisabledCommands(): readonly CommandId[];\n /** Whether a command is turned off: by its id, or through one of its categories. */\n isCommandDisabled(id: CommandId): boolean;\n /** Turn one command off: the `disabledCommands` setting gains it. */\n disableCommand(id: CommandId): void;\n /** Turn a command on again; it stays off while one of its categories is. */\n enableCommand(id: CommandId): void;\n /** Replace the commands that are off one by one. */\n setDisabledCommands(ids: readonly CommandId[]): void;\n\n // ── events ──\n /** A command ran. */\n readonly onExecuted: EventHook<CommandExecutedEvent>;\n /** A command's `run` threw; `execute` rejects with the same error. */\n readonly onExecutionFailed: EventHook<CommandExecutionFailedEvent>;\n}\n"],"mappings":";;;;;AAMA,MAAa,iBAAA,GAAA,eAAA,sBAAA,CAA0D,YAAY,EACjF,MAAM,6EACR,CAAC;;;;;;;AC0MD,MAAa,yBACX,MACA,UACY;CACZ,IAAI,SAAS,OAAO,OAAO;CAC3B,IAAI,CAAC,QAAQ,CAAC,OAAO,OAAO;CAC5B,OACE,KAAK,OAAO,MAAM,MAClB,KAAK,UAAU,MAAM,SACrB,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,YAAY,MAAM,YAAY,WAC/C,KAAK,YAAY,cAAc,MAAM,YAAY,aACjD,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,MAAM,WACvB,KAAK,WAAW,MAAM,UACtB,KAAK,cAAc,MAAM,aACzB,KAAK,YAAY,MAAM,WACvB,KAAK,mBAAmB,MAAM,kBAC9B,KAAK,UAAU,WAAW,MAAM,UAAU,UAC1C,KAAK,UAAU,OAAO,UAAU,UAAU,aAAa,MAAM,UAAU,MAAM;AAEjF;;;;;AAMA,MAAa,uBAAuB,QAAoC;CACtE;CACA,OAAO;CACP,WAAW,CAAC;CACZ,SAAS;CACT,QAAQ;CACR,WAAW;CACX,SAAS;CACT,YAAY,CAAC;AACf;;AAGA,MAAa,yBAAyB,IAAe,UACnD,eAAe,GAAG,IAAA,GAAA,kBAAA,WAAA,CAAc,IAAI,KAAK,EAAE;;;;;;AAe7C,SAAgB,eACd,SACA,SACA,SACc;CACd,MAAM,CAAC,SAAS,QAAQ;CACxB,OAAO;EACL,GAAG;EACH,WAAW,QAAQ,QAAQ,EAAE;EAC7B,eAAe,UAAU,KAAA,IAAY,QAAA,GAAA,kBAAA,eAAA,CAAsB,OAAO,EAAE,OAAO,QAAQ,MAAM,CAAC;CAC5F;AACF;;AAgCA,MAAa,oBAAsC;CACjD,UAAU,CAAC;CACX,UAAU,KAAA;CACV,oBAAoB,CAAC;CACrB,kBAAkB,CAAC;CACnB,YAAY;AACd"}
|
|
1
|
+
{"version":3,"file":"contract-DK9eNgkr.cjs","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it to the host capability. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { CommandsCapability } from './contract';\n\nexport const CommandsToken = createCapabilityToken<CommandsCapability>('commands', {\n hint: `add commandsPlugin() from '@embedpdf/plugin-commands' to your plugins list`,\n});\n","/**\n * @embedpdf/plugin-commands/contract — the commands that toolbars, menus,\n * shortcuts and a command palette all show and run.\n *\n * A command's state is read from live state: `resolveCommand` asks the other\n * capabilities again after each store change (once, however many readers\n * ask), so every reader follows the kernel's one change stream, with no\n * events. Definitions hold functions, so they live in the settings and the\n * plugin's registry, never in state.\n */\nimport type {\n CapabilityToken,\n DeepPartial,\n EventHook,\n OperationOptions,\n Permission,\n PluginErrorInfo,\n SettingLock,\n SettingsApi,\n Unsubscribe,\n} from '@embedpdf/core';\nimport { didYouMean, formatShortcut } from '@embedpdf/core-ui';\n\nexport { CommandsToken } from './token';\n\nexport type CommandId = string;\n\n/**\n * What a command's derivations and `run` see: capabilities resolved for the command's document\n * (the one named, else the document in scope, else the active one), and your app's state.\n */\nexport interface CommandContext<AppState = any> {\n /** The command's document, or `null` when none is open. */\n readonly documentId: string | null;\n /** Your app's state, as the `appState` setting has it now: `any` until you give its type. */\n readonly appState: AppState;\n /** What the caller passed: `execute(id, { args })`. */\n readonly args?: unknown;\n /** Fires when the caller cancels `execute()`: pass it on to the calls `run` makes. */\n readonly signal?: AbortSignal;\n /** A capability, for the command's document when the plugin is document-scoped. Throws when it isn't available. */\n get<T>(token: CapabilityToken<T>): T;\n /** Like `get`, but `null` when the capability isn't available (no plugin, no document). */\n tryGet<T>(token: CapabilityToken<T>): T | null;\n}\n\n/**\n * Up to two colors that go with a command's icon, such as a tool's current color: data a\n * renderer may use (tint the icon, show a swatch), like `icon` itself.\n */\nexport interface IconAccent {\n /** The mark: a stroke, the markup or the text color. */\n readonly primary?: string;\n /** The fill, when there is one. */\n readonly secondary?: string;\n}\n\n/**\n * One command, as you define it. Its functions get your app's state as `AppState`; they're\n * methods, so a command typed for your state (`CommandDefinition<Review>`) goes wherever a command does.\n */\nexport interface CommandDefinition<AppState = any> {\n /** A unique name, by convention `area:action`: `'zoom:in'`, `'review:approve'`. */\n readonly id: string;\n /**\n * What the user sees. With `labelKey` too, it's what shows when no language has the key. Its\n * `{name}` slots take the values `labelParams` gives.\n */\n readonly label?: string;\n /**\n * A translation key for the label, read through the i18n plugin. Without the plugin, or a\n * string for the key, the command shows `label`, else the key. The string's `{name}` slots\n * take the values `labelParams` gives, and a number `count` picks its plural form.\n */\n readonly labelKey?: string;\n /** Your icon's name; your buttons turn it into an icon. */\n readonly icon?: string;\n /** Colors for the icon, read from live state like `active`. */\n iconAccent?(context: CommandContext<AppState>): IconAccent | null;\n /** A key such as `'Mod+K'` (`Mod` is Cmd on a Mac, Ctrl elsewhere), or a list of them. */\n readonly shortcut?: string | readonly string[];\n /**\n * Whether its shortcut also runs while the cursor is in a text field where the shortcuts\n * listen (a search box, a comment), as the viewer's Find does. Default false: a key typed in\n * a field is the field's.\n */\n readonly shortcutInTextFields?: boolean;\n /**\n * The features it belongs to, so turning one off turns it off: `['annotations.highlight']`.\n * Turning off a feature turns off every feature under it, on whole dotted parts: `annotations`\n * covers `annotations.highlight`, not `annotationsExtra`.\n */\n readonly categories?: readonly string[];\n /**\n * The scope permissions it needs, such as `'doc.annotate.modify'`, checked against its\n * document. Without them it's hidden, or shown disabled with its reason under the\n * `notAllowed: 'disable'` setting. With no document open there is nothing to check.\n */\n readonly requires?: readonly Permission[];\n /**\n * Whether the session may run it, from the plugins' `can*` checks\n * (`documents.canPrint()`), for a command whose permission is a plugin's to know. When it\n * says no, the command isn't allowed, as with `requires`. Asked only while a document is\n * open; one that throws allows it.\n */\n allowed?(context: CommandContext<AppState>): boolean;\n /**\n * The translation key of the sentence that says why `allowed` refused it, with `{label}` for\n * its label: `'commands.notAllowed.doc-print'`. Without it, or a string for it,\n * `commands.notAllowed.default`.\n */\n readonly notAllowedKey?: string;\n /**\n * The lock on the setting it changes, for a command that changes one\n * (`(context) => context.get(StageToken).getLock('spread')`), or `null`.\n * While a lock holds, it shows disabled, whatever the `notAllowed` setting\n * says, with the sentence under the lock's `reasonKey` (else\n * `commands.locked.default`) as its `disabledReason`; it stays `active` for\n * its own value. One that throws counts as unlocked.\n */\n locked?(context: CommandContext<AppState>): SettingLock | null;\n\n // ── what the command opens ───────────────────────────────────────────────\n // A command that opens a panel, menu or dialog says so instead of opening\n // it in `run`: it then needs no `run`, it shows as active while the surface\n // is open, and a button can show that it opens a menu.\n /** Opens and closes a menu of yours, by its id. */\n readonly menu?: string;\n /**\n * Opens and closes a panel, closing the others with the same `exclusive` tag. With `focus`,\n * opening it asks for the cursor (the shell's `open(id, { focus: true })`).\n */\n readonly panel?:\n | string\n | { readonly id: string; readonly exclusive?: string; readonly focus?: boolean };\n /** Opens and closes a dialog; one dialog is open at a time. */\n readonly modal?: string;\n\n // ── read from live state and your app's, again whenever either changes ──\n /** When it can run. Default: always. One that throws counts as false. */\n enabled?(context: CommandContext<AppState>): boolean;\n /** When it shows as pressed, such as the current tool. One that throws counts as false. */\n active?(context: CommandContext<AppState>): boolean;\n /** When it shows at all. Default: always. One that throws counts as false. */\n visible?(context: CommandContext<AppState>): boolean;\n /**\n * The values for its label's `{name}` slots, such as how many pages are selected:\n * `({ count: pageEdit.getSelected().length })`. A number `count` also picks the plural form of a\n * translated label. One that throws gives none, and the slots show as they are.\n */\n labelParams?(context: CommandContext<AppState>): Readonly<Record<string, string | number>>;\n\n /** What it does; `execute()` resolves once it has. Not needed for a `menu`, `panel` or `modal`. */\n run?(context: CommandContext<AppState>): void | Promise<unknown>;\n}\n\n/**\n * A command for each of a set of names, made from one definition, such as `tool:<id>` for every\n * tool a document has. Its commands resolve and run like any other, and `listCommands()` lists\n * one per name. A command defined with the same id wins over the family's.\n */\nexport interface CommandFamily {\n /** Where the commands' ids start: `'tool:'` makes `tool:highlight`. */\n readonly prefix: string;\n /** The names the command's document has, in order. Return the same array while nothing changed. */\n readonly names: (context: CommandContext) => readonly string[];\n /** The command for one name. A family's commands have no shortcuts. */\n readonly command: (name: string) => Omit<CommandDefinition, 'id' | 'shortcut'>;\n}\n\n/** A command as a button shows it: everything read for its document. */\nexport interface ResolvedCommand {\n readonly id: string;\n readonly label: string;\n readonly icon?: string;\n readonly iconAccent?: IconAccent;\n readonly shortcuts: readonly string[];\n readonly menu?: string;\n readonly enabled: boolean;\n readonly active: boolean;\n /**\n * Whether it's a toggle, pressed while `active`: it has an `active` of its own, or opens a panel.\n * Its button says `aria-pressed`, true or false; another button leaves it off. A command that\n * opens a menu or a dialog isn't one.\n */\n readonly pressable: boolean;\n readonly visible: boolean;\n readonly categories: readonly string[];\n /**\n * Why it's disabled, as a sentence for its tooltip: set when the scope doesn't allow it and\n * the `notAllowed` setting is `'disable'`, or when a lock holds the setting it changes.\n */\n readonly disabledReason?: string;\n}\n\n/**\n * Why a command won't run whatever the moment: it's turned off in this viewer\n * (`disabledCategories`, `disabledCommands`), the scope doesn't allow it (`requires`), or a lock\n * holds the setting it changes (`locked`). A command that only can't run right now (`enabled`,\n * `visible`) has no refusal.\n */\nexport interface CommandRefusal {\n readonly reason: 'turned-off' | 'not-allowed' | 'locked';\n /** A sentence for the user, translated through the i18n plugin when it's there. */\n readonly message: string;\n}\n\n/**\n * Whether two resolved commands show the same, for readers that compare what a command looks\n * like rather than which object holds it (a group of commands, or one command for two documents).\n */\nexport const resolvedCommandsEqual = (\n left: ResolvedCommand | null,\n right: ResolvedCommand | null,\n): boolean => {\n if (left === right) return true;\n if (!left || !right) return false;\n return (\n left.id === right.id &&\n left.label === right.label &&\n left.icon === right.icon &&\n left.iconAccent?.primary === right.iconAccent?.primary &&\n left.iconAccent?.secondary === right.iconAccent?.secondary &&\n left.menu === right.menu &&\n left.enabled === right.enabled &&\n left.active === right.active &&\n left.pressable === right.pressable &&\n left.visible === right.visible &&\n left.disabledReason === right.disabledReason &&\n left.shortcuts.length === right.shortcuts.length &&\n left.shortcuts.every((shortcut, index) => shortcut === right.shortcuts[index])\n );\n};\n\n/**\n * What a component or a toolbar draws for a command id no plugin registered: labelled with its\n * id, neither enabled nor visible, the way a turned-off command is.\n */\nexport const unregisteredCommand = (id: CommandId): ResolvedCommand => ({\n id,\n label: id,\n shortcuts: [],\n enabled: false,\n active: false,\n pressable: false,\n visible: false,\n categories: [],\n});\n\n/** What a component that asks for an id no plugin registered hears, in development. */\nexport const unknownCommandWarning = (id: CommandId, known: Iterable<CommandId>): string =>\n `no command \"${id}\"${didYouMean(id, known)}: it shows as neither visible nor enabled`;\n\n/** A command with everything a button needs: what it shows, `run`, and its shortcut for a tooltip. */\nexport interface BoundCommand extends ResolvedCommand {\n /** Run the command for the document it was read for. */\n readonly run: () => Promise<ExecuteResult>;\n /** Its first shortcut, formatted for the platform (`'⌘K'` on a Mac, `'Ctrl+K'` elsewhere), or `null`. */\n readonly shortcutLabel: string | null;\n}\n\n/**\n * A resolved command, bound for a button: `run` executes it through `execute`, and\n * `shortcutLabel` is its first shortcut formatted for the platform. Which platform is the\n * caller's to know (`isMacPlatform()` in `@embedpdf/web`).\n */\nexport function boundCommandOf(\n command: ResolvedCommand,\n execute: (id: CommandId) => Promise<ExecuteResult>,\n options: { readonly isMac: boolean },\n): BoundCommand {\n const [first] = command.shortcuts;\n return {\n ...command,\n run: () => execute(command.id),\n shortcutLabel: first === undefined ? null : formatShortcut(first, { isMac: options.isMac }),\n };\n}\n\n/**\n * The commands plugin's settings. `commandsPlugin(config)` registers them over\n * {@link COMMANDS_DEFAULTS}, and `updateSettings()` changes them while the app runs.\n */\nexport interface CommandsSettings {\n /** The commands your viewer has. A later definition with an id that's taken replaces the earlier one. */\n readonly commands: readonly (CommandDefinition | CommandFamily)[];\n /**\n * Your app's state, which every command's functions get as `appState`: values, and functions\n * that change them. A new value replaces the old one whole, and every command is asked again.\n */\n readonly appState: unknown;\n /**\n * Categories turned off, with every category under them: their commands are hidden and\n * refused wherever they appear.\n */\n readonly disabledCategories: readonly string[];\n /** Commands turned off one by one, by id: hidden and refused wherever they appear. */\n readonly disabledCommands: readonly CommandId[];\n /**\n * What a command the scope doesn't allow does: `'hide'` leaves it out, `'disable'` shows it\n * disabled, with the reason in its `disabledReason`.\n */\n readonly notAllowed: NotAllowedMode;\n}\n\n/** How a command shows when the scope doesn't allow it: hidden, or disabled with its reason. */\nexport type NotAllowedMode = 'hide' | 'disable';\n\n/** What the commands settings are when the app registers none. */\nexport const COMMANDS_DEFAULTS: CommandsSettings = {\n commands: [],\n appState: undefined,\n disabledCategories: [],\n disabledCommands: [],\n notAllowed: 'hide',\n};\n\n/** What `commandsPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type CommandsConfig<AppState = any> = Omit<\n DeepPartial<CommandsSettings>,\n 'commands' | 'appState'\n> & {\n readonly commands?: readonly (CommandDefinition<AppState> | CommandFamily)[];\n readonly appState?: AppState;\n};\n\nexport interface RegisterCommandOptions {\n /** Replace a command with the same id; without it, a taken id throws `conflict`. */\n replace?: boolean;\n}\n\nexport interface ExecuteOptions extends OperationOptions {\n /** The document to run it for; the document in scope, else the active one, when left out. */\n documentId?: string;\n /** Passed to the command's `run` and derivations as `args`. */\n args?: unknown;\n}\n\n/** How `execute()` went: it ran, or it was refused before running, and why. */\nexport type ExecuteResult =\n | { readonly status: 'executed' }\n | { readonly status: 'rejected'; readonly reason: 'not-found' | 'disabled' | 'hidden' };\n\n// ── events ──\nexport interface CommandExecutedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly args: unknown;\n}\nexport interface CommandExecutionFailedEvent {\n readonly commandId: CommandId;\n readonly documentId: string | null;\n readonly error: PluginErrorInfo;\n}\n\n/**\n * The commands. A call that leaves out the document is for the document in scope when the\n * capability was resolved for one (`ctx.forDocument`, a `<DocumentScope>`), and for the active\n * document otherwise.\n */\nexport interface CommandsCapability extends SettingsApi<CommandsSettings> {\n // ── the commands ──\n /**\n * Add a command while the app runs, and get a function that removes it. A taken id throws\n * `conflict` unless `replace`.\n */\n registerCommand(definition: CommandDefinition, options?: RegisterCommandOptions): Unsubscribe;\n /** `registerCommand` for several definitions; the function removes all of them. */\n registerCommands(\n definitions: readonly CommandDefinition[],\n options?: RegisterCommandOptions,\n ): Unsubscribe;\n /** Whether a command has this id; with a family, every id that starts with its prefix does. */\n hasCommand(id: CommandId): boolean;\n /** A command as you defined it, or `null`. */\n getCommand(id: CommandId): CommandDefinition | null;\n /** Every command's id for the active document, in the order they were added. The same array until one changes. */\n listCommandIds(): readonly CommandId[];\n\n // ── what a button shows ──\n /** A command as a button shows it, or `null` for an unknown id. The same object while nothing about it changed. */\n resolveCommand(id: CommandId, documentId?: string): ResolvedCommand | null;\n /** Every command, resolved, in the order they were added. The same array while nothing changed. */\n listCommands(documentId?: string): readonly ResolvedCommand[];\n /** The visible commands whose label or id contains the query, for a command palette. */\n searchCommands(query: string, documentId?: string): readonly ResolvedCommand[];\n /** Every shortcut with its command, for a keyboard help sheet. The same array until the commands change. */\n listShortcuts(): readonly { readonly commandId: CommandId; readonly shortcut: string }[];\n\n // ── running them ──\n /**\n * Run a command; resolves once its `run` has, with `{ status: 'executed' }` and\n * `onExecuted`, or `{ status: 'rejected', reason }` for a command that is unknown, hidden or\n * disabled (a command turned off is hidden). A `run` that throws fires `onExecutionFailed` and rejects with its `PluginError`;\n * the signal rejects `operation-cancelled`.\n */\n execute(id: CommandId, options?: ExecuteOptions): Promise<ExecuteResult>;\n /** Whether a command can run now: it exists, and is enabled and visible. */\n canExecute(id: CommandId, documentId?: string): boolean;\n /**\n * Why a command won't run whatever the moment: it's turned off, or not allowed for its\n * document. `null` when it may run (or only can't right now), and for an unknown id.\n */\n getRefusal(id: CommandId, documentId?: string): CommandRefusal | null;\n\n // ── turning commands off ──\n /** The categories turned off. */\n getDisabledCategories(): readonly string[];\n /** Whether a category is turned off: it, or a category it's under (`annotations` for `annotations.highlight`). */\n isCategoryDisabled(category: string): boolean;\n /** Turn a category off, with every category under it: the `disabledCategories` setting gains it. */\n disableCategory(category: string): void;\n /** Turn a category on again. */\n enableCategory(category: string): void;\n /** Replace the categories that are off. */\n setDisabledCategories(categories: readonly string[]): void;\n /** The commands turned off one by one. */\n getDisabledCommands(): readonly CommandId[];\n /** Whether a command is turned off: by its id, or through one of its categories. */\n isCommandDisabled(id: CommandId): boolean;\n /** Turn one command off: the `disabledCommands` setting gains it. */\n disableCommand(id: CommandId): void;\n /** Turn a command on again; it stays off while one of its categories is. */\n enableCommand(id: CommandId): void;\n /** Replace the commands that are off one by one. */\n setDisabledCommands(ids: readonly CommandId[]): void;\n\n // ── events ──\n /** A command ran. */\n readonly onExecuted: EventHook<CommandExecutedEvent>;\n /** A command's `run` threw; `execute` rejects with the same error. */\n readonly onExecutionFailed: EventHook<CommandExecutionFailedEvent>;\n}\n"],"mappings":";;;;;AAMA,MAAa,iBAAA,GAAA,eAAA,sBAAA,CAA0D,YAAY,EACjF,MAAM,6EACR,CAAC;;;;;;;AC2MD,MAAa,yBACX,MACA,UACY;CACZ,IAAI,SAAS,OAAO,OAAO;CAC3B,IAAI,CAAC,QAAQ,CAAC,OAAO,OAAO;CAC5B,OACE,KAAK,OAAO,MAAM,MAClB,KAAK,UAAU,MAAM,SACrB,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,YAAY,MAAM,YAAY,WAC/C,KAAK,YAAY,cAAc,MAAM,YAAY,aACjD,KAAK,SAAS,MAAM,QACpB,KAAK,YAAY,MAAM,WACvB,KAAK,WAAW,MAAM,UACtB,KAAK,cAAc,MAAM,aACzB,KAAK,YAAY,MAAM,WACvB,KAAK,mBAAmB,MAAM,kBAC9B,KAAK,UAAU,WAAW,MAAM,UAAU,UAC1C,KAAK,UAAU,OAAO,UAAU,UAAU,aAAa,MAAM,UAAU,MAAM;AAEjF;;;;;AAMA,MAAa,uBAAuB,QAAoC;CACtE;CACA,OAAO;CACP,WAAW,CAAC;CACZ,SAAS;CACT,QAAQ;CACR,WAAW;CACX,SAAS;CACT,YAAY,CAAC;AACf;;AAGA,MAAa,yBAAyB,IAAe,UACnD,eAAe,GAAG,IAAA,GAAA,kBAAA,WAAA,CAAc,IAAI,KAAK,EAAE;;;;;;AAe7C,SAAgB,eACd,SACA,SACA,SACc;CACd,MAAM,CAAC,SAAS,QAAQ;CACxB,OAAO;EACL,GAAG;EACH,WAAW,QAAQ,QAAQ,EAAE;EAC7B,eAAe,UAAU,KAAA,IAAY,QAAA,GAAA,kBAAA,eAAA,CAAsB,OAAO,EAAE,OAAO,QAAQ,MAAM,CAAC;CAC5F;AACF;;AAgCA,MAAa,oBAAsC;CACjD,UAAU,CAAC;CACX,UAAU,KAAA;CACV,oBAAoB,CAAC;CACrB,kBAAkB,CAAC;CACnB,YAAY;AACd"}
|
package/dist/index.cjs
CHANGED
|
@@ -33,6 +33,8 @@ function configuredCommands(items) {
|
|
|
33
33
|
* dotted segments, so `annotations` covers `annotations.highlight` and not `annotationsExtra`.
|
|
34
34
|
*/
|
|
35
35
|
const isCategoryOff = (category, disabled) => disabled.some((off) => category === off || category.startsWith(`${off}.`));
|
|
36
|
+
/** The translate function for a command's document: a new one only when its strings may differ. */
|
|
37
|
+
const translateOf = (context) => context.tryGet(_embedpdf_plugin_i18n_contract.I18nToken)?.getTranslator() ?? null;
|
|
36
38
|
/** The values for a label's slots, from `labelParams`; none without it, or when it throws. */
|
|
37
39
|
const labelParamsOf = (definition, context) => {
|
|
38
40
|
if (!definition.labelParams) return void 0;
|
|
@@ -48,15 +50,13 @@ const labelParamsOf = (definition, context) => {
|
|
|
48
50
|
* So a string for `'document:download'` relabels that one command, whichever key its label is
|
|
49
51
|
* under.
|
|
50
52
|
*/
|
|
51
|
-
const labelOf = (definition,
|
|
52
|
-
|
|
53
|
-
const i18n = context.tryGet(_embedpdf_plugin_i18n_contract.I18nToken);
|
|
54
|
-
if (!i18n) return (0, _embedpdf_plugin_i18n_contract.interpolate)(definition.label ?? definition.labelKey ?? definition.id, params);
|
|
53
|
+
const labelOf = (definition, params, t) => {
|
|
54
|
+
if (!t) return (0, _embedpdf_plugin_i18n_contract.interpolate)(definition.label ?? definition.labelKey ?? definition.id, params);
|
|
55
55
|
const options = {
|
|
56
56
|
...definition.labelKey ? { fallbackKey: definition.labelKey } : {},
|
|
57
57
|
...params ? { params } : {}
|
|
58
58
|
};
|
|
59
|
-
return definition.label === void 0 && definition.labelKey ?
|
|
59
|
+
return definition.label === void 0 && definition.labelKey ? t(definition.id, options) : t(definition.id, {
|
|
60
60
|
...options,
|
|
61
61
|
fallback: definition.label ?? definition.id
|
|
62
62
|
});
|
|
@@ -72,14 +72,13 @@ const permissionKeyOf = (permission) => `commands.notAllowed.${permission.replac
|
|
|
72
72
|
/** The general sentence's key: `{label} isn't allowed`. */
|
|
73
73
|
const DEFAULT_NOT_ALLOWED_KEY = "commands.notAllowed.default";
|
|
74
74
|
/** The sentence for a command the session may not run, under `key`, else the general one. */
|
|
75
|
-
const notAllowedMessage = (key, label,
|
|
75
|
+
const notAllowedMessage = (key, label, t) => {
|
|
76
76
|
const fallback = `${label} isn't allowed`;
|
|
77
|
-
|
|
78
|
-
if (!i18n) return fallback;
|
|
77
|
+
if (!t) return fallback;
|
|
79
78
|
const params = { label };
|
|
80
|
-
return
|
|
79
|
+
return t(key, {
|
|
81
80
|
params,
|
|
82
|
-
fallback:
|
|
81
|
+
fallback: t(DEFAULT_NOT_ALLOWED_KEY, {
|
|
83
82
|
params,
|
|
84
83
|
fallback
|
|
85
84
|
})
|
|
@@ -87,29 +86,24 @@ const notAllowedMessage = (key, label, context) => {
|
|
|
87
86
|
};
|
|
88
87
|
/** The general locked sentence's key: `{label} can't be changed in this document`. */
|
|
89
88
|
const DEFAULT_LOCKED_KEY = "commands.locked.default";
|
|
90
|
-
/** The sentence for a command whose setting a lock holds
|
|
91
|
-
const lockedMessage = (
|
|
89
|
+
/** The sentence for a command whose setting a lock holds, under `key`, else the general one. */
|
|
90
|
+
const lockedMessage = (key, label, t) => {
|
|
92
91
|
const fallback = `${label} can't be changed in this document`;
|
|
93
|
-
|
|
94
|
-
if (!i18n) return fallback;
|
|
92
|
+
if (!t) return fallback;
|
|
95
93
|
const params = { label };
|
|
96
|
-
|
|
94
|
+
return t(key, {
|
|
97
95
|
params,
|
|
98
|
-
fallback
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
fallback: general
|
|
96
|
+
fallback: t(DEFAULT_LOCKED_KEY, {
|
|
97
|
+
params,
|
|
98
|
+
fallback
|
|
99
|
+
})
|
|
103
100
|
});
|
|
104
101
|
};
|
|
105
102
|
/** The sentence for a command that's turned off. */
|
|
106
|
-
const turnedOffMessage = (label,
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
fallback: "{label} isn't available"
|
|
111
|
-
}) : `${label} isn't available`;
|
|
112
|
-
};
|
|
103
|
+
const turnedOffMessage = (label, t) => t ? t("commands.turnedOff", {
|
|
104
|
+
params: { label },
|
|
105
|
+
fallback: "{label} isn't available"
|
|
106
|
+
}) : `${label} isn't available`;
|
|
113
107
|
function createAvailability(ctx, settings) {
|
|
114
108
|
/** Whether a command is turned off: by its id, or through one of its categories. */
|
|
115
109
|
const isTurnedOff = (definition) => {
|
|
@@ -125,14 +119,20 @@ function createAvailability(ctx, settings) {
|
|
|
125
119
|
return true;
|
|
126
120
|
}
|
|
127
121
|
};
|
|
128
|
-
/**
|
|
129
|
-
|
|
122
|
+
/**
|
|
123
|
+
* Why a lock holds the setting a command changes, as the key of the sentence that says so (the
|
|
124
|
+
* lock's `reasonKey`, else `commands.locked.default`), or `null` while nothing holds it; a
|
|
125
|
+
* `locked` that throws is no lock.
|
|
126
|
+
*/
|
|
127
|
+
const lockedKeyOf = (definition, context) => {
|
|
130
128
|
if (!definition.locked) return null;
|
|
129
|
+
let lock;
|
|
131
130
|
try {
|
|
132
|
-
|
|
131
|
+
lock = definition.locked(context);
|
|
133
132
|
} catch {
|
|
134
133
|
return null;
|
|
135
134
|
}
|
|
135
|
+
return lock === null ? null : lock.reasonKey ?? DEFAULT_LOCKED_KEY;
|
|
136
136
|
};
|
|
137
137
|
/**
|
|
138
138
|
* Why its document's session may not run a command, as the key of the sentence that says
|
|
@@ -150,25 +150,27 @@ function createAvailability(ctx, settings) {
|
|
|
150
150
|
};
|
|
151
151
|
/** Why a command won't run whatever the moment, or `null` when it may run. */
|
|
152
152
|
const refusalOf = (definition, context) => {
|
|
153
|
+
const t = translateOf(context);
|
|
154
|
+
const label = () => labelOf(definition, labelParamsOf(definition, context), t);
|
|
153
155
|
if (isTurnedOff(definition)) return {
|
|
154
156
|
reason: "turned-off",
|
|
155
|
-
message: turnedOffMessage(
|
|
157
|
+
message: turnedOffMessage(label(), t)
|
|
156
158
|
};
|
|
157
159
|
const notAllowed = notAllowedKeyOf(definition, context);
|
|
158
160
|
if (notAllowed !== null) return {
|
|
159
161
|
reason: "not-allowed",
|
|
160
|
-
message: notAllowedMessage(notAllowed,
|
|
162
|
+
message: notAllowedMessage(notAllowed, label(), t)
|
|
161
163
|
};
|
|
162
|
-
const
|
|
163
|
-
return
|
|
164
|
+
const locked = lockedKeyOf(definition, context);
|
|
165
|
+
return locked === null ? null : {
|
|
164
166
|
reason: "locked",
|
|
165
|
-
message: lockedMessage(
|
|
167
|
+
message: lockedMessage(locked, label(), t)
|
|
166
168
|
};
|
|
167
169
|
};
|
|
168
170
|
return {
|
|
169
171
|
isTurnedOff,
|
|
170
172
|
notAllowedKeyOf,
|
|
171
|
-
|
|
173
|
+
lockedKeyOf,
|
|
172
174
|
refusalOf
|
|
173
175
|
};
|
|
174
176
|
}
|
|
@@ -206,10 +208,10 @@ function createTurningOff(settings, definitionOf, isTurnedOff) {
|
|
|
206
208
|
/**
|
|
207
209
|
* The commands controller: the commands (from the settings, added while the
|
|
208
210
|
* app runs, and from families), resolution for a document (derivations over
|
|
209
|
-
* live state, safe to throw), the one way to run
|
|
210
|
-
* off (by category and one by one), what the
|
|
211
|
-
* `requires`, the plugins' checks in `allowed`),
|
|
212
|
-
* matcher.
|
|
211
|
+
* live state, safe to throw, asked once per store change), the one way to run
|
|
212
|
+
* a command, turning commands off (by category and one by one), what the
|
|
213
|
+
* session may run (the scope's `requires`, the plugins' checks in `allowed`),
|
|
214
|
+
* and the host-only keystroke matcher.
|
|
213
215
|
*
|
|
214
216
|
* Definitions hold functions, so the commands added while the app runs are a
|
|
215
217
|
* map outside state; every change to it calls `ctx.notify()` so readers read
|
|
@@ -223,21 +225,21 @@ const panelTarget = (definition) => definition.panel === void 0 ? null : typeof
|
|
|
223
225
|
const pressableOf = (definition) => !definition.menu && (definition.active !== void 0 || definition.panel !== void 0);
|
|
224
226
|
const NOT_REGISTERED = [
|
|
225
227
|
null,
|
|
226
|
-
|
|
228
|
+
null,
|
|
229
|
+
void 0,
|
|
227
230
|
void 0,
|
|
228
231
|
void 0,
|
|
229
232
|
false,
|
|
230
233
|
false,
|
|
231
234
|
false,
|
|
232
|
-
|
|
235
|
+
null,
|
|
236
|
+
null
|
|
233
237
|
];
|
|
234
238
|
const NO_NAMES = [];
|
|
235
239
|
const accentOf = (primary, secondary) => primary === void 0 && secondary === void 0 ? void 0 : {
|
|
236
240
|
...primary !== void 0 ? { primary } : {},
|
|
237
241
|
...secondary !== void 0 ? { secondary } : {}
|
|
238
242
|
};
|
|
239
|
-
/** The memo key of a resolution: the command id and the document named, if any. */
|
|
240
|
-
const resolutionKey = (id, documentId) => JSON.stringify([id, documentId ?? null]);
|
|
241
243
|
function createCommandsController(ctx) {
|
|
242
244
|
const settings = ctx.settings();
|
|
243
245
|
/** Commands added while the app runs, in the order they were added. */
|
|
@@ -271,6 +273,24 @@ function createCommandsController(ctx) {
|
|
|
271
273
|
}
|
|
272
274
|
};
|
|
273
275
|
};
|
|
276
|
+
/**
|
|
277
|
+
* The context a document's derivations read (`''` is the active document): the same object
|
|
278
|
+
* until the store changes. It keeps the capabilities it finds, which stay the same objects
|
|
279
|
+
* until then.
|
|
280
|
+
*/
|
|
281
|
+
const contextByDocument = (0, _embedpdf_core.memoByKey)((_documentKey) => [ctx.storeChangeCount()], (documentKey) => {
|
|
282
|
+
const context = commandContext(documentKey || void 0);
|
|
283
|
+
const found = /* @__PURE__ */ new Map();
|
|
284
|
+
const tryGet = (token) => {
|
|
285
|
+
if (!found.has(token)) found.set(token, context.tryGet(token));
|
|
286
|
+
return found.get(token);
|
|
287
|
+
};
|
|
288
|
+
return {
|
|
289
|
+
...context,
|
|
290
|
+
tryGet,
|
|
291
|
+
get: (token) => tryGet(token) ?? context.get(token)
|
|
292
|
+
};
|
|
293
|
+
});
|
|
274
294
|
/** A family's command for one name, made once so it keeps its identity. */
|
|
275
295
|
const familyCommands = /* @__PURE__ */ new WeakMap();
|
|
276
296
|
const familyCommand = (family, name) => {
|
|
@@ -326,62 +346,94 @@ function createCommandsController(ctx) {
|
|
|
326
346
|
return NO_NAMES;
|
|
327
347
|
}
|
|
328
348
|
};
|
|
329
|
-
const { isTurnedOff, notAllowedKeyOf,
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
const
|
|
349
|
+
const { isTurnedOff, notAllowedKeyOf, lockedKeyOf, refusalOf } = createAvailability(ctx, settings);
|
|
350
|
+
/** Whether a command shows as pressed: its `active`, else while what it opens is open. */
|
|
351
|
+
const activeOf = (definition, context) => {
|
|
352
|
+
if (definition.active) return derive(definition.active, context, false);
|
|
353
|
+
const shell = context.tryGet(_embedpdf_plugin_shell_contract.ShellToken);
|
|
354
|
+
if (!shell) return false;
|
|
355
|
+
const panel = panelTarget(definition);
|
|
356
|
+
return definition.menu ? shell.isMenuOpen(definition.menu) : panel ? shell.isOpen(panel.id) : definition.modal ? shell.isOpen(definition.modal) : false;
|
|
357
|
+
};
|
|
358
|
+
/**
|
|
359
|
+
* Whether a command can run and whether it shows, as its derivations answer now, with the keys
|
|
360
|
+
* of the sentences that say why it's disabled. Turned off hides it; not allowed hides it, or
|
|
361
|
+
* disables it with the reason; a lock on the setting it changes disables it with the lock's
|
|
362
|
+
* reason, whatever `notAllowed` says.
|
|
363
|
+
*/
|
|
364
|
+
const availabilityOf = (definition, context) => {
|
|
334
365
|
const turnedOff = isTurnedOff(definition);
|
|
335
366
|
const notAllowed = turnedOff ? null : notAllowedKeyOf(definition, context);
|
|
336
367
|
const shownWhenNotAllowed = settings.get().notAllowed === "disable";
|
|
337
|
-
const
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
368
|
+
const lockedKey = turnedOff || notAllowed !== null ? null : lockedKeyOf(definition, context);
|
|
369
|
+
return {
|
|
370
|
+
enabled: !(turnedOff || notAllowed !== null || lockedKey !== null) && derive(definition.enabled, context, true),
|
|
371
|
+
visible: !turnedOff && (notAllowed === null || shownWhenNotAllowed) && derive(definition.visible, context, true),
|
|
372
|
+
notAllowedKey: shownWhenNotAllowed ? notAllowed : null,
|
|
373
|
+
lockedKey
|
|
374
|
+
};
|
|
375
|
+
};
|
|
376
|
+
/** What a command's derivations answer for a document now. */
|
|
377
|
+
const answersOf = (entry, context) => {
|
|
378
|
+
const { definition } = entry;
|
|
379
|
+
const { enabled, visible, notAllowedKey, lockedKey } = availabilityOf(definition, context);
|
|
380
|
+
const labelParams = labelParamsOf(definition, context);
|
|
346
381
|
const accent = deriveAccent(definition.iconAccent, context);
|
|
347
382
|
return [
|
|
348
383
|
entry,
|
|
349
|
-
|
|
384
|
+
translateOf(context),
|
|
385
|
+
labelParams === void 0 ? void 0 : JSON.stringify(labelParams),
|
|
350
386
|
accent?.primary,
|
|
351
387
|
accent?.secondary,
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
388
|
+
enabled,
|
|
389
|
+
activeOf(definition, context),
|
|
390
|
+
visible,
|
|
391
|
+
notAllowedKey,
|
|
392
|
+
lockedKey
|
|
356
393
|
];
|
|
357
394
|
};
|
|
358
|
-
/**
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
395
|
+
/**
|
|
396
|
+
* One document's commands as buttons show them, by id (`''` is the active document). A
|
|
397
|
+
* command's derivations are asked at most once per store change, however many readers ask for
|
|
398
|
+
* it; its resolved object is built again, label and sentences translated, only when one of their
|
|
399
|
+
* answers changed.
|
|
400
|
+
*/
|
|
401
|
+
const documentResolution = (documentKey) => {
|
|
402
|
+
const answersById = (0, _embedpdf_core.memoByKey)((_id) => [ctx.storeChangeCount()], (id) => {
|
|
403
|
+
const entry = entryOf(id);
|
|
404
|
+
return entry ? answersOf(entry, contextByDocument(documentKey)) : NOT_REGISTERED;
|
|
405
|
+
});
|
|
406
|
+
return (0, _embedpdf_core.memoByKey)((id) => answersById(id), (_id, entry, translate, labelParams, accentPrimary, accentSecondary, enabled, active, visible, notAllowedKey, lockedKey) => {
|
|
407
|
+
if (!entry) return null;
|
|
408
|
+
const params = labelParams === void 0 ? void 0 : JSON.parse(labelParams);
|
|
409
|
+
const label = labelOf(entry.definition, params, translate);
|
|
410
|
+
const disabledReason = notAllowedKey !== null ? notAllowedMessage(notAllowedKey, label, translate) : lockedKey !== null ? lockedMessage(lockedKey, label, translate) : void 0;
|
|
411
|
+
return {
|
|
412
|
+
id: entry.definition.id,
|
|
413
|
+
label,
|
|
414
|
+
icon: entry.definition.icon,
|
|
415
|
+
iconAccent: accentOf(accentPrimary, accentSecondary),
|
|
416
|
+
shortcuts: entry.shortcuts,
|
|
417
|
+
menu: entry.definition.menu,
|
|
418
|
+
enabled,
|
|
419
|
+
active,
|
|
420
|
+
pressable: pressableOf(entry.definition),
|
|
421
|
+
visible,
|
|
422
|
+
categories: entry.definition.categories ?? [],
|
|
423
|
+
...disabledReason === void 0 ? {} : { disabledReason }
|
|
424
|
+
};
|
|
425
|
+
});
|
|
426
|
+
};
|
|
427
|
+
/** Each document's resolution, made the first time the document is asked about. */
|
|
428
|
+
const resolutionByDocument = (0, _embedpdf_core.memoByKey)((_documentKey) => [], documentResolution);
|
|
429
|
+
const resolveCommand = (id, documentId) => resolutionByDocument(documentId ?? "")(id);
|
|
378
430
|
/**
|
|
379
431
|
* Every command's id for a document (`''` is the active one): the defined ones in the order
|
|
380
432
|
* they were added, then each family's names that no defined command took.
|
|
381
433
|
*/
|
|
382
434
|
const idsByDocument = (0, _embedpdf_core.memoByKey)((documentKey) => {
|
|
383
435
|
const config = configured();
|
|
384
|
-
const context =
|
|
436
|
+
const context = contextByDocument(documentKey);
|
|
385
437
|
return [
|
|
386
438
|
definedCommands(),
|
|
387
439
|
config,
|
|
@@ -431,12 +483,12 @@ function createCommandsController(ctx) {
|
|
|
431
483
|
status: "rejected",
|
|
432
484
|
reason: "not-found"
|
|
433
485
|
};
|
|
434
|
-
const
|
|
435
|
-
if (!
|
|
486
|
+
const now = availabilityOf(entry.definition, contextByDocument(documentId ?? ""));
|
|
487
|
+
if (!now.visible) return {
|
|
436
488
|
status: "rejected",
|
|
437
489
|
reason: "hidden"
|
|
438
490
|
};
|
|
439
|
-
if (!
|
|
491
|
+
if (!now.enabled) return {
|
|
440
492
|
status: "rejected",
|
|
441
493
|
reason: "disabled"
|
|
442
494
|
};
|
|
@@ -496,12 +548,14 @@ function createCommandsController(ctx) {
|
|
|
496
548
|
listShortcuts,
|
|
497
549
|
execute,
|
|
498
550
|
canExecute: (id, documentId) => {
|
|
499
|
-
const
|
|
500
|
-
|
|
551
|
+
const entry = entryOf(id);
|
|
552
|
+
if (!entry) return false;
|
|
553
|
+
const now = availabilityOf(entry.definition, contextByDocument(documentId ?? ""));
|
|
554
|
+
return now.enabled && now.visible;
|
|
501
555
|
},
|
|
502
556
|
getRefusal: (id, documentId) => {
|
|
503
557
|
const entry = entryOf(id);
|
|
504
|
-
return entry ? refusalOf(entry.definition,
|
|
558
|
+
return entry ? refusalOf(entry.definition, contextByDocument(documentId ?? "")) : null;
|
|
505
559
|
},
|
|
506
560
|
...turningOff,
|
|
507
561
|
onExecuted: executed.on,
|
|
@@ -512,7 +566,7 @@ function createCommandsController(ctx) {
|
|
|
512
566
|
for (const entry of definedCommands()) {
|
|
513
567
|
if (options.inTextField && !entry.definition.shortcutInTextFields) continue;
|
|
514
568
|
if (!entry.parsed.some((shortcut) => (0, _embedpdf_core_ui.matchShortcut)(shortcut, stroke, options))) continue;
|
|
515
|
-
const context =
|
|
569
|
+
const context = contextByDocument("");
|
|
516
570
|
const refusal = refusalOf(entry.definition, context);
|
|
517
571
|
const visible = derive(entry.definition.visible, context, true);
|
|
518
572
|
if (!refusal) {
|