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