@lofcz/embedpdf-plugin-commands 2.15.0 → 3.0.0-next.7

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/LICENSE CHANGED
@@ -1,21 +1,192 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 CloudPDF
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Copyright 2026 CloudPDF LTD
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use files in this distribution except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ https://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ -----------------------------------------------------------------------
16
+
17
+ Apache License
18
+ Version 2.0, January 2004
19
+ http://www.apache.org/licenses/
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
package/dist/index.cjs CHANGED
@@ -1,2 +1,196 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@embedpdf/core"),t="commands",s={id:t,name:"Commands Plugin",version:"1.0.0",provides:["commands"],requires:[],optional:["i18n","ui"],defaultConfig:{commands:{}}},o="COMMANDS/SET_DISABLED_CATEGORIES",i=e=>({type:o,payload:e}),a=class extends e.BasePlugin{constructor(t,s,o){var a;super(t,s),this.commands=new Map,this.i18n=null,this.shortcutMap=new Map,this.commandExecuted$=e.createEmitter(),this.commandStateChanged$=e.createEmitter(),this.shortcutExecuted$=e.createEmitter(),this.categoryChanged$=e.createBehaviorEmitter(),this.previousStates=new Map;const r=s.getPlugin("i18n");this.i18n=(null==r?void 0:r.provides())??null,(null==(a=o.disabledCategories)?void 0:a.length)&&this.dispatch(i(o.disabledCategories)),Object.values(o.commands).forEach(e=>{this.registerCommand(e)}),this.registry.getStore().subscribe((e,t)=>{this.onGlobalStoreChange(t)})}onDocumentClosed(e){this.previousStates.delete(e),this.logger.debug("CommandsPlugin","DocumentClosed",`Cleaned up command state cache for document: ${e}`)}async initialize(){this.logger.info("CommandsPlugin","Initialize","Commands plugin initialized")}async destroy(){this.commandExecuted$.clear(),this.commandStateChanged$.clear(),this.shortcutExecuted$.clear(),this.categoryChanged$.clear(),this.commands.clear(),this.shortcutMap.clear(),this.previousStates.clear(),super.destroy()}disableCategoryImpl(e){const t=new Set(this.state.disabledCategories);t.has(e)||(t.add(e),this.dispatch(i(Array.from(t))),this.categoryChanged$.emit({disabledCategories:Array.from(t)}))}enableCategoryImpl(e){const t=new Set(this.state.disabledCategories);t.has(e)&&(t.delete(e),this.dispatch(i(Array.from(t))),this.categoryChanged$.emit({disabledCategories:Array.from(t)}))}toggleCategoryImpl(e){this.state.disabledCategories.includes(e)?this.enableCategoryImpl(e):this.disableCategoryImpl(e)}setDisabledCategoriesImpl(e){this.dispatch(i(e)),this.categoryChanged$.emit({disabledCategories:e})}isCommandCategoryDisabled(e){var t;return!!(null==(t=e.categories)?void 0:t.length)&&e.categories.some(e=>this.state.disabledCategories.includes(e))}buildCapability(){return{resolve:(e,t)=>this.resolve(e,t),execute:(e,t,s="ui")=>this.execute(e,t,s),getAllCommands:e=>this.getAllCommands(e),getCommandsByCategory:(e,t)=>this.getCommandsByCategory(e,t),getCommandByShortcut:e=>this.getCommandByShortcut(e),getAllShortcuts:()=>new Map(this.shortcutMap),forDocument:e=>this.createCommandScope(e),registerCommand:e=>this.registerCommand(e),unregisterCommand:e=>this.unregisterCommand(e),disableCategory:e=>this.disableCategoryImpl(e),enableCategory:e=>this.enableCategoryImpl(e),toggleCategory:e=>this.toggleCategoryImpl(e),setDisabledCategories:e=>this.setDisabledCategoriesImpl(e),getDisabledCategories:()=>this.state.disabledCategories,isCategoryDisabled:e=>this.state.disabledCategories.includes(e),onCommandExecuted:this.commandExecuted$.on,onCommandStateChanged:this.commandStateChanged$.on,onShortcutExecuted:this.shortcutExecuted$.on,onCategoryChanged:this.categoryChanged$.on}}createCommandScope(e){return{resolve:t=>this.resolve(t,e),execute:(t,s="ui")=>this.execute(t,e,s),getAllCommands:()=>this.getAllCommands(e),getCommandsByCategory:t=>this.getCommandsByCategory(t,e),onCommandStateChanged:t=>this.commandStateChanged$.on(s=>{if(s.documentId===e){const{documentId:e,...o}=s;t(o)}})}}resolve(e,t){const s=t??this.getActiveDocumentId(),o=this.commands.get(e);if(!o)throw new Error(`Command not found: ${e}`);const i=this.registry.getStore().getState(),a=this.resolveLabel(o,i,s),r=o.shortcuts?Array.isArray(o.shortcuts)?o.shortcuts:[o.shortcuts]:void 0,n=this.resolveDynamic(o.disabled,i,s)??!1,d=this.isCommandCategoryDisabled(o),m=n||d;return{id:o.id,label:a,icon:this.resolveDynamic(o.icon,i,s),iconProps:this.resolveDynamic(o.iconProps,i,s),active:this.resolveDynamic(o.active,i,s)??!1,disabled:m,visible:this.resolveDynamic(o.visible,i,s)??!0,shortcuts:r,shortcutLabel:o.shortcutLabel,categories:o.categories,description:o.description,execute:()=>o.action({registry:this.registry,state:i,documentId:s,logger:this.logger})}}resolveLabel(e,t,s){const o=this.resolveDynamic(e.labelKey,t,s);if(o&&this.i18n){const i=this.resolveDynamic(e.labelParams,t,s);return this.i18n.t(o,{params:i,documentId:s})}return e.label?e.label:e.id}resolveDynamic(e,t,s){if(void 0!==e)return"function"==typeof e?e({registry:this.registry,state:t,documentId:s,logger:this.logger}):e}execute(e,t,s="ui"){const o=t??this.getActiveDocumentId(),i=this.resolve(e,o);i.disabled?this.logger.warn("CommandsPlugin","ExecutionBlocked",`Command '${e}' is disabled for document '${o}'`):i.visible?(i.execute(),this.commandExecuted$.emit({commandId:e,documentId:o,source:s}),this.logger.debug("CommandsPlugin","CommandExecuted",`Command '${e}' executed for document '${o}' (source: ${s})`)):this.logger.warn("CommandsPlugin","ExecutionBlocked",`Command '${e}' is not visible for document '${o}'`)}registerCommand(e){if(this.commands.has(e.id)&&this.logger.warn("CommandsPlugin","CommandOverwrite",`Command '${e.id}' already exists and will be overwritten`),this.commands.set(e.id,e),e.shortcuts){(Array.isArray(e.shortcuts)?e.shortcuts:[e.shortcuts]).forEach(t=>{const s=this.normalizeShortcut(t);this.shortcutMap.set(s,e.id)})}this.logger.debug("CommandsPlugin","CommandRegistered",`Command '${e.id}' registered`)}unregisterCommand(e){const t=this.commands.get(e);if(t){if(t.shortcuts){(Array.isArray(t.shortcuts)?t.shortcuts:[t.shortcuts]).forEach(e=>{const t=this.normalizeShortcut(e);this.shortcutMap.delete(t)})}this.commands.delete(e),this.logger.debug("CommandsPlugin","CommandUnregistered",`Command '${e}' unregistered`)}}getCommandByShortcut(e){const t=this.normalizeShortcut(e),s=this.shortcutMap.get(t);return s?this.commands.get(s)??null:null}normalizeShortcut(e){return e.toLowerCase().split("+").sort().join("+")}getAllCommands(e){const t=e??this.getActiveDocumentId();return Array.from(this.commands.keys()).map(e=>this.resolve(e,t))}getCommandsByCategory(e,t){const s=t??this.getActiveDocumentId();return Array.from(this.commands.values()).filter(t=>{var s;return null==(s=t.categories)?void 0:s.includes(e)}).map(e=>this.resolve(e.id,s))}onGlobalStoreChange(e){Object.keys(e.core.documents).forEach(t=>{this.detectCommandChanges(t,e)})}detectCommandChanges(t,s){const o=s.core.documents[t];if(!o||"loaded"!==o.status)return;const i=this.previousStates.get(t)??new Map;this.commands.forEach((s,o)=>{const a=this.resolve(o,t),r=i.get(o);if(!r)return void i.set(o,a);const n={};r.active!==a.active&&(n.active=a.active),r.disabled!==a.disabled&&(n.disabled=a.disabled),r.visible!==a.visible&&(n.visible=a.visible),r.label!==a.label&&(n.label=a.label),r.icon!==a.icon&&(n.icon=a.icon),e.arePropsEqual(r.iconProps,a.iconProps)||(n.iconProps=a.iconProps),Object.keys(n).length>0&&(i.set(o,a),this.commandStateChanged$.emit({commandId:o,documentId:t,changes:n}))}),this.previousStates.set(t,i)}};a.id="commands";let r=a;const n={disabledCategories:[]},d={manifest:s,create:(e,s)=>new r(t,e,s),reducer:(e=n,t)=>t.type===o?{...e,disabledCategories:t.payload}:e,initialState:n};exports.COMMANDS_PLUGIN_ID=t,exports.CommandsPlugin=r,exports.CommandsPluginPackage=d,exports.manifest=s;
2
- //# sourceMappingURL=index.cjs.map
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ 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_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,
12
+ shortcuts,
13
+ parsed: shortcuts.map(_embedpdf_core_ui.parseShortcut)
14
+ });
15
+ }
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;
23
+ const get = (token) => target ? ctx.forDocument(token, target) : ctx.get(token);
24
+ return {
25
+ documentId: target,
26
+ core: ctx.core,
27
+ get,
28
+ tryGet: (token) => {
29
+ try {
30
+ return get(token);
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+ };
36
+ };
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;
42
+ try {
43
+ return fn(c);
44
+ } catch {
45
+ return fallback;
46
+ }
47
+ };
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;
52
+ try {
53
+ return fn(c) ?? void 0;
54
+ } catch {
55
+ return;
56
+ }
57
+ };
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;
73
+ }
74
+ 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 ?? []
85
+ };
86
+ };
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);
95
+ return;
96
+ }
97
+ const shell = c.tryGet(_embedpdf_plugin_shell.ShellToken);
98
+ 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" });
103
+ };
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;
119
+ },
120
+ menuTarget: (id) => {
121
+ const entry = registry.get(id);
122
+ return entry ? { menu: entry.def.menu } : null;
123
+ },
124
+ 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;
128
+ },
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
+ }
155
+ }
156
+ //#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
+ //#region src/commands.plugin.ts
168
+ /**
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`.
173
+ */
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
+ };
189
+ //#endregion
190
+ exports.CommandsToken = CommandsToken;
191
+ exports.commandsPlugin = commandsPlugin;
192
+ exports.commandsReducer = commandsReducer;
193
+ exports.initialCommandsState = initialCommandsState;
194
+ exports.resolvedCommandsEqual = resolvedCommandsEqual;
195
+
196
+ //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/lib/manifest.ts","../src/lib/actions.ts","../src/lib/commands-plugin.ts","../src/lib/reducer.ts","../src/lib/index.ts"],"sourcesContent":["import { PluginManifest } from '@embedpdf/core';\nimport { CommandsPluginConfig } from './types';\n\nexport const COMMANDS_PLUGIN_ID = 'commands';\n\nexport const manifest: PluginManifest<CommandsPluginConfig> = {\n id: COMMANDS_PLUGIN_ID,\n name: 'Commands Plugin',\n version: '1.0.0',\n provides: ['commands'],\n requires: [],\n optional: ['i18n', 'ui'],\n defaultConfig: {\n commands: {},\n },\n};\n","import { Action } from '@embedpdf/core';\n\nexport const SET_DISABLED_CATEGORIES = 'COMMANDS/SET_DISABLED_CATEGORIES';\n\nexport interface SetDisabledCategoriesAction extends Action {\n type: typeof SET_DISABLED_CATEGORIES;\n payload: string[];\n}\n\nexport type CommandsAction = SetDisabledCategoriesAction;\n\nexport const setDisabledCategories = (categories: string[]): SetDisabledCategoriesAction => ({\n type: SET_DISABLED_CATEGORIES,\n payload: categories,\n});\n","import {\n BasePlugin,\n PluginRegistry,\n StoreState,\n createEmitter,\n createBehaviorEmitter,\n Listener,\n arePropsEqual,\n} from '@embedpdf/core';\nimport { Logger } from '@embedpdf/models';\nimport { I18nCapability, I18nPlugin } from '@embedpdf/plugin-i18n';\nimport {\n CommandsCapability,\n CommandsPluginConfig,\n CommandsState,\n Command,\n ResolvedCommand,\n CommandExecutedEvent,\n CommandStateChangedEvent,\n ShortcutExecutedEvent,\n CategoryChangedEvent,\n CommandScope,\n Dynamic,\n} from './types';\nimport { CommandsAction, setDisabledCategories } from './actions';\n\nexport class CommandsPlugin extends BasePlugin<\n CommandsPluginConfig,\n CommandsCapability,\n CommandsState,\n CommandsAction\n> {\n static readonly id = 'commands' as const;\n\n private commands = new Map<string, Command>();\n private i18n: I18nCapability | null = null;\n private shortcutMap = new Map<string, string>(); // shortcut -> commandId\n\n private readonly commandExecuted$ = createEmitter<CommandExecutedEvent>();\n private readonly commandStateChanged$ = createEmitter<CommandStateChangedEvent>();\n private readonly shortcutExecuted$ = createEmitter<ShortcutExecutedEvent>();\n private readonly categoryChanged$ = createBehaviorEmitter<CategoryChangedEvent>();\n\n // Cache previous resolved states per document to detect changes\n private previousStates = new Map<string, Map<string, ResolvedCommand>>();\n\n constructor(id: string, registry: PluginRegistry, config: CommandsPluginConfig) {\n super(id, registry);\n\n // Check if i18n plugin is available (optional dependency)\n const i18nPlugin = registry.getPlugin<I18nPlugin>('i18n');\n this.i18n = i18nPlugin?.provides() ?? null;\n\n // Initialize disabled categories from config\n if (config.disabledCategories?.length) {\n this.dispatch(setDisabledCategories(config.disabledCategories));\n }\n\n // Register all commands from config\n Object.values(config.commands).forEach((command) => {\n this.registerCommand(command);\n });\n\n // Subscribe to global store changes\n this.registry.getStore().subscribe((_action, newState) => {\n this.onGlobalStoreChange(newState);\n });\n }\n\n protected override onDocumentClosed(documentId: string): void {\n // Cleanup previous states cache\n this.previousStates.delete(documentId);\n\n this.logger.debug(\n 'CommandsPlugin',\n 'DocumentClosed',\n `Cleaned up command state cache for document: ${documentId}`,\n );\n }\n\n async initialize(): Promise<void> {\n this.logger.info('CommandsPlugin', 'Initialize', 'Commands plugin initialized');\n }\n\n async destroy(): Promise<void> {\n this.commandExecuted$.clear();\n this.commandStateChanged$.clear();\n this.shortcutExecuted$.clear();\n this.categoryChanged$.clear();\n this.commands.clear();\n this.shortcutMap.clear();\n this.previousStates.clear();\n super.destroy();\n }\n\n // ─────────────────────────────────────────────────────────\n // Category Management\n // ─────────────────────────────────────────────────────────\n\n private disableCategoryImpl(category: string): void {\n const current = new Set(this.state.disabledCategories);\n if (!current.has(category)) {\n current.add(category);\n this.dispatch(setDisabledCategories(Array.from(current)));\n this.categoryChanged$.emit({ disabledCategories: Array.from(current) });\n }\n }\n\n private enableCategoryImpl(category: string): void {\n const current = new Set(this.state.disabledCategories);\n if (current.has(category)) {\n current.delete(category);\n this.dispatch(setDisabledCategories(Array.from(current)));\n this.categoryChanged$.emit({ disabledCategories: Array.from(current) });\n }\n }\n\n private toggleCategoryImpl(category: string): void {\n if (this.state.disabledCategories.includes(category)) {\n this.enableCategoryImpl(category);\n } else {\n this.disableCategoryImpl(category);\n }\n }\n\n private setDisabledCategoriesImpl(categories: string[]): void {\n this.dispatch(setDisabledCategories(categories));\n this.categoryChanged$.emit({ disabledCategories: categories });\n }\n\n /**\n * Check if command has any disabled category\n */\n private isCommandCategoryDisabled(command: Command): boolean {\n if (!command.categories?.length) return false;\n return command.categories.some((cat) => this.state.disabledCategories.includes(cat));\n }\n\n // ─────────────────────────────────────────────────────────\n // Capability\n // ─────────────────────────────────────────────────────────\n\n protected buildCapability(): CommandsCapability {\n return {\n resolve: (commandId, documentId) => this.resolve(commandId, documentId),\n execute: (commandId, documentId, source = 'ui') =>\n this.execute(commandId, documentId, source),\n getAllCommands: (documentId) => this.getAllCommands(documentId),\n getCommandsByCategory: (category, documentId) =>\n this.getCommandsByCategory(category, documentId),\n getCommandByShortcut: (shortcut) => this.getCommandByShortcut(shortcut),\n getAllShortcuts: () => new Map(this.shortcutMap),\n forDocument: (documentId) => this.createCommandScope(documentId),\n registerCommand: (command) => this.registerCommand(command),\n unregisterCommand: (commandId) => this.unregisterCommand(commandId),\n\n // Category management\n disableCategory: (category) => this.disableCategoryImpl(category),\n enableCategory: (category) => this.enableCategoryImpl(category),\n toggleCategory: (category) => this.toggleCategoryImpl(category),\n setDisabledCategories: (categories) => this.setDisabledCategoriesImpl(categories),\n getDisabledCategories: () => this.state.disabledCategories,\n isCategoryDisabled: (category) => this.state.disabledCategories.includes(category),\n\n // Events\n onCommandExecuted: this.commandExecuted$.on,\n onCommandStateChanged: this.commandStateChanged$.on,\n onShortcutExecuted: this.shortcutExecuted$.on,\n onCategoryChanged: this.categoryChanged$.on,\n };\n }\n\n // ─────────────────────────────────────────────────────────\n // Document Scoping\n // ─────────────────────────────────────────────────────────\n\n private createCommandScope(documentId: string): CommandScope {\n return {\n resolve: (commandId) => this.resolve(commandId, documentId),\n execute: (commandId, source = 'ui') => this.execute(commandId, documentId, source),\n getAllCommands: () => this.getAllCommands(documentId),\n getCommandsByCategory: (category) => this.getCommandsByCategory(category, documentId),\n onCommandStateChanged: (listener: Listener<Omit<CommandStateChangedEvent, 'documentId'>>) =>\n this.commandStateChanged$.on((event) => {\n if (event.documentId === documentId) {\n const { documentId: _, ...rest } = event;\n listener(rest);\n }\n }),\n };\n }\n\n // ─────────────────────────────────────────────────────────\n // Command Resolution\n // ─────────────────────────────────────────────────────────\n\n private resolve(commandId: string, documentId?: string): ResolvedCommand {\n const resolvedDocId = documentId ?? this.getActiveDocumentId();\n\n const command = this.commands.get(commandId);\n if (!command) {\n throw new Error(`Command not found: ${commandId}`);\n }\n\n const state = this.registry.getStore().getState();\n\n // Resolve label with i18n if available\n const label = this.resolveLabel(command, state, resolvedDocId);\n\n // Resolve shortcuts\n const shortcuts = command.shortcuts\n ? Array.isArray(command.shortcuts)\n ? command.shortcuts\n : [command.shortcuts]\n : undefined;\n\n // Check if disabled via categories OR explicit disabled predicate\n const explicitDisabled = this.resolveDynamic(command.disabled, state, resolvedDocId) ?? false;\n const categoryDisabled = this.isCommandCategoryDisabled(command);\n const isDisabled = explicitDisabled || categoryDisabled;\n\n return {\n id: command.id,\n label,\n icon: this.resolveDynamic(command.icon, state, resolvedDocId),\n iconProps: this.resolveDynamic(command.iconProps, state, resolvedDocId),\n active: this.resolveDynamic(command.active, state, resolvedDocId) ?? false,\n disabled: isDisabled,\n visible: this.resolveDynamic(command.visible, state, resolvedDocId) ?? true,\n shortcuts,\n shortcutLabel: command.shortcutLabel,\n categories: command.categories,\n description: command.description,\n execute: () =>\n command.action({\n registry: this.registry,\n state,\n documentId: resolvedDocId,\n logger: this.logger,\n }),\n };\n }\n\n private resolveLabel(command: Command, state: StoreState<any>, documentId: string): string {\n // Priority: labelKey (with i18n) > label (plain string) > id (fallback)\n const labelKey = this.resolveDynamic(command.labelKey, state, documentId);\n if (labelKey && this.i18n) {\n const params = this.resolveDynamic(command.labelParams, state, documentId);\n return this.i18n.t(labelKey, { params, documentId });\n }\n\n if (command.label) {\n return command.label;\n }\n\n return command.id; // Fallback to ID\n }\n\n private resolveDynamic<T>(\n value: Dynamic<any, T> | undefined,\n state: StoreState<any>,\n documentId: string,\n ): T | undefined {\n if (value === undefined) return undefined;\n\n // Check if it's a function (the dynamic evaluator)\n if (typeof value === 'function') {\n return (\n value as (context: {\n registry: PluginRegistry;\n state: StoreState<any>;\n documentId: string;\n logger: Logger;\n }) => T\n )({\n registry: this.registry,\n state,\n documentId,\n logger: this.logger,\n });\n }\n\n // Otherwise it's the static value\n return value as T;\n }\n\n // ─────────────────────────────────────────────────────────\n // Command Execution\n // ─────────────────────────────────────────────────────────\n\n private execute(\n commandId: string,\n documentId?: string,\n source: 'keyboard' | 'ui' | 'api' = 'ui',\n ): void {\n const resolvedDocId = documentId ?? this.getActiveDocumentId();\n const resolved = this.resolve(commandId, resolvedDocId);\n\n if (resolved.disabled) {\n this.logger.warn(\n 'CommandsPlugin',\n 'ExecutionBlocked',\n `Command '${commandId}' is disabled for document '${resolvedDocId}'`,\n );\n return;\n }\n\n if (!resolved.visible) {\n this.logger.warn(\n 'CommandsPlugin',\n 'ExecutionBlocked',\n `Command '${commandId}' is not visible for document '${resolvedDocId}'`,\n );\n return;\n }\n\n resolved.execute();\n\n this.commandExecuted$.emit({\n commandId,\n documentId: resolvedDocId,\n source,\n });\n\n this.logger.debug(\n 'CommandsPlugin',\n 'CommandExecuted',\n `Command '${commandId}' executed for document '${resolvedDocId}' (source: ${source})`,\n );\n }\n\n // ─────────────────────────────────────────────────────────\n // Command Registration\n // ─────────────────────────────────────────────────────────\n\n private registerCommand(command: Command): void {\n if (this.commands.has(command.id)) {\n this.logger.warn(\n 'CommandsPlugin',\n 'CommandOverwrite',\n `Command '${command.id}' already exists and will be overwritten`,\n );\n }\n\n this.commands.set(command.id, command);\n\n // Register shortcuts\n if (command.shortcuts) {\n const shortcuts = Array.isArray(command.shortcuts) ? command.shortcuts : [command.shortcuts];\n\n shortcuts.forEach((shortcut) => {\n const normalized = this.normalizeShortcut(shortcut);\n this.shortcutMap.set(normalized, command.id);\n });\n }\n\n this.logger.debug('CommandsPlugin', 'CommandRegistered', `Command '${command.id}' registered`);\n }\n\n private unregisterCommand(commandId: string): void {\n const command = this.commands.get(commandId);\n if (!command) return;\n\n // Remove shortcuts\n if (command.shortcuts) {\n const shortcuts = Array.isArray(command.shortcuts) ? command.shortcuts : [command.shortcuts];\n\n shortcuts.forEach((shortcut) => {\n const normalized = this.normalizeShortcut(shortcut);\n this.shortcutMap.delete(normalized);\n });\n }\n\n this.commands.delete(commandId);\n this.logger.debug(\n 'CommandsPlugin',\n 'CommandUnregistered',\n `Command '${commandId}' unregistered`,\n );\n }\n\n // ─────────────────────────────────────────────────────────\n // Shortcuts\n // ─────────────────────────────────────────────────────────\n\n private getCommandByShortcut(shortcut: string): Command | null {\n const normalized = this.normalizeShortcut(shortcut);\n const commandId = this.shortcutMap.get(normalized);\n return commandId ? (this.commands.get(commandId) ?? null) : null;\n }\n\n private normalizeShortcut(shortcut: string): string {\n // Normalize: \"Ctrl+Shift+A\" -> \"ctrl+shift+a\"\n return shortcut.toLowerCase().split('+').sort().join('+');\n }\n\n // ─────────────────────────────────────────────────────────\n // Query Methods\n // ─────────────────────────────────────────────────────────\n\n private getAllCommands(documentId?: string): ResolvedCommand[] {\n const resolvedDocId = documentId ?? this.getActiveDocumentId();\n return Array.from(this.commands.keys()).map((id) => this.resolve(id, resolvedDocId));\n }\n\n private getCommandsByCategory(category: string, documentId?: string): ResolvedCommand[] {\n const resolvedDocId = documentId ?? this.getActiveDocumentId();\n return Array.from(this.commands.values())\n .filter((cmd) => cmd.categories?.includes(category))\n .map((cmd) => this.resolve(cmd.id, resolvedDocId));\n }\n\n // ─────────────────────────────────────────────────────────\n // State Change Detection\n // ─────────────────────────────────────────────────────────\n\n private onGlobalStoreChange(newState: StoreState<any>): void {\n // Get all documents from core state\n const documentIds = Object.keys(newState.core.documents);\n\n // Check each document for command state changes\n documentIds.forEach((documentId) => {\n this.detectCommandChanges(documentId, newState);\n });\n }\n\n private detectCommandChanges(documentId: string, newState: StoreState<any>): void {\n // Skip if document isn't fully loaded yet\n const coreDoc = newState.core.documents[documentId];\n if (!coreDoc || coreDoc.status !== 'loaded') return;\n\n const previousCache = this.previousStates.get(documentId) ?? new Map();\n const changedCommandIds: string[] = [];\n\n this.commands.forEach((command, commandId) => {\n const newResolved = this.resolve(commandId, documentId);\n const prevResolved = previousCache.get(commandId);\n\n if (!prevResolved) {\n // First time resolving for this document\n previousCache.set(commandId, newResolved);\n return;\n }\n\n // Check for changes\n const changes: CommandStateChangedEvent['changes'] = {};\n\n if (prevResolved.active !== newResolved.active) {\n changes.active = newResolved.active;\n }\n if (prevResolved.disabled !== newResolved.disabled) {\n changes.disabled = newResolved.disabled;\n }\n if (prevResolved.visible !== newResolved.visible) {\n changes.visible = newResolved.visible;\n }\n if (prevResolved.label !== newResolved.label) {\n changes.label = newResolved.label;\n }\n if (prevResolved.icon !== newResolved.icon) {\n changes.icon = newResolved.icon;\n }\n if (!arePropsEqual(prevResolved.iconProps, newResolved.iconProps)) {\n changes.iconProps = newResolved.iconProps;\n }\n\n if (Object.keys(changes).length > 0) {\n changedCommandIds.push(commandId);\n previousCache.set(commandId, newResolved);\n\n this.commandStateChanged$.emit({\n commandId,\n documentId,\n changes,\n });\n }\n });\n\n this.previousStates.set(documentId, previousCache);\n }\n}\n","import { Reducer } from '@embedpdf/core';\nimport { CommandsState } from './types';\nimport { CommandsAction, SET_DISABLED_CATEGORIES } from './actions';\n\nexport const initialState: CommandsState = {\n disabledCategories: [],\n};\n\nexport const commandsReducer: Reducer<CommandsState, CommandsAction> = (\n state = initialState,\n action,\n) => {\n switch (action.type) {\n case SET_DISABLED_CATEGORIES:\n return {\n ...state,\n disabledCategories: action.payload,\n };\n\n default:\n return state;\n }\n};\n","import { PluginPackage } from '@embedpdf/core';\nimport { manifest, COMMANDS_PLUGIN_ID } from './manifest';\nimport { CommandsPluginConfig, CommandsState } from './types';\nimport { CommandsPlugin } from './commands-plugin';\nimport { CommandsAction } from './actions';\nimport { commandsReducer, initialState } from './reducer';\n\nexport const CommandsPluginPackage: PluginPackage<\n CommandsPlugin,\n CommandsPluginConfig,\n CommandsState,\n CommandsAction\n> = {\n manifest,\n create: (registry, config) => new CommandsPlugin(COMMANDS_PLUGIN_ID, registry, config),\n reducer: commandsReducer,\n initialState,\n};\n\nexport * from './commands-plugin';\nexport * from './types';\nexport * from './manifest';\n"],"names":["COMMANDS_PLUGIN_ID","manifest","id","name","version","provides","requires","optional","defaultConfig","commands","SET_DISABLED_CATEGORIES","setDisabledCategories","categories","type","payload","_CommandsPlugin","BasePlugin","constructor","registry","config","super","this","Map","i18n","shortcutMap","commandExecuted$","createEmitter","commandStateChanged$","shortcutExecuted$","categoryChanged$","createBehaviorEmitter","previousStates","i18nPlugin","getPlugin","_a","disabledCategories","length","dispatch","Object","values","forEach","command","registerCommand","getStore","subscribe","_action","newState","onGlobalStoreChange","onDocumentClosed","documentId","delete","logger","debug","initialize","info","destroy","clear","disableCategoryImpl","category","current","Set","state","has","add","Array","from","emit","enableCategoryImpl","toggleCategoryImpl","includes","setDisabledCategoriesImpl","isCommandCategoryDisabled","some","cat","buildCapability","resolve","commandId","execute","source","getAllCommands","getCommandsByCategory","getCommandByShortcut","shortcut","getAllShortcuts","forDocument","createCommandScope","unregisterCommand","disableCategory","enableCategory","toggleCategory","getDisabledCategories","isCategoryDisabled","onCommandExecuted","on","onCommandStateChanged","onShortcutExecuted","onCategoryChanged","listener","event","_","rest","resolvedDocId","getActiveDocumentId","get","Error","getState","label","resolveLabel","shortcuts","isArray","explicitDisabled","resolveDynamic","disabled","categoryDisabled","isDisabled","icon","iconProps","active","visible","shortcutLabel","description","action","labelKey","params","labelParams","t","value","resolved","warn","set","normalized","normalizeShortcut","toLowerCase","split","sort","join","keys","map","filter","cmd","core","documents","detectCommandChanges","coreDoc","status","previousCache","newResolved","prevResolved","changes","arePropsEqual","CommandsPlugin","initialState","CommandsPluginPackage","create","reducer"],"mappings":"kHAGaA,EAAqB,WAErBC,EAAiD,CAC5DC,GAAIF,EACJG,KAAM,kBACNC,QAAS,QACTC,SAAU,CAAC,YACXC,SAAU,GACVC,SAAU,CAAC,OAAQ,MACnBC,cAAe,CACbC,SAAU,CAAA,ICXDC,EAA0B,mCAS1BC,EAAyBC,IAAA,CACpCC,KAAMH,EACNI,QAASF,ICaEG,EAAN,cAA6BC,EAAAA,WAoBlC,WAAAC,CAAYf,EAAYgB,EAA0BC,SAChDC,MAAMlB,EAAIgB,GAbZG,KAAQZ,aAAea,IACvBD,KAAQE,KAA8B,KACtCF,KAAQG,gBAAkBF,IAE1BD,KAAiBI,iBAAmBC,kBACpCL,KAAiBM,qBAAuBD,kBACxCL,KAAiBO,kBAAoBF,kBACrCL,KAAiBQ,iBAAmBC,0BAGpCT,KAAQU,mBAAqBT,IAM3B,MAAMU,EAAad,EAASe,UAAsB,QAClDZ,KAAKE,YAAOS,WAAY3B,aAAc,MAGlC,OAAA6B,EAAAf,EAAOgB,yBAAP,EAAAD,EAA2BE,SAC7Bf,KAAKgB,SAAS1B,EAAsBQ,EAAOgB,qBAI7CG,OAAOC,OAAOpB,EAAOV,UAAU+B,QAASC,IACtCpB,KAAKqB,gBAAgBD,KAIvBpB,KAAKH,SAASyB,WAAWC,UAAU,CAACC,EAASC,KAC3CzB,KAAK0B,oBAAoBD,IAE7B,CAEmB,gBAAAE,CAAiBC,GAElC5B,KAAKU,eAAemB,OAAOD,GAE3B5B,KAAK8B,OAAOC,MACV,iBACA,iBACA,gDAAgDH,IAEpD,CAEA,gBAAMI,GACJhC,KAAK8B,OAAOG,KAAK,iBAAkB,aAAc,8BACnD,CAEA,aAAMC,GACJlC,KAAKI,iBAAiB+B,QACtBnC,KAAKM,qBAAqB6B,QAC1BnC,KAAKO,kBAAkB4B,QACvBnC,KAAKQ,iBAAiB2B,QACtBnC,KAAKZ,SAA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AAW3B,GACtCkG,EAAeF,EAAc1C,IAAI3B,GAEvC,IAAKuE,EAGH,YADAF,EAAchB,IAAIrD,EAAWsE,GAK/B,MAAME,EAA+C,CAAA,EAEjDD,EAAa9B,SAAW6B,EAAY7B,SACtC+B,EAAQ/B,OAAS6B,EAAY7B,QAE3B8B,EAAanC,WAAakC,EAAYlC,WACxCoC,EAAQpC,SAAWkC,EAAYlC,UAE7BmC,EAAa7B,UAAY4B,EAAY5B,UACvC8B,EAAQ9B,QAAU4B,EAAY5B,SAE5B6B,EAAazC,QAAUwC,EAAYxC,QACrC0C,EAAQ1C,MAAQwC,EAAYxC,OAE1ByC,EAAahC,OAAS+B,EAAY/B,OACpCiC,EAAQjC,KAAO+B,EAAY/B,MAExBkC,EAAAA,cAAcF,EAAa/B,UAAW8B,EAAY9B,aACrDgC,EAAQhC,UAAY8B,EAAY9B,WAG9B9E,OAAOkG,KAAKY,GAAShH,OAAS,IAEhC6G,EAAchB,IAAIrD,EAAWsE,GAE7B7H,KAAKM,qBAAqBuC,KAAK,CAC7BU,YACA3B,aACAmG,eAKN/H,KAAKU,eAAekG,IAAIhF,EAAYgG,EACtC,GA/bAlI,EAAgBb,GAAK,WANhB,IAAMoJ,EAANvI,ECtBA,MAAMwI,EAA8B,CACzCpH,mBAAoB,ICETqH,EAKT,CACFvJ,WACAwJ,OAAQ,CAACvI,EAAUC,IAAW,IAAImI,EAAetJ,EAAoBkB,EAAUC,GAC/EuI,QDPqE,CACrE7F,EAAQ0F,EACR9B,IAEQA,EAAO5G,OACRH,EACI,IACFmD,EACH1B,mBAAoBsF,EAAO3G,SAItB+C,ECJX0F"}
1
+ {"version":3,"file":"index.cjs","names":["parseShortcut","I18nToken","ShellToken"],"sources":["../src/capability.ts","../src/reducer.ts","../src/types.ts","../src/commands.plugin.ts"],"sourcesContent":["import type { CapabilityToken, PluginContext } from '@embedpdf/core';\nimport { I18nToken } from '@embedpdf/plugin-i18n';\nimport { ShellToken } from '@embedpdf/plugin-shell';\nimport { matchShortcut, parseShortcut } from '@embedpdf/core-ui';\nimport type { KeyStroke, ParsedShortcut } from '@embedpdf/core-ui';\nimport type {\n CommandCtx,\n CommandDef,\n CommandsAction,\n CommandsCapability,\n CommandsState,\n IconAccent,\n ResolvedCommand,\n} from './types';\n\n/** A registered command: the definition plus its pre-parsed shortcuts. */\nexport interface RegisteredCommand {\n readonly def: CommandDef;\n readonly shortcuts: readonly string[];\n readonly parsed: readonly ParsedShortcut[];\n}\n\nexport type CommandRegistry = Map<string, RegisteredCommand>;\n\nexport function registerCommand(registry: CommandRegistry, def: CommandDef): void {\n if (registry.has(def.id)) throw new Error(`[commands] duplicate command: ${def.id}`);\n const shortcuts = def.shortcut === undefined ? [] : ([] as string[]).concat(def.shortcut);\n registry.set(def.id, { def, shortcuts, parsed: shortcuts.map(parseShortcut) });\n}\n\nconst panelTarget = (def: CommandDef): { id: string; exclusive?: string } | null =>\n def.panel === undefined ? null : typeof def.panel === 'string' ? { id: def.panel } : def.panel;\n\nexport function createCommandsCapability(\n ctx: PluginContext<CommandsState, CommandsAction>,\n registry: CommandRegistry,\n): CommandsCapability {\n /** Bind capability resolution to the command's target document. The kernel\n * resolves workspace tokens regardless of the document argument, so one\n * code path serves both scopes. */\n const commandCtx = (documentId?: string): CommandCtx => {\n const target = documentId ?? ctx.core().activeId;\n const get = <T>(token: CapabilityToken<T>): T =>\n target ? ctx.forDocument(token, target) : ctx.get(token);\n return {\n documentId: target,\n core: ctx.core,\n get,\n tryGet: <T>(token: CapabilityToken<T>): T | null => {\n try {\n return get(token);\n } catch {\n return null;\n }\n },\n };\n };\n\n /** Derivations run against live state; a derivation that throws (e.g. it\n * needs a document and none is open) falls back to the safe default —\n * the button renders, disabled, exactly like v2's empty state. */\n const derive = (\n fn: ((c: CommandCtx) => boolean) | undefined,\n c: CommandCtx,\n fallback: boolean,\n ): boolean => {\n if (!fn) return fallback;\n try {\n return fn(c);\n } catch {\n return fallback;\n }\n };\n\n /** Same guard as `derive`, for the icon-accent derivation: a throw (no\n * document, provider missing) means \"no accent\" — the icon renders plain. */\n const deriveAccent = (\n fn: ((c: CommandCtx) => IconAccent | null) | undefined,\n c: CommandCtx,\n ): IconAccent | undefined => {\n if (!fn) return undefined;\n try {\n return fn(c) ?? undefined;\n } catch {\n return undefined;\n }\n };\n\n const resolve = (id: string, documentId?: string): ResolvedCommand | null => {\n const entry = registry.get(id);\n if (!entry) return null;\n const { def } = entry;\n const c = commandCtx(documentId);\n\n const disabled = ctx.getState().disabledCategories;\n const categoryHidden = (def.categories ?? []).some((cat) => disabled.includes(cat));\n\n const i18n = c.tryGet(I18nToken);\n const label = i18n ? i18n.t(def.labelKey) : def.labelKey;\n\n // Surface-target commands derive `active` from the surface's open state\n // unless the definition overrides it.\n let active: boolean;\n if (def.active) {\n active = derive(def.active, c, false);\n } else {\n const shell = c.tryGet(ShellToken);\n const panel = panelTarget(def);\n active = shell\n ? def.menu\n ? shell.isMenuOpen(def.menu)\n : panel\n ? shell.isOpen(panel.id)\n : def.modal\n ? shell.isOpen(def.modal)\n : false\n : false;\n }\n\n return {\n id: def.id,\n label,\n icon: def.icon,\n iconAccent: deriveAccent(def.iconAccent, c),\n shortcuts: entry.shortcuts,\n menu: def.menu,\n enabled: derive(def.enabled, c, true) && !categoryHidden,\n active,\n visible: derive(def.visible, c, true) && !categoryHidden,\n categories: def.categories ?? [],\n };\n };\n\n const execute = (id: string, documentId?: string): void => {\n const entry = registry.get(id);\n if (!entry) return;\n const resolved = resolve(id, documentId);\n if (!resolved || !resolved.enabled || !resolved.visible) return;\n const c = commandCtx(documentId);\n\n if (entry.def.run) {\n entry.def.run(c);\n return;\n }\n // Default routing for declarative surface targets.\n const shell = c.tryGet(ShellToken);\n if (!shell) return;\n const panel = panelTarget(entry.def);\n if (entry.def.menu) shell.toggleMenu(entry.def.menu);\n else if (panel) shell.toggle(panel.id, { exclusive: panel.exclusive });\n else if (entry.def.modal) shell.toggle(entry.def.modal, { exclusive: 'modal' });\n };\n\n return {\n register: (def) => registerCommand(registry, def),\n unregister: (id) => void registry.delete(id),\n has: (id) => registry.has(id),\n ids: () => [...registry.keys()],\n\n resolve,\n search: (query, documentId) => {\n const q = query.trim().toLowerCase();\n const hits: ResolvedCommand[] = [];\n for (const id of registry.keys()) {\n const r = resolve(id, documentId);\n if (!r || !r.visible) continue;\n if (q === '' || r.label.toLowerCase().includes(q) || r.id.includes(q)) hits.push(r);\n }\n return hits;\n },\n menuTarget: (id) => {\n const entry = registry.get(id);\n return entry ? { menu: entry.def.menu } : null;\n },\n\n execute,\n matchStroke: (stroke: KeyStroke, opts) => {\n for (const [id, entry] of registry) {\n if (entry.parsed.some((p) => matchShortcut(p, stroke, opts))) return id;\n }\n return null;\n },\n\n disabledCategories: () => ctx.getState().disabledCategories,\n isCategoryDisabled: (category) => ctx.getState().disabledCategories.includes(category),\n disableCategory: (category) => ctx.dispatch({ type: 'COMMANDS/DISABLE_CATEGORY', category }),\n enableCategory: (category) => ctx.dispatch({ type: 'COMMANDS/ENABLE_CATEGORY', category }),\n setDisabledCategories: (categories) =>\n ctx.dispatch({ type: 'COMMANDS/SET_DISABLED_CATEGORIES', categories }),\n };\n}\n","import type { CommandsAction, CommandsState } from './types';\n\nexport const initialCommandsState: CommandsState = {\n disabledCategories: [],\n};\n\nexport function commandsReducer(state: CommandsState, action: CommandsAction): CommandsState {\n switch (action.type) {\n case 'COMMANDS/DISABLE_CATEGORY':\n return state.disabledCategories.includes(action.category)\n ? state\n : { disabledCategories: [...state.disabledCategories, action.category] };\n case 'COMMANDS/ENABLE_CATEGORY':\n return state.disabledCategories.includes(action.category)\n ? { disabledCategories: state.disabledCategories.filter((c) => c !== action.category) }\n : state;\n case 'COMMANDS/SET_DISABLED_CATEGORIES':\n return { disabledCategories: [...action.categories] };\n default:\n return state;\n }\n}\n","import { createCapabilityToken } from '@embedpdf/core';\nimport type { CapabilityToken, CoreState } from '@embedpdf/core';\nimport type { KeyStroke } from '@embedpdf/core-ui';\n\n/**\n * @embedpdf/plugin-commands — the contract.\n *\n * Commands are the single vocabulary of verbs: toolbars, menus, contextual\n * strips, shortcuts, and the palette are all projections of this registry.\n * The plugin ships ZERO commands (mechanism here, definitions in the product\n * — same split as plugin-i18n's locale packs).\n *\n * Command state is a pure DERIVATION over the store: `resolve()` reads other\n * capabilities' selectors at call time, so any store change is reflected on\n * the next read and the framework binding's one change stream makes every\n * consumer reactive. There is no CommandStateChangedEvent, no diffing, no\n * cache — v2's entire notification apparatus has no v3 equivalent because\n * the reactive store subsumes it.\n *\n * Definitions hold functions, so they live in the plugin's registry (config\n * + `register()`), never in the store; store state is only the serializable\n * `disabledCategories`.\n */\n\n/** What a derivation or `run` sees: capability resolution bound to the\n * command's target document (explicit, else the active one). */\nexport interface CommandCtx {\n /** The target document, or null when no document is open. */\n readonly documentId: string | null;\n core(): CoreState;\n /** Resolve a capability; document-scoped tokens bind to the target document. */\n get<T>(token: CapabilityToken<T>): T;\n /** Like `get`, but null when unavailable (no provider / no document). */\n tryGet<T>(token: CapabilityToken<T>): T | null;\n}\n\n/**\n * Up to two theme colors accompanying a command's icon — typed FACTS any\n * renderer can interpret (tint a glyph's slots, show a swatch), never\n * renderer props. The registry carries it the way it carries `icon`: as\n * data it doesn't interpret. Deliberately NOT v2's `iconProps` bag —\n * renderer-specific needs live app-side, joined by command id.\n */\nexport interface IconAccent {\n /** The mark: stroke / markup / font color. */\n readonly primary?: string;\n /** The fill, when there is one. */\n readonly secondary?: string;\n}\n\nexport interface CommandDef {\n /** Convention: 'domain:verb' — 'zoom:in', 'mode:annotate', 'panel:search'. */\n readonly id: string;\n /** i18n key, resolved through I18nToken when present (else shown verbatim). */\n readonly labelKey: string;\n readonly icon?: string;\n /** Live color accent for the icon (a tool previewing its drawing defaults).\n * A pure derivation over the store, exactly like `active`/`enabled`. */\n readonly iconAccent?: (ctx: CommandCtx) => IconAccent | null;\n /** 'Mod+K' style (ui-core grammar). Multiple bindings allowed. */\n readonly shortcut?: string | readonly string[];\n /** Feature-gating tags: a disabled category hides its commands everywhere. */\n readonly categories?: readonly string[];\n\n // ── declarative surface targets ──────────────────────────────────────────\n // A command that opens chrome DECLARES what it opens instead of doing it\n // imperatively. This is load-bearing: buttons render carets/aria-haspopup,\n // `active` derives automatically from the surface's open state, and the\n // overflow projection renders `menu` targets as nested submenus.\n /** Toggles a named dropdown menu (a MenuSchema id in the app's chrome). */\n readonly menu?: string;\n /** Toggles a named shell surface, optionally exclusive within a tag ('left'…). */\n readonly panel?: string | { readonly id: string; readonly exclusive?: string };\n /** Toggles a modal surface (exclusive within the built-in 'modal' tag). */\n readonly modal?: string;\n\n // ── pure derivations over the store ──────────────────────────────────────\n readonly enabled?: (ctx: CommandCtx) => boolean;\n readonly active?: (ctx: CommandCtx) => boolean;\n readonly visible?: (ctx: CommandCtx) => boolean;\n\n /** The verb. Optional for pure surface-target commands. Runs before the\n * default target routing when both are present. */\n readonly run?: (ctx: CommandCtx) => void;\n}\n\n/** A command as a renderer sees it — everything resolved for the target document. */\nexport interface ResolvedCommand {\n readonly id: string;\n readonly label: string;\n readonly icon?: string;\n readonly iconAccent?: IconAccent;\n readonly shortcuts: readonly string[];\n readonly menu?: string;\n readonly enabled: boolean;\n readonly active: boolean;\n readonly visible: boolean;\n readonly categories: readonly string[];\n}\n\n/** Value equality over resolved commands — `resolve()` mints a fresh object\n * per read, so reactive bindings memo by value to re-render on real change. */\nexport const resolvedCommandsEqual = (\n a: ResolvedCommand | null,\n b: ResolvedCommand | null,\n): boolean => {\n if (a === b) return true;\n if (!a || !b) return false;\n return (\n a.id === b.id &&\n a.label === b.label &&\n a.icon === b.icon &&\n // by value: resolve() mints a fresh accent object each read\n a.iconAccent?.primary === b.iconAccent?.primary &&\n a.iconAccent?.secondary === b.iconAccent?.secondary &&\n a.menu === b.menu &&\n a.enabled === b.enabled &&\n a.active === b.active &&\n a.visible === b.visible &&\n a.shortcuts.length === b.shortcuts.length &&\n a.shortcuts.every((s, i) => s === b.shortcuts[i])\n );\n};\n\nexport interface CommandsState {\n readonly disabledCategories: readonly string[];\n}\n\nexport type CommandsAction =\n | { type: 'COMMANDS/DISABLE_CATEGORY'; category: string }\n | { type: 'COMMANDS/ENABLE_CATEGORY'; category: string }\n | { type: 'COMMANDS/SET_DISABLED_CATEGORIES'; categories: readonly string[] };\n\nexport interface CommandsConfig {\n /** The app's command definitions (content — the plugin ships none). */\n commands?: readonly CommandDef[];\n /** Categories disabled at startup (host feature-gating). */\n disabledCategories?: readonly string[];\n}\n\nexport interface CommandsCapability {\n // ── registry ──\n register(def: CommandDef): void;\n unregister(id: string): void;\n has(id: string): boolean;\n ids(): string[];\n\n // ── resolution (pure reads; reactive through the store) ──\n resolve(id: string, documentId?: string): ResolvedCommand | null;\n /** Palette query: visible commands whose resolved label matches. */\n search(query: string, documentId?: string): ResolvedCommand[];\n /** The one fact the overflow projection needs (ResolveMenuTarget-shaped). */\n menuTarget(id: string): { menu?: string } | null;\n\n // ── execution (the ONLY path; guarded by enabled/visible) ──\n execute(id: string, documentId?: string): void;\n /** Match a keystroke against every registered shortcut → command id or null. */\n matchStroke(stroke: KeyStroke, opts: { isMac: boolean }): string | null;\n\n // ── category gating ──\n disabledCategories(): readonly string[];\n isCategoryDisabled(category: string): boolean;\n disableCategory(category: string): void;\n enableCategory(category: string): void;\n setDisabledCategories(categories: readonly string[]): void;\n}\n\nexport const CommandsToken = createCapabilityToken<CommandsCapability>('commands');\n","import { definePlugin } from '@embedpdf/core';\nimport { createCommandsCapability, registerCommand } from './capability';\nimport type { CommandRegistry } from './capability';\nimport { commandsReducer, initialCommandsState } from './reducer';\nimport { CommandsToken } from './types';\nimport type { CommandsAction, CommandsCapability, CommandsConfig, CommandsState } from './types';\n\n/**\n * The commands plugin: workspace-scoped (one vocabulary for the whole\n * workspace; resolution/execution bind to a target document per call).\n * Definitions live in this closure — never in the store (they hold\n * functions); the store slice holds only `disabledCategories`.\n */\nexport const commandsPlugin = (config?: CommandsConfig) => {\n const registry: CommandRegistry = new Map();\n for (const def of config?.commands ?? []) registerCommand(registry, def);\n\n return definePlugin<CommandsState, CommandsAction, CommandsCapability>({\n id: 'commands',\n scope: 'workspace',\n token: CommandsToken,\n initialState: {\n ...initialCommandsState,\n disabledCategories: [...(config?.disabledCategories ?? [])],\n },\n reduce: commandsReducer,\n capability: (ctx) => createCommandsCapability(ctx, registry),\n });\n};\n"],"mappings":";;;;;;AAwBA,SAAgB,gBAAgB,UAA2B,KAAuB;CAChF,IAAI,SAAS,IAAI,IAAI,EAAE,GAAG,MAAM,IAAI,MAAM,iCAAiC,IAAI,IAAI;CACnF,MAAM,YAAY,IAAI,aAAa,KAAA,IAAY,CAAC,IAAK,CAAC,CAAC,CAAc,OAAO,IAAI,QAAQ;CACxF,SAAS,IAAI,IAAI,IAAI;EAAE;EAAK;EAAW,QAAQ,UAAU,IAAIA,kBAAAA,aAAa;CAAE,CAAC;AAC/E;AAEA,MAAM,eAAe,QACnB,IAAI,UAAU,KAAA,IAAY,OAAO,OAAO,IAAI,UAAU,WAAW,EAAE,IAAI,IAAI,MAAM,IAAI,IAAI;AAE3F,SAAgB,yBACd,KACA,UACoB;;;;CAIpB,MAAM,cAAc,eAAoC;EACtD,MAAM,SAAS,cAAc,IAAI,KAAK,CAAC,CAAC;EACxC,MAAM,OAAU,UACd,SAAS,IAAI,YAAY,OAAO,MAAM,IAAI,IAAI,IAAI,KAAK;EACzD,OAAO;GACL,YAAY;GACZ,MAAM,IAAI;GACV;GACA,SAAY,UAAwC;IAClD,IAAI;KACF,OAAO,IAAI,KAAK;IAClB,QAAQ;KACN,OAAO;IACT;GACF;EACF;CACF;;;;CAKA,MAAM,UACJ,IACA,GACA,aACY;EACZ,IAAI,CAAC,IAAI,OAAO;EAChB,IAAI;GACF,OAAO,GAAG,CAAC;EACb,QAAQ;GACN,OAAO;EACT;CACF;;;CAIA,MAAM,gBACJ,IACA,MAC2B;EAC3B,IAAI,CAAC,IAAI,OAAO,KAAA;EAChB,IAAI;GACF,OAAO,GAAG,CAAC,KAAK,K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