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