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

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