@embedpdf/plugin-interaction 3.0.0-next.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/LICENSE ADDED
@@ -0,0 +1,192 @@
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 ADDED
@@ -0,0 +1,214 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _embedpdf_core = require("@embedpdf/core");
3
+ //#region src/capability.ts
4
+ /**
5
+ * The interaction hub. Tools + handlers + the captured-gesture owner + cursor
6
+ * claims live in this closure (runtime registries, not serializable state); the
7
+ * reducer state holds only the active tool id and the resolved cursor, so the UI
8
+ * can react to them. The router (`dispatch`) is the heart: on down, the first
9
+ * eligible handler (by priority) to return true OWNS the gesture; move/up route
10
+ * to it; with no owner, move is hover (cursor feedback).
11
+ *
12
+ * Cursor arbitration, top to bottom: the highest-priority CLAIM (hover feedback
13
+ * — 'move' over an annotation, 'text' over text) → over a page, the tool's
14
+ * declared cursor → over a gap, the tool's `gapCursor` (default the neutral
15
+ * arrow). The winning KEYWORD (claim or base, never gap) is then restyled
16
+ * through the armed tool's skin when it maps that keyword. One resolver, so an
17
+ * image cursor can never shadow hover feedback or outlive the page under the
18
+ * pointer.
19
+ */
20
+ function createInteractionCapability(ctx, builtinTools) {
21
+ const tools = /* @__PURE__ */ new Map();
22
+ for (const t of builtinTools) tools.set(t.id, t);
23
+ const handlers = [];
24
+ const claims = /* @__PURE__ */ new Map();
25
+ const cursorSkins = /* @__PURE__ */ new Map();
26
+ const toolCbs = /* @__PURE__ */ new Set();
27
+ let owner = null;
28
+ let overPage = false;
29
+ const toolOf = (id) => tools.get(id) ?? {
30
+ id,
31
+ cursor: "default",
32
+ enables: /* @__PURE__ */ new Set()
33
+ };
34
+ const active = () => toolOf(ctx.getState().activeToolId);
35
+ const resolveCursor = () => {
36
+ let top = null;
37
+ for (const c of claims.values()) if (!top || c.priority > top.priority) top = c;
38
+ const tool = active();
39
+ const skin = cursorSkins.get(tool.id);
40
+ if (top) return skin?.[top.cursor] ?? top.cursor;
41
+ if (!overPage) return tool.gapCursor ?? "default";
42
+ return skin?.[tool.cursor] ?? tool.cursor;
43
+ };
44
+ const syncCursor = () => {
45
+ const next = resolveCursor();
46
+ if (next !== ctx.getState().cursor) ctx.dispatch({
47
+ type: "SET_CURSOR",
48
+ cursor: next
49
+ });
50
+ };
51
+ const eligible = () => {
52
+ const tool = active();
53
+ return handlers.filter((h) => h.enabledFor(tool)).sort((a, b) => b.priority - a.priority);
54
+ };
55
+ return {
56
+ activeTool: active,
57
+ activeToolId: () => ctx.getState().activeToolId,
58
+ cursor: () => ctx.getState().cursor,
59
+ tools: () => [...tools.values()],
60
+ activateTool: (id) => {
61
+ if (!tools.has(id)) throw new Error(`[interaction] unknown tool '${id}'`);
62
+ owner = null;
63
+ claims.clear();
64
+ ctx.dispatch({
65
+ type: "SET_TOOL",
66
+ toolId: id
67
+ });
68
+ syncCursor();
69
+ toolCbs.forEach((cb) => cb());
70
+ },
71
+ onToolChange: (cb) => {
72
+ toolCbs.add(cb);
73
+ return () => toolCbs.delete(cb);
74
+ },
75
+ registerTool: (tool) => {
76
+ tools.set(tool.id, tool);
77
+ return () => {
78
+ tools.delete(tool.id);
79
+ cursorSkins.delete(tool.id);
80
+ };
81
+ },
82
+ setToolCursor: (id, skin) => {
83
+ if (skin === null) cursorSkins.delete(id);
84
+ else cursorSkins.set(id, skin);
85
+ syncCursor();
86
+ },
87
+ registerHandler: (handler) => {
88
+ handlers.push(handler);
89
+ return () => {
90
+ const i = handlers.indexOf(handler);
91
+ if (i >= 0) handlers.splice(i, 1);
92
+ if (owner === handler) owner = null;
93
+ };
94
+ },
95
+ setCursor: (token, cursor, priority = 0) => {
96
+ if (cursor === null) claims.delete(token);
97
+ else claims.set(token, {
98
+ cursor,
99
+ priority
100
+ });
101
+ syncCursor();
102
+ },
103
+ dispatch: (sample) => {
104
+ const nowOverPage = sample.page != null;
105
+ if (nowOverPage !== overPage) {
106
+ overPage = nowOverPage;
107
+ syncCursor();
108
+ }
109
+ if (sample.phase === "down") {
110
+ owner = null;
111
+ for (const h of eligible()) if (h.onDown(sample)) {
112
+ owner = h;
113
+ break;
114
+ }
115
+ } else if (sample.phase === "move") if (owner) owner.onMove?.(sample);
116
+ else for (const h of eligible()) h.onHover?.(sample);
117
+ else {
118
+ owner?.onUp?.(sample);
119
+ owner = null;
120
+ }
121
+ }
122
+ };
123
+ }
124
+ //#endregion
125
+ //#region src/reducer.ts
126
+ const initialInteractionState = (config) => ({
127
+ activeToolId: config.defaultTool ?? "pointer",
128
+ cursor: "default"
129
+ });
130
+ const interactionReducer = (state, action) => {
131
+ switch (action.type) {
132
+ case "SET_TOOL": return state.activeToolId === action.toolId ? state : {
133
+ ...state,
134
+ activeToolId: action.toolId
135
+ };
136
+ case "SET_CURSOR": return state.cursor === action.cursor ? state : {
137
+ ...state,
138
+ cursor: action.cursor
139
+ };
140
+ default: return state;
141
+ }
142
+ };
143
+ //#endregion
144
+ //#region src/types.ts
145
+ const InteractionToken = (0, _embedpdf_core.createCapabilityToken)("interaction");
146
+ /**
147
+ * Resolve a sample against a gesture's HOME page. Page-anchored gestures track
148
+ * the page they started on even when the cursor wanders off it — `s.page`
149
+ * re-resolves per event (a foreign page is a DIFFERENT coordinate frame), so
150
+ * prefer the source's unclamped projection and fall back to the page hit only
151
+ * when it is the same page. Null → this sample can't speak for the home page.
152
+ * Shared by every gesture owner (annotation edit/draw, form placement).
153
+ */
154
+ const samplePointOn = (s, pon) => s.project?.(pon) ?? (s.page?.pon === pon ? s.page.point : null);
155
+ //#endregion
156
+ //#region src/interaction.plugin.ts
157
+ /**
158
+ * The two built-in tools. Features ADD tools via `registerTool` (a draw tool, a
159
+ * redact tool…). `enables` is the composition seam:
160
+ * pointer → text selection + annotation editing + annotation marquee selection
161
+ * pan → scrolling (contributed by Stage) + annotation editing, NO text select
162
+ *
163
+ * Both carry `form-fill`: filling a form is the RESTING state of a viewer
164
+ * (Acrobat's hand tool fills forms too), so widgets are fill-controls under the
165
+ * default tools and only become geometry-editable under a form-design tool.
166
+ * Both carry `link-nav` for the same reason: links navigate under the default
167
+ * tools (Acrobat behaviour) and only become geometry-editable under the link
168
+ * tool. Tags are opaque to the hub — without the form/link plugins they're inert.
169
+ */
170
+ const builtinTools = () => [{
171
+ id: "pointer",
172
+ cursor: "default",
173
+ enables: /* @__PURE__ */ new Set([
174
+ "text-select",
175
+ "annotation-edit",
176
+ "annotation-marquee",
177
+ "form-fill",
178
+ "link-nav"
179
+ ])
180
+ }, {
181
+ id: "pan",
182
+ cursor: "grab",
183
+ gapCursor: "grab",
184
+ enables: /* @__PURE__ */ new Set([
185
+ "scroll",
186
+ "annotation-edit",
187
+ "form-fill",
188
+ "link-nav"
189
+ ])
190
+ }];
191
+ /**
192
+ * The interaction hub plugin — document-scoped, depends on nothing. Every feature
193
+ * plugin (selection, annotation, forms, redaction) `requires` this token; Stage
194
+ * `optional`-ly contributes a scroll handler. Works with `<Stage>` or a standalone
195
+ * `<PageView>` — it only routes page-space pointer samples.
196
+ */
197
+ const interactionPlugin = (config = {}) => (0, _embedpdf_core.definePlugin)({
198
+ id: "interaction",
199
+ token: InteractionToken,
200
+ scope: "document",
201
+ initialState: () => initialInteractionState(config),
202
+ reduce: interactionReducer,
203
+ capability: (ctx) => createInteractionCapability(ctx, builtinTools())
204
+ });
205
+ //#endregion
206
+ exports.InteractionToken = InteractionToken;
207
+ exports.builtinTools = builtinTools;
208
+ exports.createInteractionCapability = createInteractionCapability;
209
+ exports.initialInteractionState = initialInteractionState;
210
+ exports.interactionPlugin = interactionPlugin;
211
+ exports.interactionReducer = interactionReducer;
212
+ exports.samplePointOn = samplePointOn;
213
+
214
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/capability.ts","../src/reducer.ts","../src/types.ts","../src/interaction.plugin.ts"],"sourcesContent":["import type { PluginContext } from '@embedpdf/core';\nimport type {\n Cursor,\n InteractionAction,\n InteractionCapability,\n InteractionHandler,\n InteractionState,\n Tool,\n ToolCursorSkin,\n ToolId,\n} from './types';\n\ninterface Claim {\n cursor: Cursor;\n priority: number;\n}\n\n/**\n * The interaction hub. Tools + handlers + the captured-gesture owner + cursor\n * claims live in this closure (runtime registries, not serializable state); the\n * reducer state holds only the active tool id and the resolved cursor, so the UI\n * can react to them. The router (`dispatch`) is the heart: on down, the first\n * eligible handler (by priority) to return true OWNS the gesture; move/up route\n * to it; with no owner, move is hover (cursor feedback).\n *\n * Cursor arbitration, top to bottom: the highest-priority CLAIM (hover feedback\n * — 'move' over an annotation, 'text' over text) → over a page, the tool's\n * declared cursor → over a gap, the tool's `gapCursor` (default the neutral\n * arrow). The winning KEYWORD (claim or base, never gap) is then restyled\n * through the armed tool's skin when it maps that keyword. One resolver, so an\n * image cursor can never shadow hover feedback or outlive the page under the\n * pointer.\n */\nexport function createInteractionCapability(\n ctx: PluginContext<InteractionState, InteractionAction>,\n builtinTools: Tool[],\n): InteractionCapability {\n const tools = new Map<ToolId, Tool>();\n for (const t of builtinTools) tools.set(t.id, t);\n const handlers: InteractionHandler[] = [];\n const claims = new Map<string, Claim>();\n const cursorSkins = new Map<ToolId, ToolCursorSkin>();\n const toolCbs = new Set<() => void>();\n let owner: InteractionHandler | null = null;\n // Whether the last dispatched sample hit a page — the base cursor only\n // applies where the tool can act; over gaps it falls back to `gapCursor`.\n let overPage = false;\n\n const toolOf = (id: ToolId): Tool =>\n tools.get(id) ?? { id, cursor: 'default', enables: new Set() };\n const active = (): Tool => toolOf(ctx.getState().activeToolId);\n\n const resolveCursor = (): Cursor => {\n let top: Claim | null = null;\n for (const c of claims.values()) if (!top || c.priority > top.priority) top = c;\n const tool = active();\n const skin = cursorSkins.get(tool.id);\n // The cursor keeps its MEANING (a keyword — the winning claim's, else the\n // tool's declared base); the skin may restyle that keyword in the armed\n // tool's identity (an I-beam + tool icon over text). Unmapped keywords\n // render as-is — a foreign affordance drops the tool identity — and gaps\n // resolve before the skin: identity only where the action is possible.\n if (top) return skin?.[top.cursor] ?? top.cursor;\n if (!overPage) return tool.gapCursor ?? 'default';\n return skin?.[tool.cursor] ?? tool.cursor;\n };\n const syncCursor = (): void => {\n const next = resolveCursor();\n if (next !== ctx.getState().cursor) ctx.dispatch({ type: 'SET_CURSOR', cursor: next });\n };\n\n const eligible = (): InteractionHandler[] => {\n const tool = active();\n return handlers.filter((h) => h.enabledFor(tool)).sort((a, b) => b.priority - a.priority);\n };\n\n return {\n activeTool: active,\n activeToolId: () => ctx.getState().activeToolId,\n cursor: () => ctx.getState().cursor,\n tools: () => [...tools.values()],\n\n activateTool: (id) => {\n if (!tools.has(id)) throw new Error(`[interaction] unknown tool '${id}'`);\n owner = null;\n claims.clear(); // drop the previous tool's hover claims; handlers re-claim on next hover\n ctx.dispatch({ type: 'SET_TOOL', toolId: id });\n syncCursor();\n toolCbs.forEach((cb) => cb());\n },\n\n onToolChange: (cb) => {\n toolCbs.add(cb);\n return () => toolCbs.delete(cb);\n },\n\n registerTool: (tool) => {\n tools.set(tool.id, tool);\n return () => {\n tools.delete(tool.id);\n cursorSkins.delete(tool.id);\n };\n },\n\n setToolCursor: (id, skin) => {\n if (skin === null) cursorSkins.delete(id);\n else cursorSkins.set(id, skin);\n syncCursor();\n },\n\n registerHandler: (handler) => {\n handlers.push(handler);\n return () => {\n const i = handlers.indexOf(handler);\n if (i >= 0) handlers.splice(i, 1);\n if (owner === handler) owner = null;\n };\n },\n\n setCursor: (token, cursor, priority = 0) => {\n if (cursor === null) claims.delete(token);\n else claims.set(token, { cursor, priority });\n syncCursor();\n },\n\n dispatch: (sample) => {\n const nowOverPage = sample.page != null;\n if (nowOverPage !== overPage) {\n overPage = nowOverPage;\n syncCursor(); // crossing a page edge re-resolves the base cursor\n }\n if (sample.phase === 'down') {\n owner = null;\n for (const h of eligible()) {\n if (h.onDown(sample)) {\n owner = h;\n break;\n }\n }\n } else if (sample.phase === 'move') {\n if (owner) owner.onMove?.(sample);\n else for (const h of eligible()) h.onHover?.(sample);\n } else {\n owner?.onUp?.(sample);\n owner = null;\n }\n },\n };\n}\n","import type { InteractionAction, InteractionConfig, InteractionState } from './types';\n\nexport const initialInteractionState = (config: InteractionConfig): InteractionState => ({\n activeToolId: config.defaultTool ?? 'pointer',\n cursor: 'default',\n});\n\nexport const interactionReducer = (\n state: InteractionState,\n action: InteractionAction,\n): InteractionState => {\n switch (action.type) {\n case 'SET_TOOL':\n return state.activeToolId === action.toolId\n ? state\n : { ...state, activeToolId: action.toolId };\n case 'SET_CURSOR':\n return state.cursor === action.cursor ? state : { ...state, cursor: action.cursor };\n default:\n return state;\n }\n};\n","import { createCapabilityToken, type PageObjectNumber } from '@embedpdf/core';\nimport type { PageRotation, Point } from '@embedpdf/core-geometry';\n\nexport type ToolId = string;\nexport type Cursor = string;\n\nexport interface Modifiers {\n shift: boolean;\n alt: boolean;\n ctrl: boolean;\n meta: boolean;\n}\n\n/**\n * The single active arbiter of what the pointer does. `pan` and `pointer` are\n * built in; features add more (`highlight`, `square`, `redact`…) via\n * `registerTool`. A tool carries no behaviour itself — it turns on capability\n * TAGS that handlers opt into (`enables`), so tools compose features without\n * coupling to them.\n */\nexport interface Tool {\n id: ToolId;\n cursor: Cursor;\n /**\n * Cursor over the viewport's page GAPS. A tool's cursor answers \"what would\n * a click do here\" — and most tools act only on pages, so gaps fall back to\n * the neutral arrow (`'default'`). A tool that works anywhere (pan) declares\n * its own (`'grab'`). Hover claims still outrank both.\n */\n gapCursor?: Cursor;\n enables: ReadonlySet<string>;\n}\n\nexport type Phase = 'down' | 'move' | 'up';\n\n/**\n * One normalized pointer event. `viewport` is the source container's px (the pan\n * handler uses the delta). `page` is the resolved page hit — its `pon` + content\n * point (y-down, PDF units, via the page's transform) — present when the pointer\n * is over a page, absent over gaps. A viewport source (Stage) resolves `page` per\n * event (so a drag can cross pages); a per-page source (PageView) always sets it.\n */\nexport interface PointerSample {\n phase: Phase;\n viewport: Point;\n /** `scale` is the hit page's VIEW px per content unit — handlers use it to\n * convert screen-px chrome settings into content-space tolerances, so grab\n * zones stay screen-constant across zoom. `rotation` is the hit page's TOTAL\n * display rotation (document /Rotate + view rotation) — per-event\n * environmental context like `scale`, for placement rules that depend on how\n * the page is DISPLAYED (an upright stamp). `zoom` is the page's zoom\n * RELATIVE to its 100% baseline (`transform.zoom` — dimensionless, 1 =\n * Acrobat's 100%), for zoom-relative policies (the `/F` NoZoom exemption);\n * distinct from `scale`, which is a units conversion. Absent when the\n * source can't say. */\n page?: {\n pon: PageObjectNumber;\n point: Point;\n scale?: number;\n rotation?: PageRotation;\n zoom?: number;\n };\n modifiers: Modifiers;\n /**\n * Click count for a `down` (1 = single, 2 = double, 3 = triple), from the\n * browser's native multi-click detection (`MouseEvent.detail`). Lets handlers\n * do word/line selection without re-implementing timing. Defaults to 1.\n */\n clickCount?: number;\n /**\n * Project this event onto a SPECIFIC page's content space, unclamped — valid\n * (and expected) outside the page's bounds. `page` answers \"what is under the\n * cursor\" and re-resolves per event; `project` answers \"where is the cursor\n * in MY page's frame\" for a gesture anchored to the page it started on (an\n * annotation drag sliding along the page edge). Null when the source can't\n * project onto that page (not laid out / a per-page source's foreign page).\n */\n project?(pon: PageObjectNumber): Point | null;\n}\n\n/**\n * A pointer handler contributed by a feature plugin. The ONE registration\n * mechanism (replacing v2's registerMode / registerHandlers / registerAlways /\n * enableForMode quartet): a handler declares which tools it's live under and a\n * priority; the hub routes each gesture to the first handler that captures it.\n */\nexport interface InteractionHandler {\n id: string;\n /** Higher wins the gesture. */\n priority: number;\n /** Usually `tool.enables.has('my-tag')`. */\n enabledFor(tool: Tool): boolean;\n /** Return true to CAPTURE: subsequent move/up route here until pointer-up. */\n onDown(sample: PointerSample): boolean;\n onMove?(sample: PointerSample): void;\n onUp?(sample: PointerSample): void;\n /** Pointer moved with no active gesture — cursor feedback only. */\n onHover?(sample: PointerSample): void;\n}\n\n/**\n * A tool's runtime cursor skin: \"while THIS tool is armed, keyword X looks\n * like Y.\" Everything cursor-shaped in the hub speaks KEYWORDS — a tool\n * declares its base ('crosshair', 'copy'), hover claims name what is under\n * the pointer ('text' over text, 'move' over an annotation) — and the skin\n * restyles those keywords, typically as image cursors carrying the tool's\n * icon. Applied uniformly to the winning claim and to the declared base, so\n * same keyword = same meaning = same look. Unmapped keywords render as-is (a\n * foreign 'move' over an annotation drops the tool identity), and page gaps\n * are never skinned — the identity appears exactly where the action is\n * possible, and the skin can only restyle where the tool already acts.\n */\nexport type ToolCursorSkin = Record<Cursor, Cursor>;\n\nexport interface InteractionState {\n activeToolId: ToolId;\n cursor: Cursor;\n}\n\nexport type InteractionAction =\n | { type: 'SET_TOOL'; toolId: ToolId }\n | { type: 'SET_CURSOR'; cursor: Cursor };\n\nexport interface InteractionCapability {\n // ── selectors ──\n activeTool(): Tool;\n activeToolId(): ToolId;\n cursor(): Cursor;\n tools(): Tool[];\n // ── tool intents ──\n activateTool(id: ToolId): void;\n /** Fires after the active tool changes — lets a feature react (e.g. a markup\n * tool taking over the selection visual). Returns an unsubscribe fn. */\n onToolChange(cb: () => void): () => void;\n /**\n * Reskin a tool's cursor keywords at runtime — how an app gives the armed\n * tool an image cursor built from its own toolbar icon (`Cursor` is any CSS\n * cursor string, `url(data:…) x y, crosshair` included). See\n * {@link ToolCursorSkin} for what the map means. `null` removes the skin.\n */\n setToolCursor(id: ToolId, skin: ToolCursorSkin | null): void;\n // ── registries (return an unregister fn) ──\n registerTool(tool: Tool): () => void;\n registerHandler(handler: InteractionHandler): () => void;\n // ── cursor claim stack (highest priority wins; null clears the token) ──\n setCursor(token: string, cursor: Cursor | null, priority?: number): void;\n // ── pointer ingress: the adapter calls this for every normalized event ──\n dispatch(sample: PointerSample): void;\n}\n\nexport const InteractionToken = createCapabilityToken<InteractionCapability>('interaction');\n\n/**\n * Resolve a sample against a gesture's HOME page. Page-anchored gestures track\n * the page they started on even when the cursor wanders off it — `s.page`\n * re-resolves per event (a foreign page is a DIFFERENT coordinate frame), so\n * prefer the source's unclamped projection and fall back to the page hit only\n * when it is the same page. Null → this sample can't speak for the home page.\n * Shared by every gesture owner (annotation edit/draw, form placement).\n */\nexport const samplePointOn = (s: PointerSample, pon: PageObjectNumber): Point | null =>\n s.project?.(pon) ?? (s.page?.pon === pon ? s.page.point : null);\n\nexport interface InteractionConfig {\n /** Tool active when a document opens. Default `'pointer'`. */\n defaultTool?: ToolId;\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { createInteractionCapability } from './capability';\nimport { initialInteractionState, interactionReducer } from './reducer';\nimport { InteractionToken } from './types';\nimport type {\n InteractionAction,\n InteractionCapability,\n InteractionConfig,\n InteractionState,\n Tool,\n} from './types';\n\n/**\n * The two built-in tools. Features ADD tools via `registerTool` (a draw tool, a\n * redact tool…). `enables` is the composition seam:\n * pointer → text selection + annotation editing + annotation marquee selection\n * pan → scrolling (contributed by Stage) + annotation editing, NO text select\n *\n * Both carry `form-fill`: filling a form is the RESTING state of a viewer\n * (Acrobat's hand tool fills forms too), so widgets are fill-controls under the\n * default tools and only become geometry-editable under a form-design tool.\n * Both carry `link-nav` for the same reason: links navigate under the default\n * tools (Acrobat behaviour) and only become geometry-editable under the link\n * tool. Tags are opaque to the hub — without the form/link plugins they're inert.\n */\nexport const builtinTools = (): Tool[] => [\n {\n id: 'pointer',\n cursor: 'default',\n enables: new Set([\n 'text-select',\n 'annotation-edit',\n 'annotation-marquee',\n 'form-fill',\n 'link-nav',\n ]),\n },\n {\n id: 'pan',\n cursor: 'grab',\n gapCursor: 'grab', // pan works anywhere — the open hand doesn't stop at page edges\n enables: new Set(['scroll', 'annotation-edit', 'form-fill', 'link-nav']),\n },\n];\n\n/**\n * The interaction hub plugin — document-scoped, depends on nothing. Every feature\n * plugin (selection, annotation, forms, redaction) `requires` this token; Stage\n * `optional`-ly contributes a scroll handler. Works with `<Stage>` or a standalone\n * `<PageView>` — it only routes page-space pointer samples.\n */\nexport const interactionPlugin = (config: InteractionConfig = {}) =>\n definePlugin<InteractionState, InteractionAction, InteractionCapability>({\n id: 'interaction',\n token: InteractionToken,\n scope: 'document',\n initialState: () => initialInteractionState(config),\n reduce: interactionReducer,\n capability: (ctx) => createInteractionCapability(ctx, builtinTools()),\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAi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SAAS,GAAG,EAAE,UAAU,MAAM;QAC9C;IACL,OAAO,OAAO,MAAM;IACpB,QAAQ;GACV;EACF;CACF;AACF;;;AClJA,MAAa,2BAA2B,YAAiD;CACvF,cAAc,OAAO,eAAe;CACpC,QAAQ;AACV;AAEA,MAAa,sBACX,OACA,WACqB;CACrB,QAAQ,OAAO,MAAf;EACE,KAAK,YACH,OAAO,MAAM,iBAAiB,OAAO,SACjC,QACA;GAAE,GAAG;GAAO,cAAc,OAAO;EAAO;EAC9C,KAAK,cACH,OAAO,MAAM,WAAW,OAAO,SAAS,QAAQ;GAAE,GAAG;GAAO,QAAQ,OAAO;EAAO;EACpF,SACE,OAAO;CACX;AACF;;;ACiIA,MAAa,oBAAA,GAAA,eAAA,sBAAA,CAAgE,aAAa;;;;;;;;;AAU1F,MAAa,iBAAiB,GAAkB,QAC9C,EAAE,UAAU,GAAG,MAAM,EAAE,MAAM,QAAQ,MAAM,EAAE,KAAK,QAAQ;;;;;;;;;;;;;;;;ACxI5D,MAAa,qBAA6B,CACxC;CACE,IAAI;CACJ,QAAQ;CACR,yBAAS,IAAI,IAAI;EACf;EACA;EACA;EACA;EACA;CACF,CAAC;AACH,GACA;CACE,IAAI;CACJ,QAAQ;CACR,WAAW;CACX,yBAAS,IAAI,IAAI;EAAC;EAAU;EAAmB;EAAa;CAAU,CAAC;AACzE,CACF;;;;;;;AAQA,MAAa,qBAAqB,SAA4B,CAAC,OAAA,GAAA,eAAA,aAAA,CACY;CACvE,IAAI;CACJ,OAAO;CACP,OAAO;CACP,oBAAoB,wBAAwB,MAAM;CAClD,QAAQ;CACR,aAAa,QAAQ,4BAA4B,KAAK,aAAa,CAAC;AACtE,CAAC"}
@@ -0,0 +1,202 @@
1
+ import { PageObjectNumber, PluginContext } from "@embedpdf/core";
2
+ import { PageRotation, Point } from "@embedpdf/core-geometry";
3
+ //#region src/types.d.ts
4
+ type ToolId = string;
5
+ type Cursor = string;
6
+ interface Modifiers {
7
+ shift: boolean;
8
+ alt: boolean;
9
+ ctrl: boolean;
10
+ meta: boolean;
11
+ }
12
+ /**
13
+ * The single active arbiter of what the pointer does. `pan` and `pointer` are
14
+ * built in; features add more (`highlight`, `square`, `redact`…) via
15
+ * `registerTool`. A tool carries no behaviour itself — it turns on capability
16
+ * TAGS that handlers opt into (`enables`), so tools compose features without
17
+ * coupling to them.
18
+ */
19
+ interface Tool {
20
+ id: ToolId;
21
+ cursor: Cursor;
22
+ /**
23
+ * Cursor over the viewport's page GAPS. A tool's cursor answers "what would
24
+ * a click do here" — and most tools act only on pages, so gaps fall back to
25
+ * the neutral arrow (`'default'`). A tool that works anywhere (pan) declares
26
+ * its own (`'grab'`). Hover claims still outrank both.
27
+ */
28
+ gapCursor?: Cursor;
29
+ enables: ReadonlySet<string>;
30
+ }
31
+ type Phase = 'down' | 'move' | 'up';
32
+ /**
33
+ * One normalized pointer event. `viewport` is the source container's px (the pan
34
+ * handler uses the delta). `page` is the resolved page hit — its `pon` + content
35
+ * point (y-down, PDF units, via the page's transform) — present when the pointer
36
+ * is over a page, absent over gaps. A viewport source (Stage) resolves `page` per
37
+ * event (so a drag can cross pages); a per-page source (PageView) always sets it.
38
+ */
39
+ interface PointerSample {
40
+ phase: Phase;
41
+ viewport: Point;
42
+ /** `scale` is the hit page's VIEW px per content unit — handlers use it to
43
+ * convert screen-px chrome settings into content-space tolerances, so grab
44
+ * zones stay screen-constant across zoom. `rotation` is the hit page's TOTAL
45
+ * display rotation (document /Rotate + view rotation) — per-event
46
+ * environmental context like `scale`, for placement rules that depend on how
47
+ * the page is DISPLAYED (an upright stamp). `zoom` is the page's zoom
48
+ * RELATIVE to its 100% baseline (`transform.zoom` — dimensionless, 1 =
49
+ * Acrobat's 100%), for zoom-relative policies (the `/F` NoZoom exemption);
50
+ * distinct from `scale`, which is a units conversion. Absent when the
51
+ * source can't say. */
52
+ page?: {
53
+ pon: PageObjectNumber;
54
+ point: Point;
55
+ scale?: number;
56
+ rotation?: PageRotation;
57
+ zoom?: number;
58
+ };
59
+ modifiers: Modifiers;
60
+ /**
61
+ * Click count for a `down` (1 = single, 2 = double, 3 = triple), from the
62
+ * browser's native multi-click detection (`MouseEvent.detail`). Lets handlers
63
+ * do word/line selection without re-implementing timing. Defaults to 1.
64
+ */
65
+ clickCount?: number;
66
+ /**
67
+ * Project this event onto a SPECIFIC page's content space, unclamped — valid
68
+ * (and expected) outside the page's bounds. `page` answers "what is under the
69
+ * cursor" and re-resolves per event; `project` answers "where is the cursor
70
+ * in MY page's frame" for a gesture anchored to the page it started on (an
71
+ * annotation drag sliding along the page edge). Null when the source can't
72
+ * project onto that page (not laid out / a per-page source's foreign page).
73
+ */
74
+ project?(pon: PageObjectNumber): Point | null;
75
+ }
76
+ /**
77
+ * A pointer handler contributed by a feature plugin. The ONE registration
78
+ * mechanism (replacing v2's registerMode / registerHandlers / registerAlways /
79
+ * enableForMode quartet): a handler declares which tools it's live under and a
80
+ * priority; the hub routes each gesture to the first handler that captures it.
81
+ */
82
+ interface InteractionHandler {
83
+ id: string;
84
+ /** Higher wins the gesture. */
85
+ priority: number;
86
+ /** Usually `tool.enables.has('my-tag')`. */
87
+ enabledFor(tool: Tool): boolean;
88
+ /** Return true to CAPTURE: subsequent move/up route here until pointer-up. */
89
+ onDown(sample: PointerSample): boolean;
90
+ onMove?(sample: PointerSample): void;
91
+ onUp?(sample: PointerSample): void;
92
+ /** Pointer moved with no active gesture — cursor feedback only. */
93
+ onHover?(sample: PointerSample): void;
94
+ }
95
+ /**
96
+ * A tool's runtime cursor skin: "while THIS tool is armed, keyword X looks
97
+ * like Y." Everything cursor-shaped in the hub speaks KEYWORDS — a tool
98
+ * declares its base ('crosshair', 'copy'), hover claims name what is under
99
+ * the pointer ('text' over text, 'move' over an annotation) — and the skin
100
+ * restyles those keywords, typically as image cursors carrying the tool's
101
+ * icon. Applied uniformly to the winning claim and to the declared base, so
102
+ * same keyword = same meaning = same look. Unmapped keywords render as-is (a
103
+ * foreign 'move' over an annotation drops the tool identity), and page gaps
104
+ * are never skinned — the identity appears exactly where the action is
105
+ * possible, and the skin can only restyle where the tool already acts.
106
+ */
107
+ type ToolCursorSkin = Record<Cursor, Cursor>;
108
+ interface InteractionState {
109
+ activeToolId: ToolId;
110
+ cursor: Cursor;
111
+ }
112
+ type InteractionAction = {
113
+ type: 'SET_TOOL';
114
+ toolId: ToolId;
115
+ } | {
116
+ type: 'SET_CURSOR';
117
+ cursor: Cursor;
118
+ };
119
+ interface InteractionCapability {
120
+ activeTool(): Tool;
121
+ activeToolId(): ToolId;
122
+ cursor(): Cursor;
123
+ tools(): Tool[];
124
+ activateTool(id: ToolId): void;
125
+ /** Fires after the active tool changes — lets a feature react (e.g. a markup
126
+ * tool taking over the selection visual). Returns an unsubscribe fn. */
127
+ onToolChange(cb: () => void): () => void;
128
+ /**
129
+ * Reskin a tool's cursor keywords at runtime — how an app gives the armed
130
+ * tool an image cursor built from its own toolbar icon (`Cursor` is any CSS
131
+ * cursor string, `url(data:…) x y, crosshair` included). See
132
+ * {@link ToolCursorSkin} for what the map means. `null` removes the skin.
133
+ */
134
+ setToolCursor(id: ToolId, skin: ToolCursorSkin | null): void;
135
+ registerTool(tool: Tool): () => void;
136
+ registerHandler(handler: InteractionHandler): () => void;
137
+ setCursor(token: string, cursor: Cursor | null, priority?: number): void;
138
+ dispatch(sample: PointerSample): void;
139
+ }
140
+ declare const InteractionToken: import("@embedpdf/core").CapabilityToken<InteractionCapability>;
141
+ /**
142
+ * Resolve a sample against a gesture's HOME page. Page-anchored gestures track
143
+ * the page they started on even when the cursor wanders off it — `s.page`
144
+ * re-resolves per event (a foreign page is a DIFFERENT coordinate frame), so
145
+ * prefer the source's unclamped projection and fall back to the page hit only
146
+ * when it is the same page. Null → this sample can't speak for the home page.
147
+ * Shared by every gesture owner (annotation edit/draw, form placement).
148
+ */
149
+ declare const samplePointOn: (s: PointerSample, pon: PageObjectNumber) => Point | null;
150
+ interface InteractionConfig {
151
+ /** Tool active when a document opens. Default `'pointer'`. */
152
+ defaultTool?: ToolId;
153
+ }
154
+ //#endregion
155
+ //#region src/interaction.plugin.d.ts
156
+ /**
157
+ * The two built-in tools. Features ADD tools via `registerTool` (a draw tool, a
158
+ * redact tool…). `enables` is the composition seam:
159
+ * pointer → text selection + annotation editing + annotation marquee selection
160
+ * pan → scrolling (contributed by Stage) + annotation editing, NO text select
161
+ *
162
+ * Both carry `form-fill`: filling a form is the RESTING state of a viewer
163
+ * (Acrobat's hand tool fills forms too), so widgets are fill-controls under the
164
+ * default tools and only become geometry-editable under a form-design tool.
165
+ * Both carry `link-nav` for the same reason: links navigate under the default
166
+ * tools (Acrobat behaviour) and only become geometry-editable under the link
167
+ * tool. Tags are opaque to the hub — without the form/link plugins they're inert.
168
+ */
169
+ declare const builtinTools: () => Tool[];
170
+ /**
171
+ * The interaction hub plugin — document-scoped, depends on nothing. Every feature
172
+ * plugin (selection, annotation, forms, redaction) `requires` this token; Stage
173
+ * `optional`-ly contributes a scroll handler. Works with `<Stage>` or a standalone
174
+ * `<PageView>` — it only routes page-space pointer samples.
175
+ */
176
+ declare const interactionPlugin: (config?: InteractionConfig) => import("@embedpdf/core").PluginDef<InteractionState, InteractionAction, InteractionCapability>;
177
+ //#endregion
178
+ //#region src/capability.d.ts
179
+ /**
180
+ * The interaction hub. Tools + handlers + the captured-gesture owner + cursor
181
+ * claims live in this closure (runtime registries, not serializable state); the
182
+ * reducer state holds only the active tool id and the resolved cursor, so the UI
183
+ * can react to them. The router (`dispatch`) is the heart: on down, the first
184
+ * eligible handler (by priority) to return true OWNS the gesture; move/up route
185
+ * to it; with no owner, move is hover (cursor feedback).
186
+ *
187
+ * Cursor arbitration, top to bottom: the highest-priority CLAIM (hover feedback
188
+ * — 'move' over an annotation, 'text' over text) → over a page, the tool's
189
+ * declared cursor → over a gap, the tool's `gapCursor` (default the neutral
190
+ * arrow). The winning KEYWORD (claim or base, never gap) is then restyled
191
+ * through the armed tool's skin when it maps that keyword. One resolver, so an
192
+ * image cursor can never shadow hover feedback or outlive the page under the
193
+ * pointer.
194
+ */
195
+ declare function createInteractionCapability(ctx: PluginContext<InteractionState, InteractionAction>, builtinTools: Tool[]): InteractionCapability;
196
+ //#endregion
197
+ //#region src/reducer.d.ts
198
+ declare const initialInteractionState: (config: InteractionConfig) => InteractionState;
199
+ declare const interactionReducer: (state: InteractionState, action: InteractionAction) => InteractionState;
200
+ //#endregion
201
+ export { type Cursor, type InteractionAction, type InteractionCapability, type InteractionConfig, type InteractionHandler, type InteractionState, InteractionToken, type Modifiers, type Phase, type PointerSample, type Tool, type ToolId, builtinTools, createInteractionCapability, initialInteractionState, interactionPlugin, interactionReducer, samplePointOn };
202
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1,202 @@
1
+ import { PageObjectNumber, PluginContext } from "@embedpdf/core";
2
+ import { PageRotation, Point } from "@embedpdf/core-geometry";
3
+ //#region src/types.d.ts
4
+ type ToolId = string;
5
+ type Cursor = string;
6
+ interface Modifiers {
7
+ shift: boolean;
8
+ alt: boolean;
9
+ ctrl: boolean;
10
+ meta: boolean;
11
+ }
12
+ /**
13
+ * The single active arbiter of what the pointer does. `pan` and `pointer` are
14
+ * built in; features add more (`highlight`, `square`, `redact`…) via
15
+ * `registerTool`. A tool carries no behaviour itself — it turns on capability
16
+ * TAGS that handlers opt into (`enables`), so tools compose features without
17
+ * coupling to them.
18
+ */
19
+ interface Tool {
20
+ id: ToolId;
21
+ cursor: Cursor;
22
+ /**
23
+ * Cursor over the viewport's page GAPS. A tool's cursor answers "what would
24
+ * a click do here" — and most tools act only on pages, so gaps fall back to
25
+ * the neutral arrow (`'default'`). A tool that works anywhere (pan) declares
26
+ * its own (`'grab'`). Hover claims still outrank both.
27
+ */
28
+ gapCursor?: Cursor;
29
+ enables: ReadonlySet<string>;
30
+ }
31
+ type Phase = 'down' | 'move' | 'up';
32
+ /**
33
+ * One normalized pointer event. `viewport` is the source container's px (the pan
34
+ * handler uses the delta). `page` is the resolved page hit — its `pon` + content
35
+ * point (y-down, PDF units, via the page's transform) — present when the pointer
36
+ * is over a page, absent over gaps. A viewport source (Stage) resolves `page` per
37
+ * event (so a drag can cross pages); a per-page source (PageView) always sets it.
38
+ */
39
+ interface PointerSample {
40
+ phase: Phase;
41
+ viewport: Point;
42
+ /** `scale` is the hit page's VIEW px per content unit — handlers use it to
43
+ * convert screen-px chrome settings into content-space tolerances, so grab
44
+ * zones stay screen-constant across zoom. `rotation` is the hit page's TOTAL
45
+ * display rotation (document /Rotate + view rotation) — per-event
46
+ * environmental context like `scale`, for placement rules that depend on how
47
+ * the page is DISPLAYED (an upright stamp). `zoom` is the page's zoom
48
+ * RELATIVE to its 100% baseline (`transform.zoom` — dimensionless, 1 =
49
+ * Acrobat's 100%), for zoom-relative policies (the `/F` NoZoom exemption);
50
+ * distinct from `scale`, which is a units conversion. Absent when the
51
+ * source can't say. */
52
+ page?: {
53
+ pon: PageObjectNumber;
54
+ point: Point;
55
+ scale?: number;
56
+ rotation?: PageRotation;
57
+ zoom?: number;
58
+ };
59
+ modifiers: Modifiers;
60
+ /**
61
+ * Click count for a `down` (1 = single, 2 = double, 3 = triple), from the
62
+ * browser's native multi-click detection (`MouseEvent.detail`). Lets handlers
63
+ * do word/line selection without re-implementing timing. Defaults to 1.
64
+ */
65
+ clickCount?: number;
66
+ /**
67
+ * Project this event onto a SPECIFIC page's content space, unclamped — valid
68
+ * (and expected) outside the page's bounds. `page` answers "what is under the
69
+ * cursor" and re-resolves per event; `project` answers "where is the cursor
70
+ * in MY page's frame" for a gesture anchored to the page it started on (an
71
+ * annotation drag sliding along the page edge). Null when the source can't
72
+ * project onto that page (not laid out / a per-page source's foreign page).
73
+ */
74
+ project?(pon: PageObjectNumber): Point | null;
75
+ }
76
+ /**
77
+ * A pointer handler contributed by a feature plugin. The ONE registration
78
+ * mechanism (replacing v2's registerMode / registerHandlers / registerAlways /
79
+ * enableForMode quartet): a handler declares which tools it's live under and a
80
+ * priority; the hub routes each gesture to the first handler that captures it.
81
+ */
82
+ interface InteractionHandler {
83
+ id: string;
84
+ /** Higher wins the gesture. */
85
+ priority: number;
86
+ /** Usually `tool.enables.has('my-tag')`. */
87
+ enabledFor(tool: Tool): boolean;
88
+ /** Return true to CAPTURE: subsequent move/up route here until pointer-up. */
89
+ onDown(sample: PointerSample): boolean;
90
+ onMove?(sample: PointerSample): void;
91
+ onUp?(sample: PointerSample): void;
92
+ /** Pointer moved with no active gesture — cursor feedback only. */
93
+ onHover?(sample: PointerSample): void;
94
+ }
95
+ /**
96
+ * A tool's runtime cursor skin: "while THIS tool is armed, keyword X looks
97
+ * like Y." Everything cursor-shaped in the hub speaks KEYWORDS — a tool
98
+ * declares its base ('crosshair', 'copy'), hover claims name what is under
99
+ * the pointer ('text' over text, 'move' over an annotation) — and the skin
100
+ * restyles those keywords, typically as image cursors carrying the tool's
101
+ * icon. Applied uniformly to the winning claim and to the declared base, so
102
+ * same keyword = same meaning = same look. Unmapped keywords render as-is (a
103
+ * foreign 'move' over an annotation drops the tool identity), and page gaps
104
+ * are never skinned — the identity appears exactly where the action is
105
+ * possible, and the skin can only restyle where the tool already acts.
106
+ */
107
+ type ToolCursorSkin = Record<Cursor, Cursor>;
108
+ interface InteractionState {
109
+ activeToolId: ToolId;
110
+ cursor: Cursor;
111
+ }
112
+ type InteractionAction = {
113
+ type: 'SET_TOOL';
114
+ toolId: ToolId;
115
+ } | {
116
+ type: 'SET_CURSOR';
117
+ cursor: Cursor;
118
+ };
119
+ interface InteractionCapability {
120
+ activeTool(): Tool;
121
+ activeToolId(): ToolId;
122
+ cursor(): Cursor;
123
+ tools(): Tool[];
124
+ activateTool(id: ToolId): void;
125
+ /** Fires after the active tool changes — lets a feature react (e.g. a markup
126
+ * tool taking over the selection visual). Returns an unsubscribe fn. */
127
+ onToolChange(cb: () => void): () => void;
128
+ /**
129
+ * Reskin a tool's cursor keywords at runtime — how an app gives the armed
130
+ * tool an image cursor built from its own toolbar icon (`Cursor` is any CSS
131
+ * cursor string, `url(data:…) x y, crosshair` included). See
132
+ * {@link ToolCursorSkin} for what the map means. `null` removes the skin.
133
+ */
134
+ setToolCursor(id: ToolId, skin: ToolCursorSkin | null): void;
135
+ registerTool(tool: Tool): () => void;
136
+ registerHandler(handler: InteractionHandler): () => void;
137
+ setCursor(token: string, cursor: Cursor | null, priority?: number): void;
138
+ dispatch(sample: PointerSample): void;
139
+ }
140
+ declare const InteractionToken: import("@embedpdf/core").CapabilityToken<InteractionCapability>;
141
+ /**
142
+ * Resolve a sample against a gesture's HOME page. Page-anchored gestures track
143
+ * the page they started on even when the cursor wanders off it — `s.page`
144
+ * re-resolves per event (a foreign page is a DIFFERENT coordinate frame), so
145
+ * prefer the source's unclamped projection and fall back to the page hit only
146
+ * when it is the same page. Null → this sample can't speak for the home page.
147
+ * Shared by every gesture owner (annotation edit/draw, form placement).
148
+ */
149
+ declare const samplePointOn: (s: PointerSample, pon: PageObjectNumber) => Point | null;
150
+ interface InteractionConfig {
151
+ /** Tool active when a document opens. Default `'pointer'`. */
152
+ defaultTool?: ToolId;
153
+ }
154
+ //#endregion
155
+ //#region src/interaction.plugin.d.ts
156
+ /**
157
+ * The two built-in tools. Features ADD tools via `registerTool` (a draw tool, a
158
+ * redact tool…). `enables` is the composition seam:
159
+ * pointer → text selection + annotation editing + annotation marquee selection
160
+ * pan → scrolling (contributed by Stage) + annotation editing, NO text select
161
+ *
162
+ * Both carry `form-fill`: filling a form is the RESTING state of a viewer
163
+ * (Acrobat's hand tool fills forms too), so widgets are fill-controls under the
164
+ * default tools and only become geometry-editable under a form-design tool.
165
+ * Both carry `link-nav` for the same reason: links navigate under the default
166
+ * tools (Acrobat behaviour) and only become geometry-editable under the link
167
+ * tool. Tags are opaque to the hub — without the form/link plugins they're inert.
168
+ */
169
+ declare const builtinTools: () => Tool[];
170
+ /**
171
+ * The interaction hub plugin — document-scoped, depends on nothing. Every feature
172
+ * plugin (selection, annotation, forms, redaction) `requires` this token; Stage
173
+ * `optional`-ly contributes a scroll handler. Works with `<Stage>` or a standalone
174
+ * `<PageView>` — it only routes page-space pointer samples.
175
+ */
176
+ declare const interactionPlugin: (config?: InteractionConfig) => import("@embedpdf/core").PluginDef<InteractionState, InteractionAction, InteractionCapability>;
177
+ //#endregion
178
+ //#region src/capability.d.ts
179
+ /**
180
+ * The interaction hub. Tools + handlers + the captured-gesture owner + cursor
181
+ * claims live in this closure (runtime registries, not serializable state); the
182
+ * reducer state holds only the active tool id and the resolved cursor, so the UI
183
+ * can react to them. The router (`dispatch`) is the heart: on down, the first
184
+ * eligible handler (by priority) to return true OWNS the gesture; move/up route
185
+ * to it; with no owner, move is hover (cursor feedback).
186
+ *
187
+ * Cursor arbitration, top to bottom: the highest-priority CLAIM (hover feedback
188
+ * — 'move' over an annotation, 'text' over text) → over a page, the tool's
189
+ * declared cursor → over a gap, the tool's `gapCursor` (default the neutral
190
+ * arrow). The winning KEYWORD (claim or base, never gap) is then restyled
191
+ * through the armed tool's skin when it maps that keyword. One resolver, so an
192
+ * image cursor can never shadow hover feedback or outlive the page under the
193
+ * pointer.
194
+ */
195
+ declare function createInteractionCapability(ctx: PluginContext<InteractionState, InteractionAction>, builtinTools: Tool[]): InteractionCapability;
196
+ //#endregion
197
+ //#region src/reducer.d.ts
198
+ declare const initialInteractionState: (config: InteractionConfig) => InteractionState;
199
+ declare const interactionReducer: (state: InteractionState, action: InteractionAction) => InteractionState;
200
+ //#endregion
201
+ export { type Cursor, type InteractionAction, type InteractionCapability, type InteractionConfig, type InteractionHandler, type InteractionState, InteractionToken, type Modifiers, type Phase, type PointerSample, type Tool, type ToolId, builtinTools, createInteractionCapability, initialInteractionState, interactionPlugin, interactionReducer, samplePointOn };
202
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,207 @@
1
+ import { createCapabilityToken, definePlugin } from "@embedpdf/core";
2
+ //#region src/capability.ts
3
+ /**
4
+ * The interaction hub. Tools + handlers + the captured-gesture owner + cursor
5
+ * claims live in this closure (runtime registries, not serializable state); the
6
+ * reducer state holds only the active tool id and the resolved cursor, so the UI
7
+ * can react to them. The router (`dispatch`) is the heart: on down, the first
8
+ * eligible handler (by priority) to return true OWNS the gesture; move/up route
9
+ * to it; with no owner, move is hover (cursor feedback).
10
+ *
11
+ * Cursor arbitration, top to bottom: the highest-priority CLAIM (hover feedback
12
+ * — 'move' over an annotation, 'text' over text) → over a page, the tool's
13
+ * declared cursor → over a gap, the tool's `gapCursor` (default the neutral
14
+ * arrow). The winning KEYWORD (claim or base, never gap) is then restyled
15
+ * through the armed tool's skin when it maps that keyword. One resolver, so an
16
+ * image cursor can never shadow hover feedback or outlive the page under the
17
+ * pointer.
18
+ */
19
+ function createInteractionCapability(ctx, builtinTools) {
20
+ const tools = /* @__PURE__ */ new Map();
21
+ for (const t of builtinTools) tools.set(t.id, t);
22
+ const handlers = [];
23
+ const claims = /* @__PURE__ */ new Map();
24
+ const cursorSkins = /* @__PURE__ */ new Map();
25
+ const toolCbs = /* @__PURE__ */ new Set();
26
+ let owner = null;
27
+ let overPage = false;
28
+ const toolOf = (id) => tools.get(id) ?? {
29
+ id,
30
+ cursor: "default",
31
+ enables: /* @__PURE__ */ new Set()
32
+ };
33
+ const active = () => toolOf(ctx.getState().activeToolId);
34
+ const resolveCursor = () => {
35
+ let top = null;
36
+ for (const c of claims.values()) if (!top || c.priority > top.priority) top = c;
37
+ const tool = active();
38
+ const skin = cursorSkins.get(tool.id);
39
+ if (top) return skin?.[top.cursor] ?? top.cursor;
40
+ if (!overPage) return tool.gapCursor ?? "default";
41
+ return skin?.[tool.cursor] ?? tool.cursor;
42
+ };
43
+ const syncCursor = () => {
44
+ const next = resolveCursor();
45
+ if (next !== ctx.getState().cursor) ctx.dispatch({
46
+ type: "SET_CURSOR",
47
+ cursor: next
48
+ });
49
+ };
50
+ const eligible = () => {
51
+ const tool = active();
52
+ return handlers.filter((h) => h.enabledFor(tool)).sort((a, b) => b.priority - a.priority);
53
+ };
54
+ return {
55
+ activeTool: active,
56
+ activeToolId: () => ctx.getState().activeToolId,
57
+ cursor: () => ctx.getState().cursor,
58
+ tools: () => [...tools.values()],
59
+ activateTool: (id) => {
60
+ if (!tools.has(id)) throw new Error(`[interaction] unknown tool '${id}'`);
61
+ owner = null;
62
+ claims.clear();
63
+ ctx.dispatch({
64
+ type: "SET_TOOL",
65
+ toolId: id
66
+ });
67
+ syncCursor();
68
+ toolCbs.forEach((cb) => cb());
69
+ },
70
+ onToolChange: (cb) => {
71
+ toolCbs.add(cb);
72
+ return () => toolCbs.delete(cb);
73
+ },
74
+ registerTool: (tool) => {
75
+ tools.set(tool.id, tool);
76
+ return () => {
77
+ tools.delete(tool.id);
78
+ cursorSkins.delete(tool.id);
79
+ };
80
+ },
81
+ setToolCursor: (id, skin) => {
82
+ if (skin === null) cursorSkins.delete(id);
83
+ else cursorSkins.set(id, skin);
84
+ syncCursor();
85
+ },
86
+ registerHandler: (handler) => {
87
+ handlers.push(handler);
88
+ return () => {
89
+ const i = handlers.indexOf(handler);
90
+ if (i >= 0) handlers.splice(i, 1);
91
+ if (owner === handler) owner = null;
92
+ };
93
+ },
94
+ setCursor: (token, cursor, priority = 0) => {
95
+ if (cursor === null) claims.delete(token);
96
+ else claims.set(token, {
97
+ cursor,
98
+ priority
99
+ });
100
+ syncCursor();
101
+ },
102
+ dispatch: (sample) => {
103
+ const nowOverPage = sample.page != null;
104
+ if (nowOverPage !== overPage) {
105
+ overPage = nowOverPage;
106
+ syncCursor();
107
+ }
108
+ if (sample.phase === "down") {
109
+ owner = null;
110
+ for (const h of eligible()) if (h.onDown(sample)) {
111
+ owner = h;
112
+ break;
113
+ }
114
+ } else if (sample.phase === "move") if (owner) owner.onMove?.(sample);
115
+ else for (const h of eligible()) h.onHover?.(sample);
116
+ else {
117
+ owner?.onUp?.(sample);
118
+ owner = null;
119
+ }
120
+ }
121
+ };
122
+ }
123
+ //#endregion
124
+ //#region src/reducer.ts
125
+ const initialInteractionState = (config) => ({
126
+ activeToolId: config.defaultTool ?? "pointer",
127
+ cursor: "default"
128
+ });
129
+ const interactionReducer = (state, action) => {
130
+ switch (action.type) {
131
+ case "SET_TOOL": return state.activeToolId === action.toolId ? state : {
132
+ ...state,
133
+ activeToolId: action.toolId
134
+ };
135
+ case "SET_CURSOR": return state.cursor === action.cursor ? state : {
136
+ ...state,
137
+ cursor: action.cursor
138
+ };
139
+ default: return state;
140
+ }
141
+ };
142
+ //#endregion
143
+ //#region src/types.ts
144
+ const InteractionToken = createCapabilityToken("interaction");
145
+ /**
146
+ * Resolve a sample against a gesture's HOME page. Page-anchored gestures track
147
+ * the page they started on even when the cursor wanders off it — `s.page`
148
+ * re-resolves per event (a foreign page is a DIFFERENT coordinate frame), so
149
+ * prefer the source's unclamped projection and fall back to the page hit only
150
+ * when it is the same page. Null → this sample can't speak for the home page.
151
+ * Shared by every gesture owner (annotation edit/draw, form placement).
152
+ */
153
+ const samplePointOn = (s, pon) => s.project?.(pon) ?? (s.page?.pon === pon ? s.page.point : null);
154
+ //#endregion
155
+ //#region src/interaction.plugin.ts
156
+ /**
157
+ * The two built-in tools. Features ADD tools via `registerTool` (a draw tool, a
158
+ * redact tool…). `enables` is the composition seam:
159
+ * pointer → text selection + annotation editing + annotation marquee selection
160
+ * pan → scrolling (contributed by Stage) + annotation editing, NO text select
161
+ *
162
+ * Both carry `form-fill`: filling a form is the RESTING state of a viewer
163
+ * (Acrobat's hand tool fills forms too), so widgets are fill-controls under the
164
+ * default tools and only become geometry-editable under a form-design tool.
165
+ * Both carry `link-nav` for the same reason: links navigate under the default
166
+ * tools (Acrobat behaviour) and only become geometry-editable under the link
167
+ * tool. Tags are opaque to the hub — without the form/link plugins they're inert.
168
+ */
169
+ const builtinTools = () => [{
170
+ id: "pointer",
171
+ cursor: "default",
172
+ enables: /* @__PURE__ */ new Set([
173
+ "text-select",
174
+ "annotation-edit",
175
+ "annotation-marquee",
176
+ "form-fill",
177
+ "link-nav"
178
+ ])
179
+ }, {
180
+ id: "pan",
181
+ cursor: "grab",
182
+ gapCursor: "grab",
183
+ enables: /* @__PURE__ */ new Set([
184
+ "scroll",
185
+ "annotation-edit",
186
+ "form-fill",
187
+ "link-nav"
188
+ ])
189
+ }];
190
+ /**
191
+ * The interaction hub plugin — document-scoped, depends on nothing. Every feature
192
+ * plugin (selection, annotation, forms, redaction) `requires` this token; Stage
193
+ * `optional`-ly contributes a scroll handler. Works with `<Stage>` or a standalone
194
+ * `<PageView>` — it only routes page-space pointer samples.
195
+ */
196
+ const interactionPlugin = (config = {}) => definePlugin({
197
+ id: "interaction",
198
+ token: InteractionToken,
199
+ scope: "document",
200
+ initialState: () => initialInteractionState(config),
201
+ reduce: interactionReducer,
202
+ capability: (ctx) => createInteractionCapability(ctx, builtinTools())
203
+ });
204
+ //#endregion
205
+ export { InteractionToken, builtinTools, createInteractionCapability, initialInteractionState, interactionPlugin, interactionReducer, samplePointOn };
206
+
207
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/capability.ts","../src/reducer.ts","../src/types.ts","../src/interaction.plugin.ts"],"sourcesContent":["import type { PluginContext } from '@embedpdf/core';\nimport type {\n Cursor,\n InteractionAction,\n InteractionCapability,\n InteractionHandler,\n InteractionState,\n Tool,\n ToolCursorSkin,\n ToolId,\n} from './types';\n\ninterface Claim {\n cursor: Cursor;\n priority: number;\n}\n\n/**\n * The interaction hub. Tools + handlers + the captured-gesture owner + cursor\n * claims live in this closure (runtime registries, not serializable state); the\n * reducer state holds only the active tool id and the resolved cursor, so the UI\n * can react to them. The router (`dispatch`) is the heart: on down, the first\n * eligible handler (by priority) to return true OWNS the gesture; move/up route\n * to it; with no owner, move is hover (cursor feedback).\n *\n * Cursor arbitration, top to bottom: the highest-priority CLAIM (hover feedback\n * — 'move' over an annotation, 'text' over text) → over a page, the tool's\n * declared cursor → over a gap, the tool's `gapCursor` (default the neutral\n * arrow). The winning KEYWORD (claim or base, never gap) is then restyled\n * through the armed tool's skin when it maps that keyword. One resolver, so an\n * image cursor can never shadow hover feedback or outlive the page under the\n * pointer.\n */\nexport function createInteractionCapability(\n ctx: PluginContext<InteractionState, InteractionAction>,\n builtinTools: Tool[],\n): InteractionCapability {\n const tools = new Map<ToolId, Tool>();\n for (const t of builtinTools) tools.set(t.id, t);\n const handlers: InteractionHandler[] = [];\n const claims = new Map<string, Claim>();\n const cursorSkins = new Map<ToolId, ToolCursorSkin>();\n const toolCbs = new Set<() => void>();\n let owner: InteractionHandler | null = null;\n // Whether the last dispatched sample hit a page — the base cursor only\n // applies where the tool can act; over gaps it falls back to `gapCursor`.\n let overPage = false;\n\n const toolOf = (id: ToolId): Tool =>\n tools.get(id) ?? { id, cursor: 'default', enables: new Set() };\n const active = (): Tool => toolOf(ctx.getState().activeToolId);\n\n const resolveCursor = (): Cursor => {\n let top: Claim | null = null;\n for (const c of claims.values()) if (!top || c.priority > top.priority) top = c;\n const tool = active();\n const skin = cursorSkins.get(tool.id);\n // The cursor keeps its MEANING (a keyword — the winning claim's, else the\n // tool's declared base); the skin may restyle that keyword in the armed\n // tool's identity (an I-beam + tool icon over text). Unmapped keywords\n // render as-is — a foreign affordance drops the tool identity — and gaps\n // resolve before the skin: identity only where the action is possible.\n if (top) return skin?.[top.cursor] ?? top.cursor;\n if (!overPage) return tool.gapCursor ?? 'default';\n return skin?.[tool.cursor] ?? tool.cursor;\n };\n const syncCursor = (): void => {\n const next = resolveCursor();\n if (next !== ctx.getState().cursor) ctx.dispatch({ type: 'SET_CURSOR', cursor: next });\n };\n\n const eligible = (): InteractionHandler[] => {\n const tool = active();\n return handlers.filter((h) => h.enabledFor(tool)).sort((a, b) => b.priority - a.priority);\n };\n\n return {\n activeTool: active,\n activeToolId: () => ctx.getState().activeToolId,\n cursor: () => ctx.getState().cursor,\n tools: () => [...tools.values()],\n\n activateTool: (id) => {\n if (!tools.has(id)) throw new Error(`[interaction] unknown tool '${id}'`);\n owner = null;\n claims.clear(); // drop the previous tool's hover claims; handlers re-claim on next hover\n ctx.dispatch({ type: 'SET_TOOL', toolId: id });\n syncCursor();\n toolCbs.forEach((cb) => cb());\n },\n\n onToolChange: (cb) => {\n toolCbs.add(cb);\n return () => toolCbs.delete(cb);\n },\n\n registerTool: (tool) => {\n tools.set(tool.id, tool);\n return () => {\n tools.delete(tool.id);\n cursorSkins.delete(tool.id);\n };\n },\n\n setToolCursor: (id, skin) => {\n if (skin === null) cursorSkins.delete(id);\n else cursorSkins.set(id, skin);\n syncCursor();\n },\n\n registerHandler: (handler) => {\n handlers.push(handler);\n return () => {\n const i = handlers.indexOf(handler);\n if (i >= 0) handlers.splice(i, 1);\n if (owner === handler) owner = null;\n };\n },\n\n setCursor: (token, cursor, priority = 0) => {\n if (cursor === null) claims.delete(token);\n else claims.set(token, { cursor, priority });\n syncCursor();\n },\n\n dispatch: (sample) => {\n const nowOverPage = sample.page != null;\n if (nowOverPage !== overPage) {\n overPage = nowOverPage;\n syncCursor(); // crossing a page edge re-resolves the base cursor\n }\n if (sample.phase === 'down') {\n owner = null;\n for (const h of eligible()) {\n if (h.onDown(sample)) {\n owner = h;\n break;\n }\n }\n } else if (sample.phase === 'move') {\n if (owner) owner.onMove?.(sample);\n else for (const h of eligible()) h.onHover?.(sample);\n } else {\n owner?.onUp?.(sample);\n owner = null;\n }\n },\n };\n}\n","import type { InteractionAction, InteractionConfig, InteractionState } from './types';\n\nexport const initialInteractionState = (config: InteractionConfig): InteractionState => ({\n activeToolId: config.defaultTool ?? 'pointer',\n cursor: 'default',\n});\n\nexport const interactionReducer = (\n state: InteractionState,\n action: InteractionAction,\n): InteractionState => {\n switch (action.type) {\n case 'SET_TOOL':\n return state.activeToolId === action.toolId\n ? state\n : { ...state, activeToolId: action.toolId };\n case 'SET_CURSOR':\n return state.cursor === action.cursor ? state : { ...state, cursor: action.cursor };\n default:\n return state;\n }\n};\n","import { createCapabilityToken, type PageObjectNumber } from '@embedpdf/core';\nimport type { PageRotation, Point } from '@embedpdf/core-geometry';\n\nexport type ToolId = string;\nexport type Cursor = string;\n\nexport interface Modifiers {\n shift: boolean;\n alt: boolean;\n ctrl: boolean;\n meta: boolean;\n}\n\n/**\n * The single active arbiter of what the pointer does. `pan` and `pointer` are\n * built in; features add more (`highlight`, `square`, `redact`…) via\n * `registerTool`. A tool carries no behaviour itself — it turns on capability\n * TAGS that handlers opt into (`enables`), so tools compose features without\n * coupling to them.\n */\nexport interface Tool {\n id: ToolId;\n cursor: Cursor;\n /**\n * Cursor over the viewport's page GAPS. A tool's cursor answers \"what would\n * a click do here\" — and most tools act only on pages, so gaps fall back to\n * the neutral arrow (`'default'`). A tool that works anywhere (pan) declares\n * its own (`'grab'`). Hover claims still outrank both.\n */\n gapCursor?: Cursor;\n enables: ReadonlySet<string>;\n}\n\nexport type Phase = 'down' | 'move' | 'up';\n\n/**\n * One normalized pointer event. `viewport` is the source container's px (the pan\n * handler uses the delta). `page` is the resolved page hit — its `pon` + content\n * point (y-down, PDF units, via the page's transform) — present when the pointer\n * is over a page, absent over gaps. A viewport source (Stage) resolves `page` per\n * event (so a drag can cross pages); a per-page source (PageView) always sets it.\n */\nexport interface PointerSample {\n phase: Phase;\n viewport: Point;\n /** `scale` is the hit page's VIEW px per content unit — handlers use it to\n * convert screen-px chrome settings into content-space tolerances, so grab\n * zones stay screen-constant across zoom. `rotation` is the hit page's TOTAL\n * display rotation (document /Rotate + view rotation) — per-event\n * environmental context like `scale`, for placement rules that depend on how\n * the page is DISPLAYED (an upright stamp). `zoom` is the page's zoom\n * RELATIVE to its 100% baseline (`transform.zoom` — dimensionless, 1 =\n * Acrobat's 100%), for zoom-relative policies (the `/F` NoZoom exemption);\n * distinct from `scale`, which is a units conversion. Absent when the\n * source can't say. */\n page?: {\n pon: PageObjectNumber;\n point: Point;\n scale?: number;\n rotation?: PageRotation;\n zoom?: number;\n };\n modifiers: Modifiers;\n /**\n * Click count for a `down` (1 = single, 2 = double, 3 = triple), from the\n * browser's native multi-click detection (`MouseEvent.detail`). Lets handlers\n * do word/line selection without re-implementing timing. Defaults to 1.\n */\n clickCount?: number;\n /**\n * Project this event onto a SPECIFIC page's content space, unclamped — valid\n * (and expected) outside the page's bounds. `page` answers \"what is under the\n * cursor\" and re-resolves per event; `project` answers \"where is the cursor\n * in MY page's frame\" for a gesture anchored to the page it started on (an\n * annotation drag sliding along the page edge). Null when the source can't\n * project onto that page (not laid out / a per-page source's foreign page).\n */\n project?(pon: PageObjectNumber): Point | null;\n}\n\n/**\n * A pointer handler contributed by a feature plugin. The ONE registration\n * mechanism (replacing v2's registerMode / registerHandlers / registerAlways /\n * enableForMode quartet): a handler declares which tools it's live under and a\n * priority; the hub routes each gesture to the first handler that captures it.\n */\nexport interface InteractionHandler {\n id: string;\n /** Higher wins the gesture. */\n priority: number;\n /** Usually `tool.enables.has('my-tag')`. */\n enabledFor(tool: Tool): boolean;\n /** Return true to CAPTURE: subsequent move/up route here until pointer-up. */\n onDown(sample: PointerSample): boolean;\n onMove?(sample: PointerSample): void;\n onUp?(sample: PointerSample): void;\n /** Pointer moved with no active gesture — cursor feedback only. */\n onHover?(sample: PointerSample): void;\n}\n\n/**\n * A tool's runtime cursor skin: \"while THIS tool is armed, keyword X looks\n * like Y.\" Everything cursor-shaped in the hub speaks KEYWORDS — a tool\n * declares its base ('crosshair', 'copy'), hover claims name what is under\n * the pointer ('text' over text, 'move' over an annotation) — and the skin\n * restyles those keywords, typically as image cursors carrying the tool's\n * icon. Applied uniformly to the winning claim and to the declared base, so\n * same keyword = same meaning = same look. Unmapped keywords render as-is (a\n * foreign 'move' over an annotation drops the tool identity), and page gaps\n * are never skinned — the identity appears exactly where the action is\n * possible, and the skin can only restyle where the tool already acts.\n */\nexport type ToolCursorSkin = Record<Cursor, Cursor>;\n\nexport interface InteractionState {\n activeToolId: ToolId;\n cursor: Cursor;\n}\n\nexport type InteractionAction =\n | { type: 'SET_TOOL'; toolId: ToolId }\n | { type: 'SET_CURSOR'; cursor: Cursor };\n\nexport interface InteractionCapability {\n // ── selectors ──\n activeTool(): Tool;\n activeToolId(): ToolId;\n cursor(): Cursor;\n tools(): Tool[];\n // ── tool intents ──\n activateTool(id: ToolId): void;\n /** Fires after the active tool changes — lets a feature react (e.g. a markup\n * tool taking over the selection visual). Returns an unsubscribe fn. */\n onToolChange(cb: () => void): () => void;\n /**\n * Reskin a tool's cursor keywords at runtime — how an app gives the armed\n * tool an image cursor built from its own toolbar icon (`Cursor` is any CSS\n * cursor string, `url(data:…) x y, crosshair` included). See\n * {@link ToolCursorSkin} for what the map means. `null` removes the skin.\n */\n setToolCursor(id: ToolId, skin: ToolCursorSkin | null): void;\n // ── registries (return an unregister fn) ──\n registerTool(tool: Tool): () => void;\n registerHandler(handler: InteractionHandler): () => void;\n // ── cursor claim stack (highest priority wins; null clears the token) ──\n setCursor(token: string, cursor: Cursor | null, priority?: number): void;\n // ── pointer ingress: the adapter calls this for every normalized event ──\n dispatch(sample: PointerSample): void;\n}\n\nexport const InteractionToken = createCapabilityToken<InteractionCapability>('interaction');\n\n/**\n * Resolve a sample against a gesture's HOME page. Page-anchored gestures track\n * the page they started on even when the cursor wanders off it — `s.page`\n * re-resolves per event (a foreign page is a DIFFERENT coordinate frame), so\n * prefer the source's unclamped projection and fall back to the page hit only\n * when it is the same page. Null → this sample can't speak for the home page.\n * Shared by every gesture owner (annotation edit/draw, form placement).\n */\nexport const samplePointOn = (s: PointerSample, pon: PageObjectNumber): Point | null =>\n s.project?.(pon) ?? (s.page?.pon === pon ? s.page.point : null);\n\nexport interface InteractionConfig {\n /** Tool active when a document opens. Default `'pointer'`. */\n defaultTool?: ToolId;\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { createInteractionCapability } from './capability';\nimport { initialInteractionState, interactionReducer } from './reducer';\nimport { InteractionToken } from './types';\nimport type {\n InteractionAction,\n InteractionCapability,\n InteractionConfig,\n InteractionState,\n Tool,\n} from './types';\n\n/**\n * The two built-in tools. Features ADD tools via `registerTool` (a draw tool, a\n * redact tool…). `enables` is the composition seam:\n * pointer → text selection + annotation editing + annotation marquee selection\n * pan → scrolling (contributed by Stage) + annotation editing, NO text select\n *\n * Both carry `form-fill`: filling a form is the RESTING state of a viewer\n * (Acrobat's hand tool fills forms too), so widgets are fill-controls under the\n * default tools and only become geometry-editable under a form-design tool.\n * Both carry `link-nav` for the same reason: links navigate under the default\n * tools (Acrobat behaviour) and only become geometry-editable under the link\n * tool. Tags are opaque to the hub — without the form/link plugins they're inert.\n */\nexport const builtinTools = (): Tool[] => [\n {\n id: 'pointer',\n cursor: 'default',\n enables: new Set([\n 'text-select',\n 'annotation-edit',\n 'annotation-marquee',\n 'form-fill',\n 'link-nav',\n ]),\n },\n {\n id: 'pan',\n cursor: 'grab',\n gapCursor: 'grab', // pan works anywhere — the open hand doesn't stop at page edges\n enables: new Set(['scroll', 'annotation-edit', 'form-fill', 'link-nav']),\n },\n];\n\n/**\n * The interaction hub plugin — document-scoped, depends on nothing. Every feature\n * plugin (selection, annotation, forms, redaction) `requires` this token; Stage\n * `optional`-ly contributes a scroll handler. Works with `<Stage>` or a standalone\n * `<PageView>` — it only routes page-space pointer samples.\n */\nexport const interactionPlugin = (config: InteractionConfig = {}) =>\n definePlugin<InteractionState, InteractionAction, InteractionCapability>({\n id: 'interaction',\n token: InteractionToken,\n scope: 'document',\n initialState: () => initialInteractionState(config),\n reduce: interactionReducer,\n capability: (ctx) => createInteractionCapability(ctx, builtinTools()),\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiCA,SAAgB,4BACd,KACA,cACuB;CACvB,MAAM,wBAAQ,IAAI,IAAkB;CACpC,KAAK,MAAM,KAAK,cAAc,MAAM,IAAI,EAAE,IAAI,CAAC;CAC/C,MAAM,WAAiC,CAAC;CACxC,MAAM,yBAAS,IAAI,IAAmB;CACtC,MAAM,8BAAc,IAAI,IAA4B;CACpD,MAAM,0BAAU,IAAI,IAAgB;CACpC,IAAI,QAAmC;CAGvC,IAAI,WAAW;CAEf,MAAM,UAAU,OACd,MAAM,IAAI,EAAE,KAAK;EAAE;EAAI,QAAQ;EAAW,yBAAS,IAAI,IAAI;CAAE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,QAAQ,OAAO;EAAO;EACpF,SACE,OAAO;CACX;AACF;;;ACiIA,MAAa,mBAAmB,sBAA6C,aAAa;;;;;;;;;AAU1F,MAAa,iBAAiB,GAAkB,QAC9C,EAAE,UAAU,GAAG,MAAM,EAAE,MAAM,QAAQ,MAAM,EAAE,KAAK,QAAQ;;;;;;;;;;;;;;;;ACxI5D,MAAa,qBAA6B,CACxC;CACE,IAAI;CACJ,QAAQ;CACR,yBAAS,IAAI,IAAI;EACf;EACA;EACA;EACA;EACA;CACF,CAAC;AACH,GACA;CACE,IAAI;CACJ,QAAQ;CACR,WAAW;CACX,yBAAS,IAAI,IAAI;EAAC;EAAU;EAAmB;EAAa;CAAU,CAAC;AACzE,CACF;;;;;;;AAQA,MAAa,qBAAqB,SAA4B,CAAC,MAC7D,aAAyE;CACvE,IAAI;CACJ,OAAO;CACP,OAAO;CACP,oBAAoB,wBAAwB,MAAM;CAClD,QAAQ;CACR,aAAa,QAAQ,4BAA4B,KAAK,aAAa,CAAC;AACtE,CAAC"}
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@embedpdf/plugin-interaction",
3
+ "version": "3.0.0-next.0",
4
+ "private": false,
5
+ "description": "The interaction hub: the active tool, the cursor, and pointer routing. Pure mechanism — knows nothing about selection/annotations/forms; they contribute tools + handlers.",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "dependencies": {
21
+ "@embedpdf/core": "3.0.0-next.0",
22
+ "@embedpdf/core-geometry": "3.0.0-next.0"
23
+ },
24
+ "devDependencies": {
25
+ "typescript": "^5.0.0",
26
+ "vitest": "^2.1.9",
27
+ "@embedpdf/tooling-build": "0.0.0"
28
+ },
29
+ "license": "Apache-2.0",
30
+ "sideEffects": false,
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/embedpdf/embed-pdf-viewer.git",
34
+ "directory": "packages/plugin/interaction"
35
+ },
36
+ "scripts": {
37
+ "build": "epdf-build",
38
+ "clean": "rimraf dist",
39
+ "typecheck": "tsc -p tsconfig.json --noEmit",
40
+ "test": "vitest run"
41
+ }
42
+ }