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