@embedpdf/plugin-selection 3.0.0-next.1 → 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.
@@ -0,0 +1,748 @@
1
+ let _embedpdf_core = require("@embedpdf/core");
2
+ let _embedpdf_core_geometry = require("@embedpdf/core-geometry");
3
+ let _embedpdf_engine_core_runtime = require("@embedpdf/engine-core/runtime");
4
+ //#region src/types.ts
5
+ /**
6
+ * The selection capability token. Typed to the full
7
+ * {@link SelectionHostCapability} for this module and `/internal`; the
8
+ * package root re-exports the SAME token narrowed to
9
+ * {@link SelectionCapability}.
10
+ */
11
+ const SelectionToken = (0, _embedpdf_core.createCapabilityToken)("selection");
12
+ //#endregion
13
+ //#region src/geometry.ts
14
+ /**
15
+ * The selection plugin's COORDINATE SEAM — and nothing else.
16
+ *
17
+ * Segmentation, hit-testing, and word/line expansion live in the canonical
18
+ * engine-core text layout (`@embedpdf/engine-core` `text/layout`): a text
19
+ * range has exactly one segmentation whether it came from a drag or a
20
+ * search. This module only converts between the viewer's content space
21
+ * (y-down, crop-relative) and the engine's PDF space (y-up) — pointer
22
+ * points inward, canonical segments outward. The PDF↔content y-flip is the
23
+ * geometry package's `pageGeometry` (the one place that math lives), never
24
+ * hand-rolled here.
25
+ */
26
+ /**
27
+ * Build a page's selection geometry. Page display rotation does NOT enter
28
+ * here — the overlay rides the page's CSS rotation, so content space stays
29
+ * un-rotated (the crop-relative y-flip is the only conversion; zoom = 1,
30
+ * the viewer's zoom is applied later by `PageTransform.toPixels`).
31
+ */
32
+ function buildSelectionPageGeometry(snapshot, crop, rotation, userUnit) {
33
+ const { pdfToContent } = (0, _embedpdf_core_geometry.pageGeometry)({
34
+ crop,
35
+ rotation,
36
+ userUnit
37
+ }, 1);
38
+ return {
39
+ layout: (0, _embedpdf_engine_core_runtime.buildPageTextLayout)(snapshot),
40
+ toContent: pdfToContent,
41
+ fromContent: (0, _embedpdf_core_geometry.invert)(pdfToContent)
42
+ };
43
+ }
44
+ /** A content-space pointer point in the layout's PDF space. */
45
+ function contentPointToPdf(geom, p) {
46
+ return (0, _embedpdf_core_geometry.applyPoint)(geom.fromContent, p);
47
+ }
48
+ /**
49
+ * A canonical PDF quad in content space. Engine quads carry frame-geometric
50
+ * slot semantics (`p1..p4` = upper-start, upper-end, lower-start,
51
+ * lower-end) — a trusted producer, so the y-flip maps corners straight onto
52
+ * their names; imported-annotation normalization does NOT apply here.
53
+ */
54
+ function toContentTextQuad(geom, quad) {
55
+ const pt = (p) => (0, _embedpdf_core_geometry.applyPoint)(geom.toContent, p);
56
+ return {
57
+ upperStart: pt(quad.p1),
58
+ upperEnd: pt(quad.p2),
59
+ lowerStart: pt(quad.p3),
60
+ lowerEnd: pt(quad.p4)
61
+ };
62
+ }
63
+ /** A canonical segment in content space (`rect` recomputed from the mapped
64
+ * quad so the pair can never drift). */
65
+ function toContentSegment(geom, segment) {
66
+ const quad = toContentTextQuad(geom, segment.quad);
67
+ return {
68
+ quad,
69
+ rect: (0, _embedpdf_core_geometry.textQuadBounds)(quad),
70
+ advance: segment.advance
71
+ };
72
+ }
73
+ //#endregion
74
+ //#region src/capability.ts
75
+ const EMPTY_SEGMENTS = [];
76
+ /** How many page-text reads `readText()` keeps in flight at once. */
77
+ const TEXT_READ_CONCURRENCY = 8;
78
+ /**
79
+ * The selection capability — ONE closure returning the host lens (the
80
+ * public lens is the same object, narrowed at the package root).
81
+ *
82
+ * State model: the reducer holds the selection range and the derived
83
+ * content-space segments; the large, non-serializable per-page caches live
84
+ * HERE in the closure, split by what invalidates them:
85
+ *
86
+ * - `rawGeometry` — PDF-space geometry snapshots, rotation-independent
87
+ * (pages load normalized; see `PageRotateResult`). Dropped only when a
88
+ * page leaves the registry or page CONTENT changes (redaction apply /
89
+ * flatten).
90
+ * - `derived` — the content-space transform + layout, keyed by the
91
+ * layout params (crop/rotation/userUnit) so a view-rotate re-derives
92
+ * from the cached raw snapshot with NO refetch.
93
+ * - `textSnapshots` — per-page text (for `readText`), same content-only
94
+ * invalidation as `rawGeometry`.
95
+ *
96
+ * Permission model: `doc.text.select` gates geometry (selection exists),
97
+ * `doc.text.copy` gates text (extraction) — neither implies the other.
98
+ * Host gesture functions are INERT when select is denied (`ensurePage`
99
+ * no-ops, so nothing warms and nothing hit-tests: the pointer handler
100
+ * needs no special-casing); the public `select()` THROWS `PermissionDenied`
101
+ * so programmatic misuse is loud; `clear()` is always allowed. The engine
102
+ * independently enforces both scopes — these gates exist so the plugin
103
+ * never issues a request that is guaranteed to fail.
104
+ *
105
+ * Selection is cross-page: glyphs are ordered globally by (pageIndex,
106
+ * glyph), so a drag from page 2 into page 4 selects the tail of 2, all of
107
+ * 3, and the head of 4. `recompute` rebuilds the merged line segments for
108
+ * every loaded page in the span, re-runs whenever a mid-span page finishes
109
+ * loading, and CLAMPS stored endpoints once their page's geometry is known
110
+ * (so `selectAll`'s open-ended focus settles to the real last character).
111
+ */
112
+ function createSelectionCapability(ctx) {
113
+ const rawGeometry = /* @__PURE__ */ new Map();
114
+ const derived = /* @__PURE__ */ new Map();
115
+ const pending = /* @__PURE__ */ new Set();
116
+ const textSnapshots = /* @__PURE__ */ new Map();
117
+ /** Bumped on content invalidation; in-flight reads from before are discarded. */
118
+ let epoch = 0;
119
+ const changeCbs = /* @__PURE__ */ new Set();
120
+ const commitCbs = /* @__PURE__ */ new Set();
121
+ const fireChange = () => changeCbs.forEach((cb) => cb());
122
+ const canSelect = () => ctx.doc?.security.allows("doc.text.select") ?? false;
123
+ const canCopy = () => ctx.doc?.security.allows("doc.text.copy") ?? false;
124
+ const layoutOf = (pon) => ctx.document()?.pages.find((p) => p.pageObjectNumber === pon);
125
+ const pageIndexOf = (pon) => ctx.document()?.pages.findIndex((p) => p.pageObjectNumber === pon) ?? -1;
126
+ const ponAtIndex = (i) => ctx.document()?.pages[i]?.pageObjectNumber;
127
+ /**
128
+ * The content-space geometry for a page, derived on demand from the raw
129
+ * snapshot + the CURRENT layout params. A view-rotate (or crop change)
130
+ * changes the key and re-derives — raw caches and the engine are never
131
+ * touched (rotation is presentation metadata).
132
+ */
133
+ function geometryFor(pon) {
134
+ const raw = rawGeometry.get(pon);
135
+ const layout = layoutOf(pon);
136
+ if (!raw || !layout) return null;
137
+ const crop = layout.boxes.crop;
138
+ const key = `${layout.rotation}|${layout.userUnit}|${crop.left},${crop.bottom},${crop.right},${crop.top}`;
139
+ const hit = derived.get(pon);
140
+ if (hit && hit.key === key) return hit.geom;
141
+ const geom = buildSelectionPageGeometry(raw, crop, layout.rotation, layout.userUnit);
142
+ derived.set(pon, {
143
+ key,
144
+ geom
145
+ });
146
+ return geom;
147
+ }
148
+ const glyphAt = (geom, point) => (0, _embedpdf_engine_core_runtime.textGlyphAt)(geom.layout, contentPointToPdf(geom, point));
149
+ function orderedEnds(sel) {
150
+ const ai = pageIndexOf(sel.anchor.pon);
151
+ const fi = pageIndexOf(sel.focus.pon);
152
+ return ai < fi || ai === fi && sel.anchor.glyph <= sel.focus.glyph ? {
153
+ start: sel.anchor,
154
+ end: sel.focus,
155
+ direction: "forward"
156
+ } : {
157
+ start: sel.focus,
158
+ end: sel.anchor,
159
+ direction: "backward"
160
+ };
161
+ }
162
+ function endpointFor(ptr, which) {
163
+ const segments = ctx.getState().segments[ptr.pon] ?? EMPTY_SEGMENTS;
164
+ if (!segments.length) return null;
165
+ const segment = which === "start" ? segments[0] : segments[segments.length - 1];
166
+ const geom = geometryFor(ptr.pon);
167
+ const cell = geom ? (0, _embedpdf_engine_core_runtime.textGlyphQuad)(geom.layout, ptr.glyph) : null;
168
+ if (geom && cell) {
169
+ const glyphQuad = toContentTextQuad(geom, cell);
170
+ return {
171
+ pon: ptr.pon,
172
+ glyphQuad,
173
+ advance: segment.advance,
174
+ rect: (0, _embedpdf_core_geometry.textQuadBounds)(glyphQuad)
175
+ };
176
+ }
177
+ return {
178
+ pon: ptr.pon,
179
+ glyphQuad: segment.quad,
180
+ advance: segment.advance,
181
+ rect: segment.rect
182
+ };
183
+ }
184
+ /** Union box of a page's segments, or null when none have materialized. */
185
+ function pageBounds(pon) {
186
+ const segs = ctx.getState().segments[pon];
187
+ if (!segs || segs.length === 0) return null;
188
+ let x1 = Infinity;
189
+ let y1 = Infinity;
190
+ let x2 = -Infinity;
191
+ let y2 = -Infinity;
192
+ for (const s of segs) {
193
+ x1 = Math.min(x1, s.rect.x);
194
+ y1 = Math.min(y1, s.rect.y);
195
+ x2 = Math.max(x2, s.rect.x + s.rect.width);
196
+ y2 = Math.max(y2, s.rect.y + s.rect.height);
197
+ }
198
+ return {
199
+ x: x1,
200
+ y: y1,
201
+ width: x2 - x1,
202
+ height: y2 - y1
203
+ };
204
+ }
205
+ function menuAnchor() {
206
+ const sel = ctx.getState().selection;
207
+ if (!sel) return null;
208
+ const { end } = orderedEnds(sel);
209
+ let bounds = pageBounds(end.pon);
210
+ if (bounds) return {
211
+ pon: end.pon,
212
+ bounds
213
+ };
214
+ const pages = ctx.document()?.pages ?? [];
215
+ for (let i = pages.length - 1; i >= 0; i--) {
216
+ const pon = pages[i].pageObjectNumber;
217
+ bounds = pageBounds(pon);
218
+ if (bounds) return {
219
+ pon,
220
+ bounds
221
+ };
222
+ }
223
+ return null;
224
+ }
225
+ function snapshot() {
226
+ const { selection, segments } = ctx.getState();
227
+ const pages = Object.keys(segments).map(Number).filter((pon) => (segments[pon]?.length ?? 0) > 0).map((pon) => ({
228
+ pon,
229
+ segments: segments[pon]
230
+ }));
231
+ if (!selection) return {
232
+ pages,
233
+ start: null,
234
+ end: null,
235
+ direction: "forward",
236
+ range: null
237
+ };
238
+ const { start, end, direction } = orderedEnds(selection);
239
+ return {
240
+ pages,
241
+ start: endpointFor(start, "start"),
242
+ end: endpointFor(end, "end"),
243
+ direction,
244
+ range: {
245
+ start: {
246
+ pon: start.pon,
247
+ index: start.glyph
248
+ },
249
+ end: {
250
+ pon: end.pon,
251
+ index: end.glyph + 1
252
+ }
253
+ }
254
+ };
255
+ }
256
+ function ensurePage(pon) {
257
+ if (rawGeometry.has(pon) || pending.has(pon)) return;
258
+ if (!canSelect()) return;
259
+ const doc = ctx.doc;
260
+ if (!doc || !layoutOf(pon)) return;
261
+ pending.add(pon);
262
+ const at = epoch;
263
+ doc.page(pon).geometry.read().then((snapshot) => {
264
+ pending.delete(pon);
265
+ if (at !== epoch) return;
266
+ rawGeometry.set(pon, snapshot);
267
+ ctx.dispatch({
268
+ type: "PAGE_LOADED",
269
+ pon
270
+ });
271
+ if (ctx.getState().selection) recompute();
272
+ }, () => {
273
+ pending.delete(pon);
274
+ });
275
+ }
276
+ /** Clamp a pointer into its page's real character range once geometry is
277
+ * known — how `selectAll`'s open-ended focus settles. */
278
+ function clampPointer(ptr) {
279
+ const geom = geometryFor(ptr.pon);
280
+ if (!geom) return ptr;
281
+ const max = Math.max(geom.layout.glyphs.length - 1, 0);
282
+ const glyph = Math.max(0, Math.min(ptr.glyph, max));
283
+ return glyph === ptr.glyph ? ptr : {
284
+ pon: ptr.pon,
285
+ glyph
286
+ };
287
+ }
288
+ function recompute(sel = ctx.getState().selection) {
289
+ if (!sel) return;
290
+ const clamped = {
291
+ anchor: clampPointer(sel.anchor),
292
+ focus: clampPointer(sel.focus)
293
+ };
294
+ const { start, end } = orderedEnds(clamped);
295
+ const si = pageIndexOf(start.pon);
296
+ const ei = pageIndexOf(end.pon);
297
+ if (si < 0 || ei < 0) {
298
+ clearSelection();
299
+ return;
300
+ }
301
+ const segments = {};
302
+ for (let i = si; i <= ei; i++) {
303
+ const pon = ponAtIndex(i);
304
+ if (pon == null) continue;
305
+ const geom = geometryFor(pon);
306
+ if (!geom) {
307
+ ensurePage(pon);
308
+ continue;
309
+ }
310
+ const from = i === si ? start.glyph : 0;
311
+ const to = i === ei ? end.glyph : geom.layout.glyphs.length - 1;
312
+ segments[pon] = (0, _embedpdf_engine_core_runtime.textSegmentsForRange)(geom.layout, from, to - from + 1).map((s) => toContentSegment(geom, s));
313
+ }
314
+ ctx.dispatch({
315
+ type: "SET",
316
+ selection: clamped,
317
+ segments
318
+ });
319
+ fireChange();
320
+ }
321
+ /** Flip the gesture-in-flight FACT (see `SelectionState.selecting`). Set
322
+ * BEFORE the recompute that fires `onChange`, so change listeners always
323
+ * observe a coherent (selecting, segments) pair. */
324
+ function setSelecting(selecting) {
325
+ ctx.dispatch({
326
+ type: "SET_SELECTING",
327
+ selecting
328
+ });
329
+ }
330
+ function clearSelection() {
331
+ setSelecting(false);
332
+ ctx.dispatch({ type: "CLEAR" });
333
+ fireChange();
334
+ }
335
+ function selectSpanAt(pon, point, expand) {
336
+ const geom = geometryFor(pon);
337
+ if (!geom) return false;
338
+ const i = glyphAt(geom, point);
339
+ if (i == null) return false;
340
+ const [from, to] = expand === "word" ? (0, _embedpdf_engine_core_runtime.expandTextRangeToWord)(geom.layout, i) : (0, _embedpdf_engine_core_runtime.expandTextRangeToLine)(geom.layout, i);
341
+ setSelecting(true);
342
+ recompute({
343
+ anchor: {
344
+ pon,
345
+ glyph: from
346
+ },
347
+ focus: {
348
+ pon,
349
+ glyph: to
350
+ }
351
+ });
352
+ return true;
353
+ }
354
+ function assertCanSelect(context) {
355
+ if (!canSelect()) throw new _embedpdf_engine_core_runtime.PermissionDenied("doc.text.select", context);
356
+ }
357
+ /** The public programmatic entry: a half-open character range in. */
358
+ function select(input) {
359
+ assertCanSelect("selection.select");
360
+ const range = "pon" in input ? {
361
+ start: {
362
+ pon: input.pon,
363
+ index: input.start
364
+ },
365
+ end: {
366
+ pon: input.pon,
367
+ index: input.start + input.count
368
+ }
369
+ } : input;
370
+ const si = pageIndexOf(range.start.pon);
371
+ let ei = pageIndexOf(range.end.pon);
372
+ if (si < 0 || ei < 0) throw new Error(`select: unknown page object ${si < 0 ? range.start.pon : range.end.pon}`);
373
+ let endIndex = range.end.index;
374
+ if (ei < si || ei === si && endIndex <= range.start.index) {
375
+ clearSelection();
376
+ return;
377
+ }
378
+ if (endIndex === 0) {
379
+ ei -= 1;
380
+ if (ei < si) {
381
+ clearSelection();
382
+ return;
383
+ }
384
+ endIndex = Number.MAX_SAFE_INTEGER;
385
+ }
386
+ const focusPon = ponAtIndex(ei);
387
+ if (focusPon == null) throw new Error(`select: unknown page at index ${ei}`);
388
+ setSelecting(false);
389
+ recompute({
390
+ anchor: {
391
+ pon: range.start.pon,
392
+ glyph: Math.max(0, range.start.index)
393
+ },
394
+ focus: {
395
+ pon: focusPon,
396
+ glyph: endIndex - 1
397
+ }
398
+ });
399
+ }
400
+ function selectAll() {
401
+ assertCanSelect("selection.selectAll");
402
+ const pages = ctx.document()?.pages ?? [];
403
+ if (pages.length === 0) return;
404
+ setSelecting(false);
405
+ recompute({
406
+ anchor: {
407
+ pon: pages[0].pageObjectNumber,
408
+ glyph: 0
409
+ },
410
+ focus: {
411
+ pon: pages[pages.length - 1].pageObjectNumber,
412
+ glyph: Number.MAX_SAFE_INTEGER
413
+ }
414
+ });
415
+ }
416
+ /** Per-page text snapshot, cached as a PROMISE so concurrent readers
417
+ * share one fetch. Rejections are evicted (a denied or failed read must
418
+ * not poison the cache for a later authorized call). */
419
+ function pageTextSnapshot(pon) {
420
+ let p = textSnapshots.get(pon);
421
+ if (!p) {
422
+ const doc = ctx.doc;
423
+ if (!doc) return Promise.reject(/* @__PURE__ */ new Error("readText: document is not open"));
424
+ p = Promise.resolve(doc.page(pon).text.read());
425
+ p.catch(() => textSnapshots.delete(pon));
426
+ textSnapshots.set(pon, p);
427
+ }
428
+ return p;
429
+ }
430
+ async function readText() {
431
+ const sel = ctx.getState().selection;
432
+ if (!sel) return "";
433
+ if (!canCopy()) throw new _embedpdf_engine_core_runtime.PermissionDenied("doc.text.copy", "selection.readText");
434
+ const { start, end } = orderedEnds(sel);
435
+ const si = pageIndexOf(start.pon);
436
+ const ei = pageIndexOf(end.pon);
437
+ if (si < 0 || ei < 0) return "";
438
+ const spans = [];
439
+ for (let i = si; i <= ei; i++) {
440
+ const pon = ponAtIndex(i);
441
+ if (pon == null) continue;
442
+ spans.push({
443
+ pon,
444
+ from: i === si ? start.glyph : 0,
445
+ to: i === ei ? end.glyph + 1 : Number.MAX_SAFE_INTEGER
446
+ });
447
+ }
448
+ const parts = new Array(spans.length);
449
+ for (let base = 0; base < spans.length; base += TEXT_READ_CONCURRENCY) {
450
+ const batch = spans.slice(base, base + TEXT_READ_CONCURRENCY);
451
+ (await Promise.all(batch.map((s) => pageTextSnapshot(s.pon)))).forEach((snap, j) => {
452
+ parts[base + j] = (0, _embedpdf_engine_core_runtime.sliceTextByChars)(snap, batch[j].from, batch[j].to);
453
+ });
454
+ }
455
+ return parts.join("\n");
456
+ }
457
+ /** Structural registry change (rotate/move/delete/insert — `revision`
458
+ * bumped): drop caches for pages that left, then recompute. Rotation
459
+ * re-derives transforms via the layout key; a deleted endpoint page
460
+ * clears via recompute's registry check. Raw snapshots are NEVER
461
+ * refetched here — they are rotation-independent. */
462
+ function onPagesUpdated() {
463
+ const alive = new Set((ctx.document()?.pages ?? []).map((p) => p.pageObjectNumber));
464
+ for (const pon of [...rawGeometry.keys()]) if (!alive.has(pon)) {
465
+ rawGeometry.delete(pon);
466
+ derived.delete(pon);
467
+ textSnapshots.delete(pon);
468
+ }
469
+ if (ctx.getState().selection) recompute();
470
+ }
471
+ /** Page CONTENT changed (redaction apply / flatten): every cached
472
+ * snapshot — geometry AND text — is stale, and any live range points
473
+ * into a character space that no longer exists. Drop everything, clear. */
474
+ function invalidateContent() {
475
+ epoch++;
476
+ rawGeometry.clear();
477
+ derived.clear();
478
+ pending.clear();
479
+ textSnapshots.clear();
480
+ if (ctx.getState().selection) clearSelection();
481
+ }
482
+ let lastRevision = ctx.document()?.revision ?? -1;
483
+ const offStore = ctx.subscribe(() => {
484
+ const revision = ctx.document()?.revision;
485
+ if (revision === void 0 || revision === lastRevision) return;
486
+ lastRevision = revision;
487
+ onPagesUpdated();
488
+ });
489
+ ctx.cleanup(offStore);
490
+ const offEvents = ctx.doc?.events.subscribe((event) => {
491
+ if (event.type === "redaction.applied" || event.type === "pages.flattened") invalidateContent();
492
+ });
493
+ if (offEvents) ctx.cleanup(offEvents);
494
+ return {
495
+ canSelect,
496
+ canCopy,
497
+ select,
498
+ selectAll,
499
+ clear: clearSelection,
500
+ snapshot,
501
+ menuAnchor,
502
+ isSelecting: () => ctx.getState().selecting,
503
+ hasSelection: () => ctx.getState().selection != null,
504
+ selectedPages: () => {
505
+ const { segments } = ctx.getState();
506
+ return Object.keys(segments).map(Number).filter((pon) => (segments[pon]?.length ?? 0) > 0);
507
+ },
508
+ segmentsForPage: (pon) => ctx.getState().segments[pon] ?? EMPTY_SEGMENTS,
509
+ rectsForPage: (pon) => (ctx.getState().segments[pon] ?? EMPTY_SEGMENTS).map((s) => s.rect),
510
+ readText,
511
+ onChange: (cb) => {
512
+ changeCbs.add(cb);
513
+ return () => changeCbs.delete(cb);
514
+ },
515
+ onCommit: (cb) => {
516
+ commitCbs.add(cb);
517
+ return () => commitCbs.delete(cb);
518
+ },
519
+ ensurePage,
520
+ isLoaded: (pon) => !!ctx.getState().loaded[pon],
521
+ isOverText: (pon, point) => {
522
+ const geom = geometryFor(pon);
523
+ return geom ? glyphAt(geom, point) != null : false;
524
+ },
525
+ beginAt: (pon, point) => {
526
+ const geom = geometryFor(pon);
527
+ if (!geom) return false;
528
+ const i = glyphAt(geom, point);
529
+ if (i == null) return false;
530
+ setSelecting(true);
531
+ recompute({
532
+ anchor: {
533
+ pon,
534
+ glyph: i
535
+ },
536
+ focus: {
537
+ pon,
538
+ glyph: i
539
+ }
540
+ });
541
+ return true;
542
+ },
543
+ selectWordAt: (pon, point) => selectSpanAt(pon, point, "word"),
544
+ selectLineAt: (pon, point) => selectSpanAt(pon, point, "line"),
545
+ extendTo: (pon, point) => {
546
+ const cur = ctx.getState().selection;
547
+ if (!cur) return;
548
+ const geom = geometryFor(pon);
549
+ if (!geom) {
550
+ ensurePage(pon);
551
+ return;
552
+ }
553
+ const i = glyphAt(geom, point);
554
+ if (i == null) return;
555
+ recompute({
556
+ anchor: cur.anchor,
557
+ focus: {
558
+ pon,
559
+ glyph: i
560
+ }
561
+ });
562
+ },
563
+ end: () => {
564
+ setSelecting(false);
565
+ commitCbs.forEach((cb) => cb());
566
+ },
567
+ setHighlightVisible: (visible) => ctx.dispatch({
568
+ type: "SET_HIGHLIGHT_HIDDEN",
569
+ hidden: !visible
570
+ }),
571
+ highlightVisible: () => !ctx.getState().highlightHidden
572
+ };
573
+ }
574
+ //#endregion
575
+ //#region src/handler.ts
576
+ const CURSOR_TOKEN = "selection-text";
577
+ const DRAG_THRESHOLD_PX = 4;
578
+ /**
579
+ * The text-selection pointer handler. It is live only under tools that enable the
580
+ * `'text-select'` tag (the built-in `pointer` tool does; `pan` does not — so
581
+ * switching to pan disables text selection with zero special-casing here).
582
+ *
583
+ * - single click → deselect; records an anchor but selects NOTHING until
584
+ * the pointer moves past the drag threshold (Chrome/Acrobat feel)
585
+ * - single-click + drag → caret selection from the anchor (extends across pages)
586
+ * - double-click → select the word
587
+ * - triple-click → select the visual line
588
+ * - down off-text → deselect, and DON'T capture (so it can't block)
589
+ * - hover → I-beam only when over text, else the pointer cursor
590
+ */
591
+ function createTextSelectHandler(selection, interaction, feedback) {
592
+ let anchor = null;
593
+ let dragging = false;
594
+ return {
595
+ id: "text-select",
596
+ priority: 60,
597
+ enabledFor: (tool) => tool.enables.has("text-select"),
598
+ onDown: (s) => {
599
+ anchor = null;
600
+ dragging = false;
601
+ if (!s.page) return false;
602
+ const { pon, point } = s.page;
603
+ const clicks = s.clickCount ?? 1;
604
+ if (clicks >= 3) {
605
+ selection.selectLineAt(pon, point);
606
+ return true;
607
+ }
608
+ if (clicks === 2) {
609
+ if (selection.selectWordAt(pon, point) && s.gesture === "long-press") feedback?.selection();
610
+ return true;
611
+ }
612
+ selection.clear();
613
+ if (!selection.isOverText(pon, point)) return false;
614
+ anchor = {
615
+ pon,
616
+ point,
617
+ vx: s.viewport.x,
618
+ vy: s.viewport.y
619
+ };
620
+ return true;
621
+ },
622
+ onMove: (s) => {
623
+ if (!s.page || !anchor) return;
624
+ if (!dragging) {
625
+ if (Math.hypot(s.viewport.x - anchor.vx, s.viewport.y - anchor.vy) < DRAG_THRESHOLD_PX) return;
626
+ dragging = true;
627
+ selection.beginAt(anchor.pon, anchor.point);
628
+ }
629
+ selection.extendTo(s.page.pon, s.page.point);
630
+ },
631
+ onUp: () => {
632
+ anchor = null;
633
+ dragging = false;
634
+ selection.end();
635
+ },
636
+ onCancel: () => {
637
+ anchor = null;
638
+ dragging = false;
639
+ selection.clear();
640
+ selection.end();
641
+ },
642
+ onHover: (s) => {
643
+ if (!s.page) {
644
+ interaction.setCursor(CURSOR_TOKEN, null);
645
+ return;
646
+ }
647
+ selection.ensurePage(s.page.pon);
648
+ const overText = selection.isOverText(s.page.pon, s.page.point);
649
+ interaction.setCursor(CURSOR_TOKEN, overText ? "text" : null, 10);
650
+ }
651
+ };
652
+ }
653
+ //#endregion
654
+ //#region src/reducer.ts
655
+ const initialSelectionState = {
656
+ selection: null,
657
+ segments: {},
658
+ loaded: {},
659
+ highlightHidden: false,
660
+ selecting: false
661
+ };
662
+ const selectionReducer = (state, action) => {
663
+ switch (action.type) {
664
+ case "PAGE_LOADED": return state.loaded[action.pon] ? state : {
665
+ ...state,
666
+ loaded: {
667
+ ...state.loaded,
668
+ [action.pon]: true
669
+ }
670
+ };
671
+ case "SET": return {
672
+ ...state,
673
+ selection: action.selection,
674
+ segments: action.segments
675
+ };
676
+ case "CLEAR": return state.selection === null && Object.keys(state.segments).length === 0 ? state : {
677
+ ...state,
678
+ selection: null,
679
+ segments: {}
680
+ };
681
+ case "SET_HIGHLIGHT_HIDDEN": return state.highlightHidden === action.hidden ? state : {
682
+ ...state,
683
+ highlightHidden: action.hidden
684
+ };
685
+ case "SET_SELECTING": return state.selecting === action.selecting ? state : {
686
+ ...state,
687
+ selecting: action.selecting
688
+ };
689
+ default: return state;
690
+ }
691
+ };
692
+ //#endregion
693
+ Object.defineProperty(exports, "SelectionToken", {
694
+ enumerable: true,
695
+ get: function() {
696
+ return SelectionToken;
697
+ }
698
+ });
699
+ Object.defineProperty(exports, "buildSelectionPageGeometry", {
700
+ enumerable: true,
701
+ get: function() {
702
+ return buildSelectionPageGeometry;
703
+ }
704
+ });
705
+ Object.defineProperty(exports, "contentPointToPdf", {
706
+ enumerable: true,
707
+ get: function() {
708
+ return contentPointToPdf;
709
+ }
710
+ });
711
+ Object.defineProperty(exports, "createSelectionCapability", {
712
+ enumerable: true,
713
+ get: function() {
714
+ return createSelectionCapability;
715
+ }
716
+ });
717
+ Object.defineProperty(exports, "createTextSelectHandler", {
718
+ enumerable: true,
719
+ get: function() {
720
+ return createTextSelectHandler;
721
+ }
722
+ });
723
+ Object.defineProperty(exports, "initialSelectionState", {
724
+ enumerable: true,
725
+ get: function() {
726
+ return initialSelectionState;
727
+ }
728
+ });
729
+ Object.defineProperty(exports, "selectionReducer", {
730
+ enumerable: true,
731
+ get: function() {
732
+ return selectionReducer;
733
+ }
734
+ });
735
+ Object.defineProperty(exports, "toContentSegment", {
736
+ enumerable: true,
737
+ get: function() {
738
+ return toContentSegment;
739
+ }
740
+ });
741
+ Object.defineProperty(exports, "toContentTextQuad", {
742
+ enumerable: true,
743
+ get: function() {
744
+ return toContentTextQuad;
745
+ }
746
+ });
747
+
748
+ //# sourceMappingURL=reducer-dmDFWFVx.cjs.map