@embedpdf/plugin-selection 3.0.0-next.0 → 3.0.0-next.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,575 +1,154 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_reducer = require("./reducer-dmDFWFVx.cjs");
2
3
  let _embedpdf_core = require("@embedpdf/core");
3
4
  let _embedpdf_plugin_interaction = require("@embedpdf/plugin-interaction");
4
5
  let _embedpdf_core_geometry = require("@embedpdf/core-geometry");
5
- //#region src/geometry.ts
6
+ //#region src/selection.plugin.ts
6
7
  /**
7
- * The pure selection geometry: engine text geometry (PDF user space, y-up) →
8
- * viewer content space (y-down), glyph hit-testing, word/line expansion, and the
9
- * line-merge. No DOM, no engine, no React.
8
+ * Text selection — document-scoped, requires the interaction hub. In `init` it
9
+ * registers ITS pointer handler with the hub; the hub owns the pointer stream
10
+ * and arbitration. Works with `<Stage>` or a standalone `<PageView>` — selection
11
+ * only needs the page coordinate context + the engine's text geometry.
10
12
  *
11
- * The non-trivial bits are ports of battle-tested algorithms, adapted to v3's
12
- * content-space `Rect {x,y,width,height}`:
13
- * - `glyphAt` — PDFium `GetIndexAtPos` (exact tight box, then a tolerance pass).
14
- * - `rectsForRange` — Chromium `pdfium_range.cc` `MergeAdjacentRects` (one rect per line).
15
- * - `expandToWord/Line` — Chromium `OnMultipleClick` (double = word, triple = line).
16
- * The PDF↔content y-flip is the geometry package's `pageGeometry` (the one place
17
- * that math lives), never hand-rolled here.
18
- */
19
- const FLAG_EMPTY = 2;
20
- const isBoundary = (flags) => (flags & 3) !== 0;
21
- const isEmpty = (flags) => (flags & FLAG_EMPTY) !== 0;
22
- const toContent = (m, b) => (0, _embedpdf_core_geometry.applyRect)(m, {
23
- x: b.left,
24
- y: b.bottom,
25
- width: b.right - b.left,
26
- height: b.top - b.bottom
27
- });
28
- /**
29
- * Flatten a page's text geometry into content-space glyphs + runs. Rotation does
30
- * NOT enter here — the overlay rides the page's CSS rotation, so glyphs stay in
31
- * un-rotated content space (the crop-relative y-flip is the only conversion).
13
+ * Registry/content invalidation is wired inside the capability itself
14
+ * (revision watch + document event subscription), so headless/programmatic
15
+ * use gets the same reconciliation as the full viewer.
32
16
  */
33
- function buildPageText(snapshot, crop, rotation, userUnit) {
34
- const { pdfToContent } = (0, _embedpdf_core_geometry.pageGeometry)({
35
- crop,
36
- rotation,
37
- userUnit
38
- }, 1);
39
- const glyphs = [];
40
- const runs = [];
41
- for (const run of snapshot.runs) {
42
- const start = glyphs.length;
43
- for (const g of run.glyphs) glyphs.push({
44
- loose: toContent(pdfToContent, g.looseBox),
45
- tight: g.tightBox ? toContent(pdfToContent, g.tightBox) : void 0,
46
- flags: g.flags
47
- });
48
- runs.push({
49
- start,
50
- count: run.glyphs.length,
51
- rect: toContent(pdfToContent, run.rect),
52
- fontSize: run.fontSize
53
- });
54
- }
55
- return {
56
- glyphs,
57
- runs
58
- };
59
- }
60
- function avgGlyphHeight(text) {
61
- let total = 0;
62
- let count = 0;
63
- for (const g of text.glyphs) {
64
- if (isEmpty(g.flags)) continue;
65
- total += g.loose.height;
66
- count++;
67
- }
68
- return count === 0 ? 0 : total / count;
69
- }
70
- /**
71
- * The glyph index at a content-space point, or null when nothing is near (so the
72
- * caller can show the pointer cursor off-text). PDFium `GetIndexAtPos`: exact
73
- * tight-box containment first, then a tolerance pass (closest by Manhattan
74
- * distance within `toleranceFactor × average glyph height`).
75
- */
76
- function glyphAt(text, p, toleranceFactor = 1.5) {
77
- for (const run of text.runs) {
78
- const r = run.rect;
79
- if (p.x < r.x || p.x > r.x + r.width || p.y < r.y || p.y > r.y + r.height) continue;
80
- for (let i = 0; i < run.count; i++) {
81
- const b = text.glyphs[run.start + i].tight ?? text.glyphs[run.start + i].loose;
82
- if (p.x >= b.x && p.x <= b.x + b.width && p.y >= b.y && p.y <= b.y + b.height) return run.start + i;
83
- }
84
- }
85
- if (toleranceFactor <= 0) return null;
86
- const half = avgGlyphHeight(text) * toleranceFactor / 2;
87
- let best = -1;
88
- let bestDist = Infinity;
89
- for (const run of text.runs) {
90
- const r = run.rect;
91
- if (p.y < r.y - half || p.y > r.y + r.height + half || p.x < r.x - half || p.x > r.x + r.width + half) continue;
92
- for (let i = 0; i < run.count; i++) {
93
- const g = text.glyphs[run.start + i];
94
- if (isEmpty(g.flags)) continue;
95
- const b = g.tight ?? g.loose;
96
- if (p.x < b.x - half || p.x > b.x + b.width + half || p.y < b.y - half || p.y > b.y + b.height + half) continue;
97
- const dx = Math.min(Math.abs(p.x - b.x), Math.abs(p.x - (b.x + b.width)));
98
- const dy = Math.min(Math.abs(p.y - b.y), Math.abs(p.y - (b.y + b.height)));
99
- if (dx + dy < bestDist) {
100
- bestDist = dx + dy;
101
- best = run.start + i;
102
- }
103
- }
104
- }
105
- return best >= 0 ? best : null;
106
- }
107
- /** Double-click: the word around `i` (walk to space/empty glyphs both ways). */
108
- function expandToWord(text, i) {
109
- const n = text.glyphs.length;
110
- if (i < 0 || i >= n) return [i, i];
111
- let from = i;
112
- while (from > 0 && !isBoundary(text.glyphs[from - 1].flags)) from--;
113
- let to = i;
114
- while (to < n - 1 && !isBoundary(text.glyphs[to + 1].flags)) to++;
115
- return [from, to];
116
- }
117
- /** Triple-click: the full visual line — runs whose vertical extent overlaps the anchor run's. */
118
- function expandToLine(text, i) {
119
- const ri = text.runs.findIndex((r) => i >= r.start && i < r.start + r.count);
120
- if (ri < 0) return [i, i];
121
- const anchor = text.runs[ri];
122
- const top = anchor.rect.y;
123
- const bottom = anchor.rect.y + anchor.rect.height;
124
- let from = anchor.start;
125
- let to = anchor.start + anchor.count - 1;
126
- for (let r = ri - 1; r >= 0; r--) {
127
- const run = text.runs[r];
128
- if (isZero(run.rect)) continue;
129
- if (!overlapV(run.rect.y, run.rect.y + run.rect.height, top, bottom)) break;
130
- from = run.start;
131
- }
132
- for (let r = ri + 1; r < text.runs.length; r++) {
133
- const run = text.runs[r];
134
- if (isZero(run.rect)) continue;
135
- if (!overlapV(run.rect.y, run.rect.y + run.rect.height, top, bottom)) break;
136
- to = run.start + run.count - 1;
137
- }
138
- return [from, to];
139
- }
140
- const CHAR_DISTANCE_FACTOR = 2.5;
141
- const FONT_SIZE_RATIO_THRESHOLD = 1.5;
142
- const VERTICAL_OVERLAP_THRESHOLD = .8;
143
- const LINE_OVERLAP_THRESHOLD = .5;
144
- function rectsForRange(text, from, to) {
145
- const lo = Math.max(0, Math.min(from, to));
146
- const hi = Math.min(text.glyphs.length - 1, Math.max(from, to));
147
- const subRuns = [];
148
- for (const run of text.runs) {
149
- const runEnd = run.start + run.count - 1;
150
- if (runEnd < lo || run.start > hi) continue;
151
- const s = Math.max(lo, run.start);
152
- const e = Math.min(hi, runEnd);
153
- let minX = Infinity;
154
- let maxX = -Infinity;
155
- let minY = Infinity;
156
- let maxY = -Infinity;
157
- let charCount = 0;
158
- let widthSum = 0;
159
- let prevRight = -Infinity;
160
- const flush = () => {
161
- if (minX !== Infinity && charCount > 0) subRuns.push({
162
- rect: {
163
- x: minX,
164
- y: minY,
165
- width: maxX - minX,
166
- height: maxY - minY
167
- },
168
- charCount,
169
- fontSize: run.fontSize
170
- });
171
- minX = Infinity;
172
- maxX = -Infinity;
173
- minY = Infinity;
174
- maxY = -Infinity;
175
- charCount = 0;
176
- widthSum = 0;
177
- prevRight = -Infinity;
178
- };
179
- for (let gi = s; gi <= e; gi++) {
180
- const g = text.glyphs[gi];
181
- if (isEmpty(g.flags)) continue;
182
- const b = g.loose;
183
- if (charCount > 0 && prevRight > -Infinity) {
184
- const avg = widthSum / charCount;
185
- if (avg > 0 && Math.abs(b.x - prevRight) > CHAR_DISTANCE_FACTOR * avg) flush();
186
- }
187
- minX = Math.min(minX, b.x);
188
- maxX = Math.max(maxX, b.x + b.width);
189
- minY = Math.min(minY, b.y);
190
- maxY = Math.max(maxY, b.y + b.height);
191
- charCount++;
192
- widthSum += b.width;
193
- prevRight = b.x + b.width;
194
- }
195
- flush();
196
- }
197
- return mergeAdjacentRects(subRuns);
198
- }
199
- function mergeAdjacentRects(runs) {
200
- const out = [];
201
- let prev = null;
202
- let cur = null;
203
- for (const run of runs) {
204
- if (prev && cur && shouldMerge(prev, run)) cur = (0, _embedpdf_core_geometry.boundsOfRects)([cur, run.rect]);
205
- else {
206
- if (cur) out.push(cur);
207
- cur = run.rect;
208
- }
209
- prev = run;
210
- }
211
- if (cur && cur.width > 0 && cur.height > 0) out.push(cur);
212
- return out;
213
- }
214
- function shouldMerge(a, b) {
215
- if (a.fontSize != null && b.fontSize != null && a.fontSize > 0 && b.fontSize > 0) {
216
- if (Math.max(a.fontSize, b.fontSize) / Math.min(a.fontSize, b.fontSize) > FONT_SIZE_RATIO_THRESHOLD) return false;
17
+ const selectionPlugin = () => (0, _embedpdf_core.definePlugin)({
18
+ id: "selection",
19
+ token: require_reducer.SelectionToken,
20
+ scope: "document",
21
+ requires: [_embedpdf_plugin_interaction.InteractionToken],
22
+ optional: [_embedpdf_plugin_interaction.FeedbackToken],
23
+ initialState: require_reducer.initialSelectionState,
24
+ reduce: require_reducer.selectionReducer,
25
+ capability: require_reducer.createSelectionCapability,
26
+ init: (ctx) => {
27
+ const interaction = ctx.get(_embedpdf_plugin_interaction.InteractionToken);
28
+ const selection = ctx.get(require_reducer.SelectionToken);
29
+ const feedback = ctx.tryGet(_embedpdf_plugin_interaction.FeedbackToken);
30
+ interaction.registerHandler(require_reducer.createTextSelectHandler(selection, interaction, feedback ?? void 0));
217
31
  }
218
- if (verticalOverlap(a.rect, b.rect) < VERTICAL_OVERLAP_THRESHOLD) return false;
219
- const aw = a.rect.width / a.charCount;
220
- const bw = b.rect.width / b.charCount;
221
- const aL = a.rect.x - aw;
222
- const aR = a.rect.x + a.rect.width + aw;
223
- const bL = b.rect.x - bw;
224
- return aL < b.rect.x + b.rect.width + bw && aR > bL;
225
- }
226
- function verticalOverlap(a, b) {
227
- if (a.height <= 0 || b.height <= 0) return 0;
228
- const u = Math.max(a.y + a.height, b.y + b.height) - Math.min(a.y, b.y);
229
- if (u === a.height || u === b.height) return 1;
230
- return Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)) / u;
231
- }
232
- const isZero = (r) => r.width === 0 && r.height === 0;
233
- function overlapV(top1, bottom1, top2, bottom2) {
234
- const u = Math.max(bottom1, bottom2) - Math.min(top1, top2);
235
- if (u === 0) return false;
236
- return Math.max(0, Math.min(bottom1, bottom2) - Math.max(top1, top2)) / u >= LINE_OVERLAP_THRESHOLD;
237
- }
32
+ });
238
33
  //#endregion
239
- //#region src/capability.ts
240
- const EMPTY = [];
34
+ //#region src/handles.ts
241
35
  /**
242
- * The selection capability. The reducer state holds the selection range, the
243
- * derived content-space rects (per page), and per-page loaded flags; the (large,
244
- * non-serializable) per-page text geometry is cached HERE in the closure.
36
+ * Selection handles — the pure policy half (the `wheel.ts` convention).
37
+ *
38
+ * A handle IS the boundary glyph's leading (or trailing) edge: a segment
39
+ * between two corners of the glyph's ORIENTED cell, with the grab head just
40
+ * beyond the ascent at the start / past the baseline at the end. Bar length,
41
+ * angle, and head all derive from that one segment, so rotated text and
42
+ * rotated pages are carried by construction — the AABB never enters.
245
43
  *
246
- * Selection is cross-page: glyphs are ordered globally by (pageIndex, glyph), so
247
- * a drag from page 2 into page 4 selects the tail of 2, all of 3, and the head of
248
- * 4. `recompute` rebuilds the merged line rects for every loaded page in the span
249
- * and re-runs whenever a mid-span page finishes loading.
44
+ * Everything here is DOM-free and framework-free: geometry is pure given a
45
+ * projector, and the drag session speaks the selection's own gesture verbs
46
+ * (`beginAt`/`extendTo`/`end` — the same ones the pointer handler uses; a
47
+ * handle drag IS a selection gesture, re-anchored). The framework adapters
48
+ * keep only subscriptions and markup; the DOM listener mechanics live in
49
+ * `@embedpdf/web`'s `attachSelectionHandle`.
50
+ *
51
+ * The view dependency is STRUCTURAL (satisfied by five lines over
52
+ * `StageCapability`) so this plugin stays stage-free — selection also runs
53
+ * in stage-less hosts (`PageView`) — and the math tests run against a fake.
250
54
  */
251
- function createSelectionCapability(ctx) {
252
- const cache = /* @__PURE__ */ new Map();
253
- const pending = /* @__PURE__ */ new Set();
254
- const changeCbs = /* @__PURE__ */ new Set();
255
- const commitCbs = /* @__PURE__ */ new Set();
256
- const fireChange = () => changeCbs.forEach((cb) => cb());
257
- const pageIndexOf = (pon) => ctx.document()?.pages.findIndex((p) => p.pageObjectNumber === pon) ?? -1;
258
- const ponAtIndex = (i) => ctx.document()?.pages[i]?.pageObjectNumber;
259
- function orderedEnds(sel) {
260
- const ai = pageIndexOf(sel.anchor.pon);
261
- const fi = pageIndexOf(sel.focus.pon);
262
- return ai < fi || ai === fi && sel.anchor.glyph <= sel.focus.glyph ? {
263
- start: sel.anchor,
264
- end: sel.focus,
265
- direction: "forward"
266
- } : {
267
- start: sel.focus,
268
- end: sel.anchor,
269
- direction: "backward"
270
- };
271
- }
272
- function endpointFor(ptr, which) {
273
- const rects = ctx.getState().rects[ptr.pon] ?? EMPTY;
274
- if (!rects.length) return null;
275
- return {
276
- pon: ptr.pon,
277
- rect: which === "start" ? rects[0] : rects[rects.length - 1]
278
- };
279
- }
280
- function snapshot() {
281
- const { selection, rects } = ctx.getState();
282
- const pages = Object.keys(rects).map(Number).filter((pon) => (rects[pon]?.length ?? 0) > 0).map((pon) => ({
283
- pon,
284
- rects: rects[pon]
285
- }));
286
- if (!selection) return {
287
- pages,
288
- start: null,
289
- end: null,
290
- direction: "forward"
291
- };
292
- const { start, end, direction } = orderedEnds(selection);
293
- return {
294
- pages,
295
- start: endpointFor(start, "start"),
296
- end: endpointFor(end, "end"),
297
- direction
298
- };
299
- }
300
- function ensurePage(pon) {
301
- if (cache.has(pon) || pending.has(pon)) return;
302
- const doc = ctx.doc;
303
- const layout = ctx.document()?.pages.find((p) => p.pageObjectNumber === pon);
304
- if (!doc || !layout) return;
305
- pending.add(pon);
306
- doc.page(pon).geometry.read().then((snapshot) => {
307
- pending.delete(pon);
308
- cache.set(pon, buildPageText(snapshot, layout.boxes.crop, layout.rotation, layout.userUnit));
309
- ctx.dispatch({
310
- type: "PAGE_LOADED",
311
- pon
312
- });
313
- if (ctx.getState().selection) recompute();
314
- }, () => {
315
- pending.delete(pon);
316
- });
317
- }
318
- function recompute(sel = ctx.getState().selection) {
319
- if (!sel) return;
320
- const { start, end } = orderedEnds(sel);
321
- const si = pageIndexOf(start.pon);
322
- const ei = pageIndexOf(end.pon);
323
- if (si < 0 || ei < 0) return;
324
- const rects = {};
325
- for (let i = si; i <= ei; i++) {
326
- const pon = ponAtIndex(i);
327
- if (pon == null) continue;
328
- const text = cache.get(pon);
329
- if (!text) {
330
- ensurePage(pon);
331
- continue;
332
- }
333
- rects[pon] = rectsForRange(text, i === si ? start.glyph : 0, i === ei ? end.glyph : text.glyphs.length - 1);
334
- }
335
- ctx.dispatch({
336
- type: "SET",
337
- selection: sel,
338
- rects
339
- });
340
- fireChange();
341
- }
342
- function selectSpan(pon, point, expand) {
343
- const text = cache.get(pon);
344
- if (!text) return;
345
- const i = glyphAt(text, point);
346
- if (i == null) return;
347
- const [from, to] = expand === "word" ? expandToWord(text, i) : expandToLine(text, i);
348
- recompute({
349
- anchor: {
350
- pon,
351
- glyph: from
352
- },
353
- focus: {
354
- pon,
355
- glyph: to
356
- }
357
- });
358
- }
55
+ const HANDLE_HEAD = 12;
56
+ const HANDLE_BAR = 2;
57
+ const HANDLE_PAD = 14;
58
+ /** Tilts within ~0.05° of upright render untransformed (float-noise guard —
59
+ * and the dominant case stays pixel-identical to an axis-aligned box). */
60
+ const HANDLE_ROT_EPSILON = .05;
61
+ const midpoint = (a, b) => ({
62
+ x: (a.x + b.x) / 2,
63
+ y: (a.y + b.y) / 2
64
+ });
65
+ /**
66
+ * The handle's geometry for one endpoint, in overlay space. Null when the
67
+ * endpoint's page isn't laid out (or the cell is degenerate) — render nothing.
68
+ */
69
+ function selectionHandleGeom(view, ep, role) {
70
+ const leading = role === "start" ? ep.advance > 0 : ep.advance < 0;
71
+ const [upperPage, lowerPage] = (0, _embedpdf_core_geometry.textQuadEdge)(ep.glyphQuad, leading ? "start" : "end");
72
+ const upper = view.toOverlay(ep.pon, upperPage);
73
+ const lower = view.toOverlay(ep.pon, lowerPage);
74
+ if (!upper || !lower) return null;
75
+ const dx = lower.x - upper.x;
76
+ const dy = lower.y - upper.y;
77
+ const length = Math.hypot(dx, dy);
78
+ if (length === 0) return null;
79
+ const rotation = Math.atan2(dy, dx) * 180 / Math.PI - 90;
80
+ const upright = Math.abs(rotation) < HANDLE_ROT_EPSILON;
81
+ const ux = dx / length;
82
+ const uy = dy / length;
83
+ const head = role === "start" ? {
84
+ x: upper.x - ux * 12 / 2,
85
+ y: upper.y - uy * 12 / 2
86
+ } : {
87
+ x: lower.x + ux * 12 / 2,
88
+ y: lower.y + uy * 12 / 2
89
+ };
359
90
  return {
360
- ensurePage,
361
- isLoaded: (pon) => !!ctx.getState().loaded[pon],
362
- isOverText: (pon, point) => {
363
- const text = cache.get(pon);
364
- return text ? glyphAt(text, point) != null : false;
365
- },
366
- beginAt: (pon, point) => {
367
- const text = cache.get(pon);
368
- if (!text) return false;
369
- const i = glyphAt(text, point);
370
- if (i == null) return false;
371
- recompute({
372
- anchor: {
373
- pon,
374
- glyph: i
375
- },
376
- focus: {
377
- pon,
378
- glyph: i
379
- }
380
- });
381
- return true;
382
- },
383
- selectWord: (pon, point) => selectSpan(pon, point, "word"),
384
- selectLine: (pon, point) => selectSpan(pon, point, "line"),
385
- extendTo: (pon, point) => {
386
- const cur = ctx.getState().selection;
387
- if (!cur) return;
388
- const text = cache.get(pon);
389
- if (!text) {
390
- ensurePage(pon);
391
- return;
392
- }
393
- const i = glyphAt(text, point);
394
- if (i == null) return;
395
- recompute({
396
- anchor: cur.anchor,
397
- focus: {
398
- pon,
399
- glyph: i
400
- }
401
- });
402
- },
403
- end: () => commitCbs.forEach((cb) => cb()),
404
- clear: () => {
405
- ctx.dispatch({ type: "CLEAR" });
406
- fireChange();
91
+ bar: {
92
+ from: upper,
93
+ to: lower
407
94
  },
408
- snapshot,
409
- rectsForPage: (pon) => ctx.getState().rects[pon] ?? EMPTY,
410
- hasSelection: () => ctx.getState().selection != null,
411
- selectedPages: () => {
412
- const { rects } = ctx.getState();
413
- return Object.keys(rects).map(Number).filter((pon) => (rects[pon]?.length ?? 0) > 0);
414
- },
415
- onChange: (cb) => {
416
- changeCbs.add(cb);
417
- return () => changeCbs.delete(cb);
418
- },
419
- onCommit: (cb) => {
420
- commitCbs.add(cb);
421
- return () => commitCbs.delete(cb);
422
- },
423
- setHighlightVisible: (visible) => ctx.dispatch({
424
- type: "SET_HIGHLIGHT_HIDDEN",
425
- hidden: !visible
426
- }),
427
- highlightVisible: () => !ctx.getState().highlightHidden
95
+ length,
96
+ rotation,
97
+ upright,
98
+ head
428
99
  };
429
100
  }
430
- //#endregion
431
- //#region src/handler.ts
432
- const CURSOR_TOKEN = "selection-text";
433
- const DRAG_THRESHOLD_PX = 4;
434
101
  /**
435
- * The text-selection pointer handler. It is live only under tools that enable the
436
- * `'text-select'` tag (the built-in `pointer` tool does; `pan` does not — so
437
- * switching to pan disables text selection with zero special-casing here).
438
- *
439
- * - single click → deselect; records an anchor but selects NOTHING until
440
- * the pointer moves past the drag threshold (Chrome/Acrobat feel)
441
- * - single-click + drag → caret selection from the anchor (extends across pages)
442
- * - double-click → select the word
443
- * - triple-click → select the visual line
444
- * - down off-text → deselect, and DON'T capture (so it can't block)
445
- * - hover → I-beam only when over text, else the pointer cursor
102
+ * One armed handle drag. Dragging a handle extends from the OPPOSITE
103
+ * endpoint: the first movement re-roots the selection gesture at that
104
+ * endpoint's cell centre, and every position then extends toward the pointer
105
+ * — snapping to glyphs and crossing pages exactly like a pointer drag,
106
+ * firing the same change/commit signals. Over a gap the point projects onto
107
+ * the last page hit (unclamped), so the selection keeps tracking instead of
108
+ * freezing at a page edge. `end()` commits only if the drag actually
109
+ * re-rooted; an untouched press settles nothing.
446
110
  */
447
- function createTextSelectHandler(selection, interaction) {
448
- let anchor = null;
449
- let dragging = false;
111
+ function createSelectionHandleDrag(selection, view, opposite, draggedPon) {
112
+ const q = opposite.glyphQuad;
113
+ const anchorPoint = midpoint(midpoint(q.upperStart, q.lowerEnd), midpoint(q.upperEnd, q.lowerStart));
114
+ let begun = false;
115
+ let lastPon = draggedPon;
450
116
  return {
451
- id: "text-select",
452
- priority: 60,
453
- enabledFor: (tool) => tool.enables.has("text-select"),
454
- onDown: (s) => {
455
- anchor = null;
456
- dragging = false;
457
- if (!s.page) return false;
458
- const { pon, point } = s.page;
459
- const clicks = s.clickCount ?? 1;
460
- if (clicks >= 3) {
461
- selection.selectLine(pon, point);
462
- return true;
463
- }
464
- if (clicks === 2) {
465
- selection.selectWord(pon, point);
466
- return true;
117
+ move: (overlay) => {
118
+ if (!begun) {
119
+ if (!selection.beginAt(opposite.pon, anchorPoint)) return;
120
+ begun = true;
467
121
  }
468
- selection.clear();
469
- if (!selection.isOverText(pon, point)) return false;
470
- anchor = {
471
- pon,
472
- point,
473
- vx: s.viewport.x,
474
- vy: s.viewport.y
475
- };
476
- return true;
477
- },
478
- onMove: (s) => {
479
- if (!s.page || !anchor) return;
480
- if (!dragging) {
481
- if (Math.hypot(s.viewport.x - anchor.vx, s.viewport.y - anchor.vy) < DRAG_THRESHOLD_PX) return;
482
- dragging = true;
483
- selection.beginAt(anchor.pon, anchor.point);
122
+ const hit = view.pageAt(overlay);
123
+ if (hit) {
124
+ lastPon = hit.pon;
125
+ selection.extendTo(hit.pon, hit.point);
126
+ } else {
127
+ const p = view.pointOnPage(lastPon, overlay);
128
+ if (p) selection.extendTo(lastPon, p);
484
129
  }
485
- selection.extendTo(s.page.pon, s.page.point);
486
130
  },
487
- onUp: () => {
488
- anchor = null;
489
- dragging = false;
490
- selection.end();
491
- },
492
- onHover: (s) => {
493
- if (!s.page) {
494
- interaction.setCursor(CURSOR_TOKEN, null);
495
- return;
496
- }
497
- selection.ensurePage(s.page.pon);
498
- const overText = selection.isOverText(s.page.pon, s.page.point);
499
- interaction.setCursor(CURSOR_TOKEN, overText ? "text" : null, 10);
131
+ end: () => {
132
+ if (begun) selection.end();
500
133
  }
501
134
  };
502
135
  }
503
136
  //#endregion
504
- //#region src/reducer.ts
505
- const initialSelectionState = {
506
- selection: null,
507
- rects: {},
508
- loaded: {},
509
- highlightHidden: false
510
- };
511
- const selectionReducer = (state, action) => {
512
- switch (action.type) {
513
- case "PAGE_LOADED": return state.loaded[action.pon] ? state : {
514
- ...state,
515
- loaded: {
516
- ...state.loaded,
517
- [action.pon]: true
518
- }
519
- };
520
- case "SET": return {
521
- ...state,
522
- selection: action.selection,
523
- rects: action.rects
524
- };
525
- case "CLEAR": return state.selection === null && Object.keys(state.rects).length === 0 ? state : {
526
- ...state,
527
- selection: null,
528
- rects: {}
529
- };
530
- case "SET_HIGHLIGHT_HIDDEN": return state.highlightHidden === action.hidden ? state : {
531
- ...state,
532
- highlightHidden: action.hidden
533
- };
534
- default: return state;
535
- }
536
- };
537
- //#endregion
538
- //#region src/types.ts
539
- const SelectionToken = (0, _embedpdf_core.createCapabilityToken)("selection");
540
- //#endregion
541
- //#region src/selection.plugin.ts
137
+ //#region src/index.ts
542
138
  /**
543
- * Text selection — document-scoped, requires the interaction hub. In `init` it
544
- * registers ITS pointer handler with the hub; the hub owns the pointer stream
545
- * and arbitration. Works with `<Stage>` or a standalone `<PageView>` — selection
546
- * only needs the page coordinate context + the engine's text geometry.
139
+ * The selection capability token, narrowed to the public
140
+ * {@link SelectionCapability} lens. It is the SAME runtime token the plugin
141
+ * provides — the host-only surface (pointer gestures, geometry warming) is
142
+ * reachable only via `@embedpdf/plugin-selection/internal`.
547
143
  */
548
- const selectionPlugin = () => (0, _embedpdf_core.definePlugin)({
549
- id: "selection",
550
- token: SelectionToken,
551
- scope: "document",
552
- requires: [_embedpdf_plugin_interaction.InteractionToken],
553
- initialState: initialSelectionState,
554
- reduce: selectionReducer,
555
- capability: createSelectionCapability,
556
- init: (ctx) => {
557
- const interaction = ctx.get(_embedpdf_plugin_interaction.InteractionToken);
558
- const selection = ctx.get(SelectionToken);
559
- interaction.registerHandler(createTextSelectHandler(selection, interaction));
560
- }
561
- });
144
+ const SelectionToken = require_reducer.SelectionToken;
562
145
  //#endregion
146
+ exports.HANDLE_BAR = HANDLE_BAR;
147
+ exports.HANDLE_HEAD = HANDLE_HEAD;
148
+ exports.HANDLE_PAD = HANDLE_PAD;
563
149
  exports.SelectionToken = SelectionToken;
564
- exports.buildPageText = buildPageText;
565
- exports.createSelectionCapability = createSelectionCapability;
566
- exports.createTextSelectHandler = createTextSelectHandler;
567
- exports.expandToLine = expandToLine;
568
- exports.expandToWord = expandToWord;
569
- exports.glyphAt = glyphAt;
570
- exports.initialSelectionState = initialSelectionState;
571
- exports.rectsForRange = rectsForRange;
150
+ exports.createSelectionHandleDrag = createSelectionHandleDrag;
151
+ exports.selectionHandleGeom = selectionHandleGeom;
572
152
  exports.selectionPlugin = selectionPlugin;
573
- exports.selectionReducer = selectionReducer;
574
153
 
575
154
  //# sourceMappingURL=index.cjs.map