@embedpdf/plugin-commands 3.0.0-next.2 → 3.0.0-next.21

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/index.cjs CHANGED
@@ -1,29 +1,247 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_contract = require("./contract-sqmSSPlP.cjs");
3
+ const require_contract_host = require("./contract/host.cjs");
2
4
  let _embedpdf_core = require("@embedpdf/core");
3
- let _embedpdf_plugin_i18n = require("@embedpdf/plugin-i18n");
4
- let _embedpdf_plugin_shell = require("@embedpdf/plugin-shell");
5
+ let _embedpdf_plugin_i18n_contract = require("@embedpdf/plugin-i18n/contract");
6
+ let _embedpdf_plugin_shell_contract = require("@embedpdf/plugin-shell/contract");
5
7
  let _embedpdf_core_ui = require("@embedpdf/core-ui");
6
- //#region src/capability.ts
7
- function registerCommand(registry, def) {
8
- if (registry.has(def.id)) throw new Error(`[commands] duplicate command: ${def.id}`);
9
- const shortcuts = def.shortcut === void 0 ? [] : [].concat(def.shortcut);
10
- registry.set(def.id, {
11
- def,
8
+ //#region src/registry.ts
9
+ /** A command definition with its shortcuts parsed once, and how the registry tells a family apart. */
10
+ const registeredCommand = (definition) => {
11
+ const shortcuts = definition.shortcut === void 0 ? [] : [].concat(definition.shortcut);
12
+ return {
13
+ definition,
12
14
  shortcuts,
13
15
  parsed: shortcuts.map(_embedpdf_core_ui.parseShortcut)
16
+ };
17
+ };
18
+ const isCommandFamily = (item) => "prefix" in item;
19
+ function configuredCommands(items) {
20
+ const commands = /* @__PURE__ */ new Map();
21
+ const families = [];
22
+ for (const item of items) if (isCommandFamily(item)) families.push(item);
23
+ else commands.set(item.id, registeredCommand(item));
24
+ return {
25
+ commands,
26
+ families
27
+ };
28
+ }
29
+ //#endregion
30
+ //#region src/services/availability.ts
31
+ /**
32
+ * Whether a category is off: it, or a category it's under, is in the list. Parts are whole
33
+ * dotted segments, so `annotations` covers `annotations.highlight` and not `annotationsExtra`.
34
+ */
35
+ const isCategoryOff = (category, disabled) => disabled.some((off) => category === off || category.startsWith(`${off}.`));
36
+ /**
37
+ * The label: a language's string under the command's id, else under its `labelKey` (the current
38
+ * language, then the fallback one), else `label`, else the id. So a string for
39
+ * `'document:download'` relabels that one command, whichever key its label is under.
40
+ */
41
+ const labelOf = (definition, context) => {
42
+ const i18n = context.tryGet(_embedpdf_plugin_i18n_contract.I18nToken);
43
+ if (!i18n) return definition.label ?? definition.labelKey ?? definition.id;
44
+ const fallbackKey = definition.labelKey ? { fallbackKey: definition.labelKey } : {};
45
+ return definition.label === void 0 && definition.labelKey ? i18n.t(definition.id, fallbackKey) : i18n.t(definition.id, {
46
+ ...fallbackKey,
47
+ fallback: definition.label ?? definition.id
14
48
  });
49
+ };
50
+ /**
51
+ * Whether a document's session holds a permission: what `ctx.allows` answers for a
52
+ * document-scoped plugin, asked here of the command's document, since the commands are one
53
+ * set for the whole workspace.
54
+ */
55
+ const sessionHolds = (security, permission) => permission === "annotations:create" ? security.allowsAnnotation("create") : security.allows(permission);
56
+ /** Where a language keeps the sentence for a permission: `commands.notAllowed.doc-text-copy`. */
57
+ const permissionKeyOf = (permission) => `commands.notAllowed.${permission.replace(/[.:]/g, "-")}`;
58
+ /** The general sentence's key: `{label} isn't allowed`. */
59
+ const DEFAULT_NOT_ALLOWED_KEY = "commands.notAllowed.default";
60
+ /** The sentence for a command the session may not run, under `key`, else the general one. */
61
+ const notAllowedMessage = (key, label, context) => {
62
+ const fallback = `${label} isn't allowed`;
63
+ const i18n = context.tryGet(_embedpdf_plugin_i18n_contract.I18nToken);
64
+ if (!i18n) return fallback;
65
+ const params = { label };
66
+ return i18n.t(key, {
67
+ params,
68
+ fallback: i18n.t(DEFAULT_NOT_ALLOWED_KEY, {
69
+ params,
70
+ fallback
71
+ })
72
+ });
73
+ };
74
+ /** The general locked sentence's key: `{label} can't be changed in this document`. */
75
+ const DEFAULT_LOCKED_KEY = "commands.locked.default";
76
+ /** The sentence for a command whose setting a lock holds: its `reasonKey`, else the general one. */
77
+ const lockedMessage = (lock, label, context) => {
78
+ const fallback = `${label} can't be changed in this document`;
79
+ const i18n = context.tryGet(_embedpdf_plugin_i18n_contract.I18nToken);
80
+ if (!i18n) return fallback;
81
+ const params = { label };
82
+ const general = i18n.t(DEFAULT_LOCKED_KEY, {
83
+ params,
84
+ fallback
85
+ });
86
+ return lock.reasonKey === void 0 ? general : i18n.t(lock.reasonKey, {
87
+ params,
88
+ fallback: general
89
+ });
90
+ };
91
+ /** The sentence for a command that's turned off. */
92
+ const turnedOffMessage = (label, context) => {
93
+ const i18n = context.tryGet(_embedpdf_plugin_i18n_contract.I18nToken);
94
+ return i18n ? i18n.t("commands.turnedOff", {
95
+ params: { label },
96
+ fallback: "{label} isn't available"
97
+ }) : `${label} isn't available`;
98
+ };
99
+ function createAvailability(ctx, settings) {
100
+ /** Whether a command is turned off: by its id, or through one of its categories. */
101
+ const isTurnedOff = (definition) => {
102
+ const { disabledCategories, disabledCommands } = settings.get();
103
+ return disabledCommands.includes(definition.id) || (definition.categories ?? []).some((category) => isCategoryOff(category, disabledCategories));
104
+ };
105
+ /** Whether a command's `allowed` check says yes; one that throws allows it. */
106
+ const passesCheck = (definition, context) => {
107
+ if (!definition.allowed) return true;
108
+ try {
109
+ return definition.allowed(context);
110
+ } catch {
111
+ return true;
112
+ }
113
+ };
114
+ /** The lock on the setting a command changes, or `null`; a `locked` that throws is no lock. */
115
+ const lockOf = (definition, context) => {
116
+ if (!definition.locked) return null;
117
+ try {
118
+ return definition.locked(context);
119
+ } catch {
120
+ return null;
121
+ }
122
+ };
123
+ /**
124
+ * Why its document's session may not run a command, as the key of the sentence that says
125
+ * so, or `null` when it may: the first permission `requires` names that the session doesn't
126
+ * hold (`commands.notAllowed.doc-print`), else its `allowed` check saying no (its
127
+ * `notAllowedKey`). With no document open there is no session to ask, and nothing is refused.
128
+ */
129
+ const notAllowedKeyOf = (definition, context) => {
130
+ if (!definition.requires?.length && !definition.allowed) return null;
131
+ const handle = context.documentId === null ? null : ctx.documentHandle(context.documentId);
132
+ if (!handle) return null;
133
+ const missing = definition.requires?.find((permission) => !sessionHolds(handle.security, permission));
134
+ if (missing !== void 0) return permissionKeyOf(missing);
135
+ return passesCheck(definition, context) ? null : definition.notAllowedKey ?? DEFAULT_NOT_ALLOWED_KEY;
136
+ };
137
+ /** Why a command won't run whatever the moment, or `null` when it may run. */
138
+ const refusalOf = (definition, context) => {
139
+ if (isTurnedOff(definition)) return {
140
+ reason: "turned-off",
141
+ message: turnedOffMessage(labelOf(definition, context), context)
142
+ };
143
+ const notAllowed = notAllowedKeyOf(definition, context);
144
+ if (notAllowed !== null) return {
145
+ reason: "not-allowed",
146
+ message: notAllowedMessage(notAllowed, labelOf(definition, context), context)
147
+ };
148
+ const lock = lockOf(definition, context);
149
+ return lock === null ? null : {
150
+ reason: "locked",
151
+ message: lockedMessage(lock, labelOf(definition, context), context)
152
+ };
153
+ };
154
+ return {
155
+ isTurnedOff,
156
+ notAllowedKeyOf,
157
+ lockOf,
158
+ refusalOf
159
+ };
15
160
  }
16
- const panelTarget = (def) => def.panel === void 0 ? null : typeof def.panel === "string" ? { id: def.panel } : def.panel;
17
- function createCommandsCapability(ctx, registry) {
18
- /** Bind capability resolution to the command's target document. The kernel
19
- * resolves workspace tokens regardless of the document argument, so one
20
- * code path serves both scopes. */
21
- const commandCtx = (documentId) => {
22
- const target = documentId ?? ctx.core().activeId;
161
+ //#endregion
162
+ //#region src/write/turning-off.ts
163
+ function createTurningOff(settings, definitionOf, isTurnedOff) {
164
+ const listOf = (list) => settings.get()[list];
165
+ const replace = (list, names) => settings.api.updateSettings(list === "disabledCategories" ? { disabledCategories: [...names] } : { disabledCommands: [...names] });
166
+ const add = (list, name) => {
167
+ const current = listOf(list);
168
+ if (!current.includes(name)) replace(list, [...current, name]);
169
+ };
170
+ const remove = (list, name) => {
171
+ const current = listOf(list);
172
+ if (current.includes(name)) replace(list, current.filter((other) => other !== name));
173
+ };
174
+ return {
175
+ getDisabledCategories: () => listOf("disabledCategories"),
176
+ isCategoryDisabled: (category) => isCategoryOff(category, listOf("disabledCategories")),
177
+ disableCategory: (category) => add("disabledCategories", category),
178
+ enableCategory: (category) => remove("disabledCategories", category),
179
+ setDisabledCategories: (categories) => replace("disabledCategories", categories),
180
+ getDisabledCommands: () => listOf("disabledCommands"),
181
+ isCommandDisabled: (id) => {
182
+ const definition = definitionOf(id);
183
+ return definition ? isTurnedOff(definition) : listOf("disabledCommands").includes(id);
184
+ },
185
+ disableCommand: (id) => add("disabledCommands", id),
186
+ enableCommand: (id) => remove("disabledCommands", id),
187
+ setDisabledCommands: (ids) => replace("disabledCommands", ids)
188
+ };
189
+ }
190
+ //#endregion
191
+ //#region src/controller.ts
192
+ /**
193
+ * The commands controller: the commands (from the settings, added while the
194
+ * app runs, and from families), resolution for a document (derivations over
195
+ * live state, safe to throw), the one way to run a command, turning commands
196
+ * off (by category and one by one), what the session may run (the scope's
197
+ * `requires`, the plugins' checks in `allowed`), and the host-only keystroke
198
+ * matcher.
199
+ *
200
+ * Definitions hold functions, so the commands added while the app runs are a
201
+ * map outside state; every change to it calls `ctx.notify()` so readers read
202
+ * again.
203
+ */
204
+ const panelTarget = (definition) => definition.panel === void 0 ? null : typeof definition.panel === "string" ? { id: definition.panel } : definition.panel;
205
+ const NOT_REGISTERED = [
206
+ null,
207
+ "",
208
+ void 0,
209
+ void 0,
210
+ false,
211
+ false,
212
+ false,
213
+ void 0
214
+ ];
215
+ const NO_NAMES = [];
216
+ const accentOf = (primary, secondary) => primary === void 0 && secondary === void 0 ? void 0 : {
217
+ ...primary !== void 0 ? { primary } : {},
218
+ ...secondary !== void 0 ? { secondary } : {}
219
+ };
220
+ /** The memo key of a resolution: the command id and the document named, if any. */
221
+ const resolutionKey = (id, documentId) => JSON.stringify([id, documentId ?? null]);
222
+ function createCommandsController(ctx) {
223
+ const settings = ctx.settings();
224
+ /** Commands added while the app runs, in the order they were added. */
225
+ const registered = /* @__PURE__ */ new Map();
226
+ /** Bumped on every change to `registered`: the input of the reads built from it. */
227
+ let registeredVersion = 0;
228
+ const registeredChanged = () => {
229
+ registeredVersion += 1;
230
+ ctx.notify();
231
+ };
232
+ /** The commands the settings define, rebuilt when the setting changes. */
233
+ const configured = (0, _embedpdf_core.memo)(() => [settings.get().commands], (items) => configuredCommands(items));
234
+ const executed = ctx.events.source();
235
+ const executionFailed = ctx.events.source();
236
+ /** Capabilities for the command's document: the one named, else the active one. */
237
+ const commandContext = (documentId, call = {}) => {
238
+ const target = documentId ?? ctx.get(_embedpdf_core.DocumentsToken).getActiveId();
23
239
  const get = (token) => target ? ctx.forDocument(token, target) : ctx.get(token);
24
240
  return {
25
241
  documentId: target,
26
- core: ctx.core,
242
+ appState: settings.get().appState,
243
+ ...call.args === void 0 ? {} : { args: call.args },
244
+ ...call.signal ? { signal: call.signal } : {},
27
245
  get,
28
246
  tryGet: (token) => {
29
247
  try {
@@ -34,163 +252,306 @@ function createCommandsCapability(ctx, registry) {
34
252
  }
35
253
  };
36
254
  };
37
- /** Derivations run against live state; a derivation that throws (e.g. it
38
- * needs a document and none is open) falls back to the safe default —
39
- * the button renders, disabled, exactly like v2's empty state. */
40
- const derive = (fn, c, fallback) => {
41
- if (!fn) return fallback;
255
+ /** A family's command for one name, made once so it keeps its identity. */
256
+ const familyCommands = /* @__PURE__ */ new WeakMap();
257
+ const familyCommand = (family, name) => {
258
+ let byName = familyCommands.get(family);
259
+ if (!byName) {
260
+ byName = /* @__PURE__ */ new Map();
261
+ familyCommands.set(family, byName);
262
+ }
263
+ let entry = byName.get(name);
264
+ if (!entry) {
265
+ entry = registeredCommand({
266
+ ...family.command(name),
267
+ id: `${family.prefix}${name}`
268
+ });
269
+ byName.set(name, entry);
270
+ }
271
+ return entry;
272
+ };
273
+ /** The command with this id: one added while the app runs, else the settings', else a family's. */
274
+ const entryOf = (id) => {
275
+ const { commands, families } = configured();
276
+ const entry = registered.get(id) ?? commands.get(id);
277
+ if (entry) return entry;
278
+ const family = families.find((candidate) => id.startsWith(candidate.prefix) && id.length > candidate.prefix.length);
279
+ return family ? familyCommand(family, id.slice(family.prefix.length)) : null;
280
+ };
281
+ /** Every command with its own definition (not a family's), each id once. */
282
+ const definedCommands = (0, _embedpdf_core.memo)(() => [registeredVersion, configured()], (_version, { commands }) => {
283
+ const entries = new Map(commands);
284
+ for (const [id, entry] of registered) entries.set(id, entry);
285
+ return [...entries.values()];
286
+ });
287
+ const derive = (derivation, context, absent) => {
288
+ if (!derivation) return absent;
42
289
  try {
43
- return fn(c);
290
+ return derivation(context);
44
291
  } catch {
45
- return fallback;
292
+ return false;
46
293
  }
47
294
  };
48
- /** Same guard as `derive`, for the icon-accent derivation: a throw (no
49
- * document, provider missing) means "no accent" — the icon renders plain. */
50
- const deriveAccent = (fn, c) => {
51
- if (!fn) return void 0;
295
+ const deriveAccent = (derivation, context) => {
296
+ if (!derivation) return void 0;
52
297
  try {
53
- return fn(c) ?? void 0;
298
+ return derivation(context) ?? void 0;
54
299
  } catch {
55
300
  return;
56
301
  }
57
302
  };
58
- const resolve = (id, documentId) => {
59
- const entry = registry.get(id);
60
- if (!entry) return null;
61
- const { def } = entry;
62
- const c = commandCtx(documentId);
63
- const disabled = ctx.getState().disabledCategories;
64
- const categoryHidden = (def.categories ?? []).some((cat) => disabled.includes(cat));
65
- const i18n = c.tryGet(_embedpdf_plugin_i18n.I18nToken);
66
- const label = i18n ? i18n.t(def.labelKey) : def.labelKey;
303
+ const namesOf = (family, context) => {
304
+ try {
305
+ return family.names(context);
306
+ } catch {
307
+ return NO_NAMES;
308
+ }
309
+ };
310
+ const { isTurnedOff, notAllowedKeyOf, lockOf, refusalOf } = createAvailability(ctx, settings);
311
+ const derivationsOf = (entry, documentId) => {
312
+ const { definition } = entry;
313
+ const context = commandContext(documentId);
314
+ const label = labelOf(definition, context);
315
+ const turnedOff = isTurnedOff(definition);
316
+ const notAllowed = turnedOff ? null : notAllowedKeyOf(definition, context);
317
+ const shownWhenNotAllowed = settings.get().notAllowed === "disable";
318
+ const lock = turnedOff || notAllowed !== null ? null : lockOf(definition, context);
319
+ const ruledOut = turnedOff || notAllowed !== null || lock !== null;
67
320
  let active;
68
- if (def.active) active = derive(def.active, c, false);
321
+ if (definition.active) active = derive(definition.active, context, false);
69
322
  else {
70
- const shell = c.tryGet(_embedpdf_plugin_shell.ShellToken);
71
- const panel = panelTarget(def);
72
- active = shell ? def.menu ? shell.isMenuOpen(def.menu) : panel ? shell.isOpen(panel.id) : def.modal ? shell.isOpen(def.modal) : false : false;
323
+ const shell = context.tryGet(_embedpdf_plugin_shell_contract.ShellToken);
324
+ const panel = panelTarget(definition);
325
+ active = shell ? definition.menu ? shell.isMenuOpen(definition.menu) : panel ? shell.isOpen(panel.id) : definition.modal ? shell.isOpen(definition.modal) : false : false;
73
326
  }
74
- return {
75
- id: def.id,
327
+ const accent = deriveAccent(definition.iconAccent, context);
328
+ return [
329
+ entry,
76
330
  label,
77
- icon: def.icon,
78
- iconAccent: deriveAccent(def.iconAccent, c),
79
- shortcuts: entry.shortcuts,
80
- menu: def.menu,
81
- enabled: derive(def.enabled, c, true) && !categoryHidden,
331
+ accent?.primary,
332
+ accent?.secondary,
333
+ !ruledOut && derive(definition.enabled, context, true),
82
334
  active,
83
- visible: derive(def.visible, c, true) && !categoryHidden,
84
- categories: def.categories ?? []
85
- };
335
+ !turnedOff && (notAllowed === null || shownWhenNotAllowed) && derive(definition.visible, context, true),
336
+ notAllowed !== null && shownWhenNotAllowed ? notAllowedMessage(notAllowed, label, context) : lock !== null ? lockedMessage(lock, label, context) : void 0
337
+ ];
86
338
  };
87
- const execute = (id, documentId) => {
88
- const entry = registry.get(id);
89
- if (!entry) return;
90
- const resolved = resolve(id, documentId);
91
- if (!resolved || !resolved.enabled || !resolved.visible) return;
92
- const c = commandCtx(documentId);
93
- if (entry.def.run) {
94
- entry.def.run(c);
339
+ /** A resolved command, the same object until one of its derivations or its entry changes. */
340
+ const resolvedByKey = (0, _embedpdf_core.memoByKey)((key) => {
341
+ const [id, documentId] = JSON.parse(key);
342
+ const entry = entryOf(id);
343
+ return entry ? derivationsOf(entry, documentId ?? void 0) : NOT_REGISTERED;
344
+ }, (_key, entry, label, accentPrimary, accentSecondary, enabled, active, visible, disabledReason) => entry && {
345
+ id: entry.definition.id,
346
+ label,
347
+ icon: entry.definition.icon,
348
+ iconAccent: accentOf(accentPrimary, accentSecondary),
349
+ shortcuts: entry.shortcuts,
350
+ menu: entry.definition.menu,
351
+ enabled,
352
+ active,
353
+ visible,
354
+ categories: entry.definition.categories ?? [],
355
+ ...disabledReason === void 0 ? {} : { disabledReason }
356
+ });
357
+ const resolveCommand = (id, documentId) => entryOf(id) ? resolvedByKey(resolutionKey(id, documentId)) : null;
358
+ /**
359
+ * Every command's id for a document (`''` is the active one): the defined ones in the order
360
+ * they were added, then each family's names that no defined command took.
361
+ */
362
+ const idsByDocument = (0, _embedpdf_core.memoByKey)((documentKey) => {
363
+ const config = configured();
364
+ const context = commandContext(documentKey || void 0);
365
+ return [
366
+ definedCommands(),
367
+ config,
368
+ ...config.families.map((family) => namesOf(family, context))
369
+ ];
370
+ }, (_documentKey, ...inputs) => {
371
+ const [defined, { families }, ...names] = inputs;
372
+ const ids = defined.map((entry) => entry.definition.id);
373
+ const taken = new Set(ids);
374
+ families.forEach((family, index) => {
375
+ for (const name of names[index] ?? NO_NAMES) {
376
+ const id = `${family.prefix}${name}`;
377
+ if (taken.has(id)) continue;
378
+ taken.add(id);
379
+ ids.push(id);
380
+ }
381
+ });
382
+ return ids;
383
+ });
384
+ const commandsByDocument = (0, _embedpdf_core.memoByKey)((documentKey) => idsByDocument(documentKey).map((id) => resolveCommand(id, documentKey || void 0)), (_documentKey, ...resolved) => resolved.filter((command) => command !== null));
385
+ const listCommands = (documentId) => commandsByDocument(documentId ?? "");
386
+ const listShortcuts = (0, _embedpdf_core.memo)(() => [definedCommands()], (entries) => entries.flatMap((entry) => entry.shortcuts.map((shortcut) => ({
387
+ commandId: entry.definition.id,
388
+ shortcut
389
+ }))));
390
+ /** What running a command does: its `run`, or opening what it opens. */
391
+ const runCommand = async (definition, context) => {
392
+ if (definition.run) {
393
+ await definition.run(context);
95
394
  return;
96
395
  }
97
- const shell = c.tryGet(_embedpdf_plugin_shell.ShellToken);
396
+ const shell = context.tryGet(_embedpdf_plugin_shell_contract.ShellToken);
397
+ const panel = panelTarget(definition);
98
398
  if (!shell) return;
99
- const panel = panelTarget(entry.def);
100
- if (entry.def.menu) shell.toggleMenu(entry.def.menu);
101
- else if (panel) shell.toggle(panel.id, { exclusive: panel.exclusive });
102
- else if (entry.def.modal) shell.toggle(entry.def.modal, { exclusive: "modal" });
399
+ if (definition.menu) shell.toggleMenu(definition.menu);
400
+ else if (panel) shell.toggle(panel.id, {
401
+ exclusive: panel.exclusive,
402
+ focus: panel.focus
403
+ });
404
+ else if (definition.modal) shell.toggle(definition.modal, { exclusive: "modal" });
103
405
  };
104
- return {
105
- register: (def) => registerCommand(registry, def),
106
- unregister: (id) => void registry.delete(id),
107
- has: (id) => registry.has(id),
108
- ids: () => [...registry.keys()],
109
- resolve,
110
- search: (query, documentId) => {
111
- const q = query.trim().toLowerCase();
112
- const hits = [];
113
- for (const id of registry.keys()) {
114
- const r = resolve(id, documentId);
115
- if (!r || !r.visible) continue;
116
- if (q === "" || r.label.toLowerCase().includes(q) || r.id.includes(q)) hits.push(r);
117
- }
118
- return hits;
406
+ const execute = async (id, options = {}) => {
407
+ const { signal, documentId, args } = options;
408
+ if (signal?.aborted) throw new _embedpdf_core.PluginError("operation-cancelled", "commands", "operation cancelled");
409
+ const entry = entryOf(id);
410
+ if (!entry) return {
411
+ status: "rejected",
412
+ reason: "not-found"
413
+ };
414
+ const resolved = resolveCommand(id, documentId);
415
+ if (!resolved?.visible) return {
416
+ status: "rejected",
417
+ reason: "hidden"
418
+ };
419
+ if (!resolved.enabled) return {
420
+ status: "rejected",
421
+ reason: "disabled"
422
+ };
423
+ const context = commandContext(documentId, {
424
+ args,
425
+ signal
426
+ });
427
+ try {
428
+ await ctx.cancellable(signal, runCommand(entry.definition, context));
429
+ } catch (error) {
430
+ if (signal?.aborted && (0, _embedpdf_core.isPluginError)(error, "operation-cancelled")) throw error;
431
+ const failure = (0, _embedpdf_core.toPluginError)("commands", error);
432
+ executionFailed.emit({
433
+ commandId: id,
434
+ documentId: context.documentId,
435
+ error: (0, _embedpdf_core.toPluginErrorInfo)(failure)
436
+ });
437
+ throw failure;
438
+ } finally {
439
+ ctx.notify();
440
+ }
441
+ executed.emit({
442
+ commandId: id,
443
+ documentId: context.documentId,
444
+ args
445
+ });
446
+ return { status: "executed" };
447
+ };
448
+ const registerOne = (definition, options) => {
449
+ if ((registered.has(definition.id) || configured().commands.has(definition.id)) && !options?.replace) throw new _embedpdf_core.PluginError("conflict", "commands", `duplicate command '${definition.id}'`);
450
+ const entry = registeredCommand(definition);
451
+ registered.set(definition.id, entry);
452
+ registeredChanged();
453
+ return () => {
454
+ if (registered.get(definition.id) !== entry) return;
455
+ registered.delete(definition.id);
456
+ registeredChanged();
457
+ };
458
+ };
459
+ const turningOff = createTurningOff(settings, (id) => entryOf(id)?.definition ?? null, isTurnedOff);
460
+ return { api: {
461
+ ...settings.api,
462
+ registerCommand: registerOne,
463
+ registerCommands: (definitions, options) => {
464
+ const removers = definitions.map((definition) => registerOne(definition, options));
465
+ return () => removers.forEach((remove) => remove());
119
466
  },
120
- menuTarget: (id) => {
121
- const entry = registry.get(id);
122
- return entry ? { menu: entry.def.menu } : null;
467
+ hasCommand: (id) => entryOf(id) !== null,
468
+ getCommand: (id) => entryOf(id)?.definition ?? null,
469
+ listCommandIds: () => idsByDocument(""),
470
+ resolveCommand,
471
+ listCommands,
472
+ searchCommands: (query, documentId) => {
473
+ const needle = query.trim().toLowerCase();
474
+ return listCommands(documentId).filter((command) => command.visible && (needle === "" || command.label.toLowerCase().includes(needle) || command.id.includes(needle)));
123
475
  },
476
+ listShortcuts,
124
477
  execute,
125
- matchStroke: (stroke, opts) => {
126
- for (const [id, entry] of registry) if (entry.parsed.some((p) => (0, _embedpdf_core_ui.matchShortcut)(p, stroke, opts))) return id;
127
- return null;
478
+ canExecute: (id, documentId) => {
479
+ const resolved = resolveCommand(id, documentId);
480
+ return !!resolved && resolved.enabled && resolved.visible;
128
481
  },
129
- disabledCategories: () => ctx.getState().disabledCategories,
130
- isCategoryDisabled: (category) => ctx.getState().disabledCategories.includes(category),
131
- disableCategory: (category) => ctx.dispatch({
132
- type: "COMMANDS/DISABLE_CATEGORY",
133
- category
134
- }),
135
- enableCategory: (category) => ctx.dispatch({
136
- type: "COMMANDS/ENABLE_CATEGORY",
137
- category
138
- }),
139
- setDisabledCategories: (categories) => ctx.dispatch({
140
- type: "COMMANDS/SET_DISABLED_CATEGORIES",
141
- categories
142
- })
143
- };
144
- }
145
- //#endregion
146
- //#region src/reducer.ts
147
- const initialCommandsState = { disabledCategories: [] };
148
- function commandsReducer(state, action) {
149
- switch (action.type) {
150
- case "COMMANDS/DISABLE_CATEGORY": return state.disabledCategories.includes(action.category) ? state : { disabledCategories: [...state.disabledCategories, action.category] };
151
- case "COMMANDS/ENABLE_CATEGORY": return state.disabledCategories.includes(action.category) ? { disabledCategories: state.disabledCategories.filter((c) => c !== action.category) } : state;
152
- case "COMMANDS/SET_DISABLED_CATEGORIES": return { disabledCategories: [...action.categories] };
153
- default: return state;
154
- }
482
+ getRefusal: (id, documentId) => {
483
+ const entry = entryOf(id);
484
+ return entry ? refusalOf(entry.definition, commandContext(documentId)) : null;
485
+ },
486
+ ...turningOff,
487
+ onExecuted: executed.on,
488
+ onExecutionFailed: executionFailed.on,
489
+ matchStroke: (stroke, options) => {
490
+ let refused = null;
491
+ for (const entry of definedCommands()) {
492
+ if (options.inTextField && !entry.definition.shortcutInTextFields) continue;
493
+ if (!entry.parsed.some((shortcut) => (0, _embedpdf_core_ui.matchShortcut)(shortcut, stroke, options))) continue;
494
+ const context = commandContext();
495
+ const refusal = refusalOf(entry.definition, context);
496
+ if (!refusal) return {
497
+ commandId: entry.definition.id,
498
+ refusal: null
499
+ };
500
+ if (!derive(entry.definition.visible, context, true)) continue;
501
+ refused ?? (refused = {
502
+ commandId: entry.definition.id,
503
+ refusal
504
+ });
505
+ }
506
+ return refused;
507
+ },
508
+ getMenuTarget: (id) => {
509
+ const entry = entryOf(id);
510
+ return entry ? { menu: entry.definition.menu } : null;
511
+ }
512
+ } };
155
513
  }
156
514
  //#endregion
157
- //#region src/types.ts
158
- /** Value equality over resolved commands — `resolve()` mints a fresh object
159
- * per read, so reactive bindings memo by value to re-render on real change. */
160
- const resolvedCommandsEqual = (a, b) => {
161
- if (a === b) return true;
162
- if (!a || !b) return false;
163
- return a.id === b.id && a.label === b.label && a.icon === b.icon && a.iconAccent?.primary === b.iconAccent?.primary && a.iconAccent?.secondary === b.iconAccent?.secondary && a.menu === b.menu && a.enabled === b.enabled && a.active === b.active && a.visible === b.visible && a.shortcuts.length === b.shortcuts.length && a.shortcuts.every((s, i) => s === b.shortcuts[i]);
164
- };
165
- const CommandsToken = (0, _embedpdf_core.createCapabilityToken)("commands");
166
- //#endregion
167
515
  //#region src/commands.plugin.ts
168
516
  /**
169
- * The commands plugin: workspace-scoped (one vocabulary for the whole
170
- * workspace; resolution/execution bind to a target document per call).
171
- * Definitions live in this closure — never in the store (they hold
172
- * functions); the store slice holds only `disabledCategories`.
517
+ * The commands: one set for the whole workspace, each resolved and run for a
518
+ * document (the one named, else the document in scope, else the active one).
519
+ * Definitions are settings and app content, never state, since they hold
520
+ * functions. `config` is the settings the app registers, over
521
+ * {@link COMMANDS_DEFAULTS}.
173
522
  */
174
- const commandsPlugin = (config) => {
175
- const registry = /* @__PURE__ */ new Map();
176
- for (const def of config?.commands ?? []) registerCommand(registry, def);
177
- return (0, _embedpdf_core.definePlugin)({
178
- id: "commands",
179
- scope: "workspace",
180
- token: CommandsToken,
181
- initialState: {
182
- ...initialCommandsState,
183
- disabledCategories: [...config?.disabledCategories ?? []]
184
- },
185
- reduce: commandsReducer,
186
- capability: (ctx) => createCommandsCapability(ctx, registry)
187
- });
188
- };
523
+ const commandsPlugin = (config) => (0, _embedpdf_core.definePlugin)({
524
+ id: "commands",
525
+ scope: "workspace",
526
+ token: require_contract_host.CommandsToken,
527
+ optional: [_embedpdf_plugin_i18n_contract.I18nToken, _embedpdf_plugin_shell_contract.ShellToken],
528
+ resolvesAnyCapability: true,
529
+ settings: {
530
+ defaults: require_contract.COMMANDS_DEFAULTS,
531
+ registered: config,
532
+ whole: ["appState"]
533
+ },
534
+ create: createCommandsController,
535
+ inScope: (commands, documentId) => ({
536
+ ...commands,
537
+ resolveCommand: (id, target = documentId) => commands.resolveCommand(id, target),
538
+ listCommands: (target = documentId) => commands.listCommands(target),
539
+ searchCommands: (query, target = documentId) => commands.searchCommands(query, target),
540
+ execute: (id, options) => commands.execute(id, {
541
+ ...options,
542
+ documentId: options?.documentId ?? documentId
543
+ }),
544
+ canExecute: (id, target = documentId) => commands.canExecute(id, target),
545
+ getRefusal: (id, target = documentId) => commands.getRefusal(id, target)
546
+ })
547
+ });
189
548
  //#endregion
190
- exports.CommandsToken = CommandsToken;
549
+ exports.COMMANDS_DEFAULTS = require_contract.COMMANDS_DEFAULTS;
550
+ exports.CommandsToken = require_contract.CommandsToken;
551
+ exports.boundCommandOf = require_contract.boundCommandOf;
191
552
  exports.commandsPlugin = commandsPlugin;
192
- exports.commandsReducer = commandsReducer;
193
- exports.initialCommandsState = initialCommandsState;
194
- exports.resolvedCommandsEqual = resolvedCommandsEqual;
553
+ exports.resolvedCommandsEqual = require_contract.resolvedCommandsEqual;
554
+ exports.unknownCommandWarning = require_contract.unknownCommandWarning;
555
+ exports.unregisteredCommand = require_contract.unregisteredCommand;
195
556
 
196
557
  //# sourceMappingURL=index.cjs.map