@embedpdf/plugin-commands 3.0.0-next.9 → 3.1.0

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