@embedpdf/plugin-selection 3.0.0-next.3 → 3.0.0-next.5
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 +20 -552
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -154
- package/dist/index.d.ts +13 -154
- package/dist/index.js +18 -541
- package/dist/index.js.map +1 -1
- package/dist/internal.cjs +11 -0
- package/dist/internal.d.cts +62 -0
- package/dist/internal.d.ts +62 -0
- package/dist/internal.js +2 -0
- package/dist/reducer-CZG2TZgo.js +688 -0
- package/dist/reducer-CZG2TZgo.js.map +1 -0
- package/dist/reducer-Dyf8p5h-.cjs +741 -0
- package/dist/reducer-Dyf8p5h-.cjs.map +1 -0
- package/dist/types-DtWaZIsm.d.cts +286 -0
- package/dist/types-DtWaZIsm.d.ts +286 -0
- package/package.json +9 -5
package/dist/index.js
CHANGED
|
@@ -1,552 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as createSelectionCapability, l as SelectionToken$1, n as selectionReducer, r as createTextSelectHandler, t as initialSelectionState } from "./reducer-CZG2TZgo.js";
|
|
2
|
+
import { definePlugin } from "@embedpdf/core";
|
|
2
3
|
import { InteractionToken } from "@embedpdf/plugin-interaction";
|
|
3
|
-
import { applyRect, boundsOfRects, pageGeometry } from "@embedpdf/core-geometry";
|
|
4
|
-
//#region src/geometry.ts
|
|
5
|
-
/**
|
|
6
|
-
* The pure selection geometry: engine text geometry (PDF user space, y-up) →
|
|
7
|
-
* viewer content space (y-down), glyph hit-testing, word/line expansion, and the
|
|
8
|
-
* line-merge. No DOM, no engine, no React.
|
|
9
|
-
*
|
|
10
|
-
* The non-trivial bits are ports of battle-tested algorithms, adapted to v3's
|
|
11
|
-
* content-space `Rect {x,y,width,height}`:
|
|
12
|
-
* - `glyphAt` — PDFium `GetIndexAtPos` (exact tight box, then a tolerance pass).
|
|
13
|
-
* - `rectsForRange` — Chromium `pdfium_range.cc` `MergeAdjacentRects` (one rect per line).
|
|
14
|
-
* - `expandToWord/Line` — Chromium `OnMultipleClick` (double = word, triple = line).
|
|
15
|
-
* The PDF↔content y-flip is the geometry package's `pageGeometry` (the one place
|
|
16
|
-
* that math lives), never hand-rolled here.
|
|
17
|
-
*/
|
|
18
|
-
const FLAG_EMPTY = 2;
|
|
19
|
-
const isBoundary = (flags) => (flags & 3) !== 0;
|
|
20
|
-
const isEmpty = (flags) => (flags & FLAG_EMPTY) !== 0;
|
|
21
|
-
const toContent = (m, b) => applyRect(m, {
|
|
22
|
-
x: b.left,
|
|
23
|
-
y: b.bottom,
|
|
24
|
-
width: b.right - b.left,
|
|
25
|
-
height: b.top - b.bottom
|
|
26
|
-
});
|
|
27
|
-
/**
|
|
28
|
-
* Flatten a page's text geometry into content-space glyphs + runs. Rotation does
|
|
29
|
-
* NOT enter here — the overlay rides the page's CSS rotation, so glyphs stay in
|
|
30
|
-
* un-rotated content space (the crop-relative y-flip is the only conversion).
|
|
31
|
-
*/
|
|
32
|
-
function buildPageText(snapshot, crop, rotation, userUnit) {
|
|
33
|
-
const { pdfToContent } = pageGeometry({
|
|
34
|
-
crop,
|
|
35
|
-
rotation,
|
|
36
|
-
userUnit
|
|
37
|
-
}, 1);
|
|
38
|
-
const glyphs = [];
|
|
39
|
-
const runs = [];
|
|
40
|
-
for (const run of snapshot.runs) {
|
|
41
|
-
const start = glyphs.length;
|
|
42
|
-
for (const g of run.glyphs) glyphs.push({
|
|
43
|
-
loose: toContent(pdfToContent, g.looseBox),
|
|
44
|
-
tight: g.tightBox ? toContent(pdfToContent, g.tightBox) : void 0,
|
|
45
|
-
flags: g.flags
|
|
46
|
-
});
|
|
47
|
-
runs.push({
|
|
48
|
-
start,
|
|
49
|
-
count: run.glyphs.length,
|
|
50
|
-
rect: toContent(pdfToContent, run.rect),
|
|
51
|
-
fontSize: run.fontSize
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
return {
|
|
55
|
-
glyphs,
|
|
56
|
-
runs
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
function avgGlyphHeight(text) {
|
|
60
|
-
let total = 0;
|
|
61
|
-
let count = 0;
|
|
62
|
-
for (const g of text.glyphs) {
|
|
63
|
-
if (isEmpty(g.flags)) continue;
|
|
64
|
-
total += g.loose.height;
|
|
65
|
-
count++;
|
|
66
|
-
}
|
|
67
|
-
return count === 0 ? 0 : total / count;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* The glyph index at a content-space point, or null when nothing is near (so the
|
|
71
|
-
* caller can show the pointer cursor off-text). PDFium `GetIndexAtPos`: exact
|
|
72
|
-
* tight-box containment first, then a tolerance pass (closest by Manhattan
|
|
73
|
-
* distance within `toleranceFactor × average glyph height`).
|
|
74
|
-
*/
|
|
75
|
-
function glyphAt(text, p, toleranceFactor = 1.5) {
|
|
76
|
-
for (const run of text.runs) {
|
|
77
|
-
const r = run.rect;
|
|
78
|
-
if (p.x < r.x || p.x > r.x + r.width || p.y < r.y || p.y > r.y + r.height) continue;
|
|
79
|
-
for (let i = 0; i < run.count; i++) {
|
|
80
|
-
const b = text.glyphs[run.start + i].tight ?? text.glyphs[run.start + i].loose;
|
|
81
|
-
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;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
if (toleranceFactor <= 0) return null;
|
|
85
|
-
const half = avgGlyphHeight(text) * toleranceFactor / 2;
|
|
86
|
-
let best = -1;
|
|
87
|
-
let bestDist = Infinity;
|
|
88
|
-
for (const run of text.runs) {
|
|
89
|
-
const r = run.rect;
|
|
90
|
-
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;
|
|
91
|
-
for (let i = 0; i < run.count; i++) {
|
|
92
|
-
const g = text.glyphs[run.start + i];
|
|
93
|
-
if (isEmpty(g.flags)) continue;
|
|
94
|
-
const b = g.tight ?? g.loose;
|
|
95
|
-
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;
|
|
96
|
-
const dx = Math.min(Math.abs(p.x - b.x), Math.abs(p.x - (b.x + b.width)));
|
|
97
|
-
const dy = Math.min(Math.abs(p.y - b.y), Math.abs(p.y - (b.y + b.height)));
|
|
98
|
-
if (dx + dy < bestDist) {
|
|
99
|
-
bestDist = dx + dy;
|
|
100
|
-
best = run.start + i;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
return best >= 0 ? best : null;
|
|
105
|
-
}
|
|
106
|
-
/** Double-click: the word around `i` (walk to space/empty glyphs both ways). */
|
|
107
|
-
function expandToWord(text, i) {
|
|
108
|
-
const n = text.glyphs.length;
|
|
109
|
-
if (i < 0 || i >= n) return [i, i];
|
|
110
|
-
let from = i;
|
|
111
|
-
while (from > 0 && !isBoundary(text.glyphs[from - 1].flags)) from--;
|
|
112
|
-
let to = i;
|
|
113
|
-
while (to < n - 1 && !isBoundary(text.glyphs[to + 1].flags)) to++;
|
|
114
|
-
return [from, to];
|
|
115
|
-
}
|
|
116
|
-
/** Triple-click: the full visual line — runs whose vertical extent overlaps the anchor run's. */
|
|
117
|
-
function expandToLine(text, i) {
|
|
118
|
-
const ri = text.runs.findIndex((r) => i >= r.start && i < r.start + r.count);
|
|
119
|
-
if (ri < 0) return [i, i];
|
|
120
|
-
const anchor = text.runs[ri];
|
|
121
|
-
const top = anchor.rect.y;
|
|
122
|
-
const bottom = anchor.rect.y + anchor.rect.height;
|
|
123
|
-
let from = anchor.start;
|
|
124
|
-
let to = anchor.start + anchor.count - 1;
|
|
125
|
-
for (let r = ri - 1; r >= 0; r--) {
|
|
126
|
-
const run = text.runs[r];
|
|
127
|
-
if (isZero(run.rect)) continue;
|
|
128
|
-
if (!overlapV(run.rect.y, run.rect.y + run.rect.height, top, bottom)) break;
|
|
129
|
-
from = run.start;
|
|
130
|
-
}
|
|
131
|
-
for (let r = ri + 1; r < text.runs.length; r++) {
|
|
132
|
-
const run = text.runs[r];
|
|
133
|
-
if (isZero(run.rect)) continue;
|
|
134
|
-
if (!overlapV(run.rect.y, run.rect.y + run.rect.height, top, bottom)) break;
|
|
135
|
-
to = run.start + run.count - 1;
|
|
136
|
-
}
|
|
137
|
-
return [from, to];
|
|
138
|
-
}
|
|
139
|
-
const CHAR_DISTANCE_FACTOR = 2.5;
|
|
140
|
-
const FONT_SIZE_RATIO_THRESHOLD = 1.5;
|
|
141
|
-
const VERTICAL_OVERLAP_THRESHOLD = .8;
|
|
142
|
-
const LINE_OVERLAP_THRESHOLD = .5;
|
|
143
|
-
function rectsForRange(text, from, to) {
|
|
144
|
-
const lo = Math.max(0, Math.min(from, to));
|
|
145
|
-
const hi = Math.min(text.glyphs.length - 1, Math.max(from, to));
|
|
146
|
-
const subRuns = [];
|
|
147
|
-
for (const run of text.runs) {
|
|
148
|
-
const runEnd = run.start + run.count - 1;
|
|
149
|
-
if (runEnd < lo || run.start > hi) continue;
|
|
150
|
-
const s = Math.max(lo, run.start);
|
|
151
|
-
const e = Math.min(hi, runEnd);
|
|
152
|
-
let minX = Infinity;
|
|
153
|
-
let maxX = -Infinity;
|
|
154
|
-
let minY = Infinity;
|
|
155
|
-
let maxY = -Infinity;
|
|
156
|
-
let charCount = 0;
|
|
157
|
-
let widthSum = 0;
|
|
158
|
-
let prevRight = -Infinity;
|
|
159
|
-
const flush = () => {
|
|
160
|
-
if (minX !== Infinity && charCount > 0) subRuns.push({
|
|
161
|
-
rect: {
|
|
162
|
-
x: minX,
|
|
163
|
-
y: minY,
|
|
164
|
-
width: maxX - minX,
|
|
165
|
-
height: maxY - minY
|
|
166
|
-
},
|
|
167
|
-
charCount,
|
|
168
|
-
fontSize: run.fontSize
|
|
169
|
-
});
|
|
170
|
-
minX = Infinity;
|
|
171
|
-
maxX = -Infinity;
|
|
172
|
-
minY = Infinity;
|
|
173
|
-
maxY = -Infinity;
|
|
174
|
-
charCount = 0;
|
|
175
|
-
widthSum = 0;
|
|
176
|
-
prevRight = -Infinity;
|
|
177
|
-
};
|
|
178
|
-
for (let gi = s; gi <= e; gi++) {
|
|
179
|
-
const g = text.glyphs[gi];
|
|
180
|
-
if (isEmpty(g.flags)) continue;
|
|
181
|
-
const b = g.loose;
|
|
182
|
-
if (charCount > 0 && prevRight > -Infinity) {
|
|
183
|
-
const avg = widthSum / charCount;
|
|
184
|
-
if (avg > 0 && Math.abs(b.x - prevRight) > CHAR_DISTANCE_FACTOR * avg) flush();
|
|
185
|
-
}
|
|
186
|
-
minX = Math.min(minX, b.x);
|
|
187
|
-
maxX = Math.max(maxX, b.x + b.width);
|
|
188
|
-
minY = Math.min(minY, b.y);
|
|
189
|
-
maxY = Math.max(maxY, b.y + b.height);
|
|
190
|
-
charCount++;
|
|
191
|
-
widthSum += b.width;
|
|
192
|
-
prevRight = b.x + b.width;
|
|
193
|
-
}
|
|
194
|
-
flush();
|
|
195
|
-
}
|
|
196
|
-
return mergeAdjacentRects(subRuns);
|
|
197
|
-
}
|
|
198
|
-
function mergeAdjacentRects(runs) {
|
|
199
|
-
const out = [];
|
|
200
|
-
let prev = null;
|
|
201
|
-
let cur = null;
|
|
202
|
-
for (const run of runs) {
|
|
203
|
-
if (prev && cur && shouldMerge(prev, run)) cur = boundsOfRects([cur, run.rect]);
|
|
204
|
-
else {
|
|
205
|
-
if (cur) out.push(cur);
|
|
206
|
-
cur = run.rect;
|
|
207
|
-
}
|
|
208
|
-
prev = run;
|
|
209
|
-
}
|
|
210
|
-
if (cur && cur.width > 0 && cur.height > 0) out.push(cur);
|
|
211
|
-
return out;
|
|
212
|
-
}
|
|
213
|
-
function shouldMerge(a, b) {
|
|
214
|
-
if (a.fontSize != null && b.fontSize != null && a.fontSize > 0 && b.fontSize > 0) {
|
|
215
|
-
if (Math.max(a.fontSize, b.fontSize) / Math.min(a.fontSize, b.fontSize) > FONT_SIZE_RATIO_THRESHOLD) return false;
|
|
216
|
-
}
|
|
217
|
-
if (verticalOverlap(a.rect, b.rect) < VERTICAL_OVERLAP_THRESHOLD) return false;
|
|
218
|
-
const aw = a.rect.width / a.charCount;
|
|
219
|
-
const bw = b.rect.width / b.charCount;
|
|
220
|
-
const aL = a.rect.x - aw;
|
|
221
|
-
const aR = a.rect.x + a.rect.width + aw;
|
|
222
|
-
const bL = b.rect.x - bw;
|
|
223
|
-
return aL < b.rect.x + b.rect.width + bw && aR > bL;
|
|
224
|
-
}
|
|
225
|
-
function verticalOverlap(a, b) {
|
|
226
|
-
if (a.height <= 0 || b.height <= 0) return 0;
|
|
227
|
-
const u = Math.max(a.y + a.height, b.y + b.height) - Math.min(a.y, b.y);
|
|
228
|
-
if (u === a.height || u === b.height) return 1;
|
|
229
|
-
return Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)) / u;
|
|
230
|
-
}
|
|
231
|
-
const isZero = (r) => r.width === 0 && r.height === 0;
|
|
232
|
-
function overlapV(top1, bottom1, top2, bottom2) {
|
|
233
|
-
const u = Math.max(bottom1, bottom2) - Math.min(top1, top2);
|
|
234
|
-
if (u === 0) return false;
|
|
235
|
-
return Math.max(0, Math.min(bottom1, bottom2) - Math.max(top1, top2)) / u >= LINE_OVERLAP_THRESHOLD;
|
|
236
|
-
}
|
|
237
|
-
//#endregion
|
|
238
|
-
//#region src/capability.ts
|
|
239
|
-
const EMPTY = [];
|
|
240
|
-
/**
|
|
241
|
-
* The selection capability. The reducer state holds the selection range, the
|
|
242
|
-
* derived content-space rects (per page), and per-page loaded flags; the (large,
|
|
243
|
-
* non-serializable) per-page text geometry is cached HERE in the closure.
|
|
244
|
-
*
|
|
245
|
-
* Selection is cross-page: glyphs are ordered globally by (pageIndex, glyph), so
|
|
246
|
-
* a drag from page 2 into page 4 selects the tail of 2, all of 3, and the head of
|
|
247
|
-
* 4. `recompute` rebuilds the merged line rects for every loaded page in the span
|
|
248
|
-
* and re-runs whenever a mid-span page finishes loading.
|
|
249
|
-
*/
|
|
250
|
-
function createSelectionCapability(ctx) {
|
|
251
|
-
const cache = /* @__PURE__ */ new Map();
|
|
252
|
-
const pending = /* @__PURE__ */ new Set();
|
|
253
|
-
const changeCbs = /* @__PURE__ */ new Set();
|
|
254
|
-
const commitCbs = /* @__PURE__ */ new Set();
|
|
255
|
-
const fireChange = () => changeCbs.forEach((cb) => cb());
|
|
256
|
-
const pageIndexOf = (pon) => ctx.document()?.pages.findIndex((p) => p.pageObjectNumber === pon) ?? -1;
|
|
257
|
-
const ponAtIndex = (i) => ctx.document()?.pages[i]?.pageObjectNumber;
|
|
258
|
-
function orderedEnds(sel) {
|
|
259
|
-
const ai = pageIndexOf(sel.anchor.pon);
|
|
260
|
-
const fi = pageIndexOf(sel.focus.pon);
|
|
261
|
-
return ai < fi || ai === fi && sel.anchor.glyph <= sel.focus.glyph ? {
|
|
262
|
-
start: sel.anchor,
|
|
263
|
-
end: sel.focus,
|
|
264
|
-
direction: "forward"
|
|
265
|
-
} : {
|
|
266
|
-
start: sel.focus,
|
|
267
|
-
end: sel.anchor,
|
|
268
|
-
direction: "backward"
|
|
269
|
-
};
|
|
270
|
-
}
|
|
271
|
-
function endpointFor(ptr, which) {
|
|
272
|
-
const rects = ctx.getState().rects[ptr.pon] ?? EMPTY;
|
|
273
|
-
if (!rects.length) return null;
|
|
274
|
-
return {
|
|
275
|
-
pon: ptr.pon,
|
|
276
|
-
rect: which === "start" ? rects[0] : rects[rects.length - 1]
|
|
277
|
-
};
|
|
278
|
-
}
|
|
279
|
-
function snapshot() {
|
|
280
|
-
const { selection, rects } = ctx.getState();
|
|
281
|
-
const pages = Object.keys(rects).map(Number).filter((pon) => (rects[pon]?.length ?? 0) > 0).map((pon) => ({
|
|
282
|
-
pon,
|
|
283
|
-
rects: rects[pon]
|
|
284
|
-
}));
|
|
285
|
-
if (!selection) return {
|
|
286
|
-
pages,
|
|
287
|
-
start: null,
|
|
288
|
-
end: null,
|
|
289
|
-
direction: "forward"
|
|
290
|
-
};
|
|
291
|
-
const { start, end, direction } = orderedEnds(selection);
|
|
292
|
-
return {
|
|
293
|
-
pages,
|
|
294
|
-
start: endpointFor(start, "start"),
|
|
295
|
-
end: endpointFor(end, "end"),
|
|
296
|
-
direction
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
function ensurePage(pon) {
|
|
300
|
-
if (cache.has(pon) || pending.has(pon)) return;
|
|
301
|
-
const doc = ctx.doc;
|
|
302
|
-
const layout = ctx.document()?.pages.find((p) => p.pageObjectNumber === pon);
|
|
303
|
-
if (!doc || !layout) return;
|
|
304
|
-
pending.add(pon);
|
|
305
|
-
doc.page(pon).geometry.read().then((snapshot) => {
|
|
306
|
-
pending.delete(pon);
|
|
307
|
-
cache.set(pon, buildPageText(snapshot, layout.boxes.crop, layout.rotation, layout.userUnit));
|
|
308
|
-
ctx.dispatch({
|
|
309
|
-
type: "PAGE_LOADED",
|
|
310
|
-
pon
|
|
311
|
-
});
|
|
312
|
-
if (ctx.getState().selection) recompute();
|
|
313
|
-
}, () => {
|
|
314
|
-
pending.delete(pon);
|
|
315
|
-
});
|
|
316
|
-
}
|
|
317
|
-
function recompute(sel = ctx.getState().selection) {
|
|
318
|
-
if (!sel) return;
|
|
319
|
-
const { start, end } = orderedEnds(sel);
|
|
320
|
-
const si = pageIndexOf(start.pon);
|
|
321
|
-
const ei = pageIndexOf(end.pon);
|
|
322
|
-
if (si < 0 || ei < 0) return;
|
|
323
|
-
const rects = {};
|
|
324
|
-
for (let i = si; i <= ei; i++) {
|
|
325
|
-
const pon = ponAtIndex(i);
|
|
326
|
-
if (pon == null) continue;
|
|
327
|
-
const text = cache.get(pon);
|
|
328
|
-
if (!text) {
|
|
329
|
-
ensurePage(pon);
|
|
330
|
-
continue;
|
|
331
|
-
}
|
|
332
|
-
rects[pon] = rectsForRange(text, i === si ? start.glyph : 0, i === ei ? end.glyph : text.glyphs.length - 1);
|
|
333
|
-
}
|
|
334
|
-
ctx.dispatch({
|
|
335
|
-
type: "SET",
|
|
336
|
-
selection: sel,
|
|
337
|
-
rects
|
|
338
|
-
});
|
|
339
|
-
fireChange();
|
|
340
|
-
}
|
|
341
|
-
function selectSpan(pon, point, expand) {
|
|
342
|
-
const text = cache.get(pon);
|
|
343
|
-
if (!text) return;
|
|
344
|
-
const i = glyphAt(text, point);
|
|
345
|
-
if (i == null) return;
|
|
346
|
-
const [from, to] = expand === "word" ? expandToWord(text, i) : expandToLine(text, i);
|
|
347
|
-
recompute({
|
|
348
|
-
anchor: {
|
|
349
|
-
pon,
|
|
350
|
-
glyph: from
|
|
351
|
-
},
|
|
352
|
-
focus: {
|
|
353
|
-
pon,
|
|
354
|
-
glyph: to
|
|
355
|
-
}
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
return {
|
|
359
|
-
ensurePage,
|
|
360
|
-
isLoaded: (pon) => !!ctx.getState().loaded[pon],
|
|
361
|
-
isOverText: (pon, point) => {
|
|
362
|
-
const text = cache.get(pon);
|
|
363
|
-
return text ? glyphAt(text, point) != null : false;
|
|
364
|
-
},
|
|
365
|
-
beginAt: (pon, point) => {
|
|
366
|
-
const text = cache.get(pon);
|
|
367
|
-
if (!text) return false;
|
|
368
|
-
const i = glyphAt(text, point);
|
|
369
|
-
if (i == null) return false;
|
|
370
|
-
recompute({
|
|
371
|
-
anchor: {
|
|
372
|
-
pon,
|
|
373
|
-
glyph: i
|
|
374
|
-
},
|
|
375
|
-
focus: {
|
|
376
|
-
pon,
|
|
377
|
-
glyph: i
|
|
378
|
-
}
|
|
379
|
-
});
|
|
380
|
-
return true;
|
|
381
|
-
},
|
|
382
|
-
selectWord: (pon, point) => selectSpan(pon, point, "word"),
|
|
383
|
-
selectLine: (pon, point) => selectSpan(pon, point, "line"),
|
|
384
|
-
extendTo: (pon, point) => {
|
|
385
|
-
const cur = ctx.getState().selection;
|
|
386
|
-
if (!cur) return;
|
|
387
|
-
const text = cache.get(pon);
|
|
388
|
-
if (!text) {
|
|
389
|
-
ensurePage(pon);
|
|
390
|
-
return;
|
|
391
|
-
}
|
|
392
|
-
const i = glyphAt(text, point);
|
|
393
|
-
if (i == null) return;
|
|
394
|
-
recompute({
|
|
395
|
-
anchor: cur.anchor,
|
|
396
|
-
focus: {
|
|
397
|
-
pon,
|
|
398
|
-
glyph: i
|
|
399
|
-
}
|
|
400
|
-
});
|
|
401
|
-
},
|
|
402
|
-
end: () => commitCbs.forEach((cb) => cb()),
|
|
403
|
-
clear: () => {
|
|
404
|
-
ctx.dispatch({ type: "CLEAR" });
|
|
405
|
-
fireChange();
|
|
406
|
-
},
|
|
407
|
-
snapshot,
|
|
408
|
-
rectsForPage: (pon) => ctx.getState().rects[pon] ?? EMPTY,
|
|
409
|
-
hasSelection: () => ctx.getState().selection != null,
|
|
410
|
-
selectedPages: () => {
|
|
411
|
-
const { rects } = ctx.getState();
|
|
412
|
-
return Object.keys(rects).map(Number).filter((pon) => (rects[pon]?.length ?? 0) > 0);
|
|
413
|
-
},
|
|
414
|
-
onChange: (cb) => {
|
|
415
|
-
changeCbs.add(cb);
|
|
416
|
-
return () => changeCbs.delete(cb);
|
|
417
|
-
},
|
|
418
|
-
onCommit: (cb) => {
|
|
419
|
-
commitCbs.add(cb);
|
|
420
|
-
return () => commitCbs.delete(cb);
|
|
421
|
-
},
|
|
422
|
-
setHighlightVisible: (visible) => ctx.dispatch({
|
|
423
|
-
type: "SET_HIGHLIGHT_HIDDEN",
|
|
424
|
-
hidden: !visible
|
|
425
|
-
}),
|
|
426
|
-
highlightVisible: () => !ctx.getState().highlightHidden
|
|
427
|
-
};
|
|
428
|
-
}
|
|
429
|
-
//#endregion
|
|
430
|
-
//#region src/handler.ts
|
|
431
|
-
const CURSOR_TOKEN = "selection-text";
|
|
432
|
-
const DRAG_THRESHOLD_PX = 4;
|
|
433
|
-
/**
|
|
434
|
-
* The text-selection pointer handler. It is live only under tools that enable the
|
|
435
|
-
* `'text-select'` tag (the built-in `pointer` tool does; `pan` does not — so
|
|
436
|
-
* switching to pan disables text selection with zero special-casing here).
|
|
437
|
-
*
|
|
438
|
-
* - single click → deselect; records an anchor but selects NOTHING until
|
|
439
|
-
* the pointer moves past the drag threshold (Chrome/Acrobat feel)
|
|
440
|
-
* - single-click + drag → caret selection from the anchor (extends across pages)
|
|
441
|
-
* - double-click → select the word
|
|
442
|
-
* - triple-click → select the visual line
|
|
443
|
-
* - down off-text → deselect, and DON'T capture (so it can't block)
|
|
444
|
-
* - hover → I-beam only when over text, else the pointer cursor
|
|
445
|
-
*/
|
|
446
|
-
function createTextSelectHandler(selection, interaction) {
|
|
447
|
-
let anchor = null;
|
|
448
|
-
let dragging = false;
|
|
449
|
-
return {
|
|
450
|
-
id: "text-select",
|
|
451
|
-
priority: 60,
|
|
452
|
-
enabledFor: (tool) => tool.enables.has("text-select"),
|
|
453
|
-
onDown: (s) => {
|
|
454
|
-
anchor = null;
|
|
455
|
-
dragging = false;
|
|
456
|
-
if (!s.page) return false;
|
|
457
|
-
const { pon, point } = s.page;
|
|
458
|
-
const clicks = s.clickCount ?? 1;
|
|
459
|
-
if (clicks >= 3) {
|
|
460
|
-
selection.selectLine(pon, point);
|
|
461
|
-
return true;
|
|
462
|
-
}
|
|
463
|
-
if (clicks === 2) {
|
|
464
|
-
selection.selectWord(pon, point);
|
|
465
|
-
return true;
|
|
466
|
-
}
|
|
467
|
-
selection.clear();
|
|
468
|
-
if (!selection.isOverText(pon, point)) return false;
|
|
469
|
-
anchor = {
|
|
470
|
-
pon,
|
|
471
|
-
point,
|
|
472
|
-
vx: s.viewport.x,
|
|
473
|
-
vy: s.viewport.y
|
|
474
|
-
};
|
|
475
|
-
return true;
|
|
476
|
-
},
|
|
477
|
-
onMove: (s) => {
|
|
478
|
-
if (!s.page || !anchor) return;
|
|
479
|
-
if (!dragging) {
|
|
480
|
-
if (Math.hypot(s.viewport.x - anchor.vx, s.viewport.y - anchor.vy) < DRAG_THRESHOLD_PX) return;
|
|
481
|
-
dragging = true;
|
|
482
|
-
selection.beginAt(anchor.pon, anchor.point);
|
|
483
|
-
}
|
|
484
|
-
selection.extendTo(s.page.pon, s.page.point);
|
|
485
|
-
},
|
|
486
|
-
onUp: () => {
|
|
487
|
-
anchor = null;
|
|
488
|
-
dragging = false;
|
|
489
|
-
selection.end();
|
|
490
|
-
},
|
|
491
|
-
onHover: (s) => {
|
|
492
|
-
if (!s.page) {
|
|
493
|
-
interaction.setCursor(CURSOR_TOKEN, null);
|
|
494
|
-
return;
|
|
495
|
-
}
|
|
496
|
-
selection.ensurePage(s.page.pon);
|
|
497
|
-
const overText = selection.isOverText(s.page.pon, s.page.point);
|
|
498
|
-
interaction.setCursor(CURSOR_TOKEN, overText ? "text" : null, 10);
|
|
499
|
-
}
|
|
500
|
-
};
|
|
501
|
-
}
|
|
502
|
-
//#endregion
|
|
503
|
-
//#region src/reducer.ts
|
|
504
|
-
const initialSelectionState = {
|
|
505
|
-
selection: null,
|
|
506
|
-
rects: {},
|
|
507
|
-
loaded: {},
|
|
508
|
-
highlightHidden: false
|
|
509
|
-
};
|
|
510
|
-
const selectionReducer = (state, action) => {
|
|
511
|
-
switch (action.type) {
|
|
512
|
-
case "PAGE_LOADED": return state.loaded[action.pon] ? state : {
|
|
513
|
-
...state,
|
|
514
|
-
loaded: {
|
|
515
|
-
...state.loaded,
|
|
516
|
-
[action.pon]: true
|
|
517
|
-
}
|
|
518
|
-
};
|
|
519
|
-
case "SET": return {
|
|
520
|
-
...state,
|
|
521
|
-
selection: action.selection,
|
|
522
|
-
rects: action.rects
|
|
523
|
-
};
|
|
524
|
-
case "CLEAR": return state.selection === null && Object.keys(state.rects).length === 0 ? state : {
|
|
525
|
-
...state,
|
|
526
|
-
selection: null,
|
|
527
|
-
rects: {}
|
|
528
|
-
};
|
|
529
|
-
case "SET_HIGHLIGHT_HIDDEN": return state.highlightHidden === action.hidden ? state : {
|
|
530
|
-
...state,
|
|
531
|
-
highlightHidden: action.hidden
|
|
532
|
-
};
|
|
533
|
-
default: return state;
|
|
534
|
-
}
|
|
535
|
-
};
|
|
536
|
-
//#endregion
|
|
537
|
-
//#region src/types.ts
|
|
538
|
-
const SelectionToken = createCapabilityToken("selection");
|
|
539
|
-
//#endregion
|
|
540
4
|
//#region src/selection.plugin.ts
|
|
541
5
|
/**
|
|
542
6
|
* Text selection — document-scoped, requires the interaction hub. In `init` it
|
|
543
7
|
* registers ITS pointer handler with the hub; the hub owns the pointer stream
|
|
544
8
|
* and arbitration. Works with `<Stage>` or a standalone `<PageView>` — selection
|
|
545
9
|
* only needs the page coordinate context + the engine's text geometry.
|
|
10
|
+
*
|
|
11
|
+
* Registry/content invalidation is wired inside the capability itself
|
|
12
|
+
* (revision watch + document event subscription), so headless/programmatic
|
|
13
|
+
* use gets the same reconciliation as the full viewer.
|
|
546
14
|
*/
|
|
547
15
|
const selectionPlugin = () => definePlugin({
|
|
548
16
|
id: "selection",
|
|
549
|
-
token: SelectionToken,
|
|
17
|
+
token: SelectionToken$1,
|
|
550
18
|
scope: "document",
|
|
551
19
|
requires: [InteractionToken],
|
|
552
20
|
initialState: initialSelectionState,
|
|
@@ -554,11 +22,20 @@ const selectionPlugin = () => definePlugin({
|
|
|
554
22
|
capability: createSelectionCapability,
|
|
555
23
|
init: (ctx) => {
|
|
556
24
|
const interaction = ctx.get(InteractionToken);
|
|
557
|
-
const selection = ctx.get(SelectionToken);
|
|
25
|
+
const selection = ctx.get(SelectionToken$1);
|
|
558
26
|
interaction.registerHandler(createTextSelectHandler(selection, interaction));
|
|
559
27
|
}
|
|
560
28
|
});
|
|
561
29
|
//#endregion
|
|
562
|
-
|
|
30
|
+
//#region src/index.ts
|
|
31
|
+
/**
|
|
32
|
+
* The selection capability token, narrowed to the public
|
|
33
|
+
* {@link SelectionCapability} lens. It is the SAME runtime token the plugin
|
|
34
|
+
* provides — the host-only surface (pointer gestures, geometry warming) is
|
|
35
|
+
* reachable only via `@embedpdf/plugin-selection/internal`.
|
|
36
|
+
*/
|
|
37
|
+
const SelectionToken = SelectionToken$1;
|
|
38
|
+
//#endregion
|
|
39
|
+
export { SelectionToken, selectionPlugin };
|
|
563
40
|
|
|
564
41
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/geometry.ts","../src/capability.ts","../src/handler.ts","../src/reducer.ts","../src/types.ts","../src/selection.plugin.ts"],"sourcesContent":["/**\n * The pure selection geometry: engine text geometry (PDF user space, y-up) →\n * viewer content space (y-down), glyph hit-testing, word/line expansion, and the\n * line-merge. No DOM, no engine, no React.\n *\n * The non-trivial bits are ports of battle-tested algorithms, adapted to v3's\n * content-space `Rect {x,y,width,height}`:\n * - `glyphAt` — PDFium `GetIndexAtPos` (exact tight box, then a tolerance pass).\n * - `rectsForRange` — Chromium `pdfium_range.cc` `MergeAdjacentRects` (one rect per line).\n * - `expandToWord/Line` — Chromium `OnMultipleClick` (double = word, triple = line).\n * The PDF↔content y-flip is the geometry package's `pageGeometry` (the one place\n * that math lives), never hand-rolled here.\n */\nimport {\n applyRect,\n boundsOfRects,\n pageGeometry,\n type Point,\n type Rect,\n type RectIn,\n} from '@embedpdf/core-geometry';\nimport type { PageGeometrySnapshot, PdfRect } from '@embedpdf/engine-core/runtime';\n\nconst FLAG_SPACE = 1;\nconst FLAG_EMPTY = 2;\nconst isBoundary = (flags: number): boolean => (flags & (FLAG_SPACE | FLAG_EMPTY)) !== 0;\nconst isEmpty = (flags: number): boolean => (flags & FLAG_EMPTY) !== 0;\n\n/** One glyph in content space. `loose` builds selection rects; `tight` hit-tests. */\nexport interface GlyphInfo {\n loose: Rect;\n tight?: Rect;\n flags: number;\n}\n\n/** A contiguous run of glyphs (a text object). `rect` is its loose enclosing box. */\nexport interface RunInfo {\n start: number; // index into PageText.glyphs (the selection coordinate)\n count: number;\n rect: Rect;\n fontSize?: number;\n}\n\n/** A page's text laid out in content space: a flat glyph list + the run structure. */\nexport interface PageText {\n glyphs: GlyphInfo[];\n runs: RunInfo[];\n}\n\nconst toContent = (m: Parameters<typeof applyRect>[0], b: PdfRect): Rect =>\n applyRect(\n m as never,\n {\n x: b.left,\n y: b.bottom,\n width: b.right - b.left,\n height: b.top - b.bottom,\n } as RectIn<'pdf'>,\n ) as Rect;\n\n/**\n * Flatten a page's text geometry into content-space glyphs + runs. Rotation does\n * NOT enter here — the overlay rides the page's CSS rotation, so glyphs stay in\n * un-rotated content space (the crop-relative y-flip is the only conversion).\n */\nexport function buildPageText(\n snapshot: PageGeometrySnapshot,\n crop: PdfRect,\n rotation: 0 | 90 | 180 | 270,\n userUnit: number,\n): PageText {\n // zoom = 1: pdfToContent is scale-free (just the y-flip); the viewer's zoom is\n // applied later by PageTransform.pageToContent, not baked in.\n const { pdfToContent } = pageGeometry({ crop, rotation, userUnit }, 1);\n const glyphs: GlyphInfo[] = [];\n const runs: RunInfo[] = [];\n for (const run of snapshot.runs) {\n const start = glyphs.length;\n for (const g of run.glyphs) {\n glyphs.push({\n loose: toContent(pdfToContent, g.looseBox),\n tight: g.tightBox ? toContent(pdfToContent, g.tightBox) : undefined,\n flags: g.flags,\n });\n }\n runs.push({\n start,\n count: run.glyphs.length,\n rect: toContent(pdfToContent, run.rect),\n fontSize: run.fontSize,\n });\n }\n return { glyphs, runs };\n}\n\nfunction avgGlyphHeight(text: PageText): number {\n let total = 0;\n let count = 0;\n for (const g of text.glyphs) {\n if (isEmpty(g.flags)) continue;\n total += g.loose.height;\n count++;\n }\n return count === 0 ? 0 : total / count;\n}\n\n/**\n * The glyph index at a content-space point, or null when nothing is near (so the\n * caller can show the pointer cursor off-text). PDFium `GetIndexAtPos`: exact\n * tight-box containment first, then a tolerance pass (closest by Manhattan\n * distance within `toleranceFactor × average glyph height`).\n */\nexport function glyphAt(text: PageText, p: Point, toleranceFactor = 1.5): number | null {\n for (const run of text.runs) {\n const r = run.rect;\n if (p.x < r.x || p.x > r.x + r.width || p.y < r.y || p.y > r.y + r.height) continue;\n for (let i = 0; i < run.count; i++) {\n const b = text.glyphs[run.start + i].tight ?? text.glyphs[run.start + i].loose;\n if (p.x >= b.x && p.x <= b.x + b.width && p.y >= b.y && p.y <= b.y + b.height) {\n return run.start + i;\n }\n }\n }\n if (toleranceFactor <= 0) return null;\n\n const half = (avgGlyphHeight(text) * toleranceFactor) / 2;\n let best = -1;\n let bestDist = Infinity;\n for (const run of text.runs) {\n const r = run.rect;\n if (\n p.y < r.y - half ||\n p.y > r.y + r.height + half ||\n p.x < r.x - half ||\n p.x > r.x + r.width + half\n ) {\n continue;\n }\n for (let i = 0; i < run.count; i++) {\n const g = text.glyphs[run.start + i];\n if (isEmpty(g.flags)) continue;\n const b = g.tight ?? g.loose;\n if (\n p.x < b.x - half ||\n p.x > b.x + b.width + half ||\n p.y < b.y - half ||\n p.y > b.y + b.height + half\n ) {\n continue;\n }\n const dx = Math.min(Math.abs(p.x - b.x), Math.abs(p.x - (b.x + b.width)));\n const dy = Math.min(Math.abs(p.y - b.y), Math.abs(p.y - (b.y + b.height)));\n if (dx + dy < bestDist) {\n bestDist = dx + dy;\n best = run.start + i;\n }\n }\n }\n return best >= 0 ? best : null;\n}\n\n/** Double-click: the word around `i` (walk to space/empty glyphs both ways). */\nexport function expandToWord(text: PageText, i: number): [number, number] {\n const n = text.glyphs.length;\n if (i < 0 || i >= n) return [i, i];\n let from = i;\n while (from > 0 && !isBoundary(text.glyphs[from - 1].flags)) from--;\n let to = i;\n while (to < n - 1 && !isBoundary(text.glyphs[to + 1].flags)) to++;\n return [from, to];\n}\n\n/** Triple-click: the full visual line — runs whose vertical extent overlaps the anchor run's. */\nexport function expandToLine(text: PageText, i: number): [number, number] {\n const ri = text.runs.findIndex((r) => i >= r.start && i < r.start + r.count);\n if (ri < 0) return [i, i];\n const anchor = text.runs[ri];\n const top = anchor.rect.y;\n const bottom = anchor.rect.y + anchor.rect.height;\n let from = anchor.start;\n let to = anchor.start + anchor.count - 1;\n for (let r = ri - 1; r >= 0; r--) {\n const run = text.runs[r];\n if (isZero(run.rect)) continue;\n if (!overlapV(run.rect.y, run.rect.y + run.rect.height, top, bottom)) break;\n from = run.start;\n }\n for (let r = ri + 1; r < text.runs.length; r++) {\n const run = text.runs[r];\n if (isZero(run.rect)) continue;\n if (!overlapV(run.rect.y, run.rect.y + run.rect.height, top, bottom)) break;\n to = run.start + run.count - 1;\n }\n return [from, to];\n}\n\n/* ── line-merge ────────────────────────────────────────────────────────────\n * Adapted from Chromium's pdf/pdfium/pdfium_range.cc (BSD-licensed,\n * Copyright 2010 The Chromium Authors). Glyphs → sub-runs (split on big intra-run\n * gaps) → merged line rects. */\n\nconst CHAR_DISTANCE_FACTOR = 2.5;\nconst FONT_SIZE_RATIO_THRESHOLD = 1.5;\nconst VERTICAL_OVERLAP_THRESHOLD = 0.8;\nconst LINE_OVERLAP_THRESHOLD = 0.5;\n\ninterface SubRun {\n rect: Rect;\n charCount: number;\n fontSize?: number;\n}\n\nexport function rectsForRange(text: PageText, from: number, to: number): Rect[] {\n const lo = Math.max(0, Math.min(from, to));\n const hi = Math.min(text.glyphs.length - 1, Math.max(from, to));\n const subRuns: SubRun[] = [];\n\n for (const run of text.runs) {\n const runEnd = run.start + run.count - 1;\n if (runEnd < lo || run.start > hi) continue;\n const s = Math.max(lo, run.start);\n const e = Math.min(hi, runEnd);\n\n let minX = Infinity;\n let maxX = -Infinity;\n let minY = Infinity;\n let maxY = -Infinity;\n let charCount = 0;\n let widthSum = 0;\n let prevRight = -Infinity;\n const flush = () => {\n if (minX !== Infinity && charCount > 0) {\n subRuns.push({\n rect: { x: minX, y: minY, width: maxX - minX, height: maxY - minY },\n charCount,\n fontSize: run.fontSize,\n });\n }\n minX = Infinity;\n maxX = -Infinity;\n minY = Infinity;\n maxY = -Infinity;\n charCount = 0;\n widthSum = 0;\n prevRight = -Infinity;\n };\n\n for (let gi = s; gi <= e; gi++) {\n const g = text.glyphs[gi];\n if (isEmpty(g.flags)) continue;\n const b = g.loose;\n if (charCount > 0 && prevRight > -Infinity) {\n const avg = widthSum / charCount;\n if (avg > 0 && Math.abs(b.x - prevRight) > CHAR_DISTANCE_FACTOR * avg) flush();\n }\n minX = Math.min(minX, b.x);\n maxX = Math.max(maxX, b.x + b.width);\n minY = Math.min(minY, b.y);\n maxY = Math.max(maxY, b.y + b.height);\n charCount++;\n widthSum += b.width;\n prevRight = b.x + b.width;\n }\n flush();\n }\n\n return mergeAdjacentRects(subRuns);\n}\n\nfunction mergeAdjacentRects(runs: SubRun[]): Rect[] {\n const out: Rect[] = [];\n let prev: SubRun | null = null;\n let cur: Rect | null = null;\n for (const run of runs) {\n if (prev && cur && shouldMerge(prev, run)) {\n cur = boundsOfRects([cur, run.rect])!;\n } else {\n if (cur) out.push(cur);\n cur = run.rect;\n }\n prev = run;\n }\n if (cur && cur.width > 0 && cur.height > 0) out.push(cur);\n return out;\n}\n\nfunction shouldMerge(a: SubRun, b: SubRun): boolean {\n if (a.fontSize != null && b.fontSize != null && a.fontSize > 0 && b.fontSize > 0) {\n const ratio = Math.max(a.fontSize, b.fontSize) / Math.min(a.fontSize, b.fontSize);\n if (ratio > FONT_SIZE_RATIO_THRESHOLD) return false;\n }\n if (verticalOverlap(a.rect, b.rect) < VERTICAL_OVERLAP_THRESHOLD) return false;\n const aw = a.rect.width / a.charCount;\n const bw = b.rect.width / b.charCount;\n const aL = a.rect.x - aw;\n const aR = a.rect.x + a.rect.width + aw;\n const bL = b.rect.x - bw;\n const bR = b.rect.x + b.rect.width + bw;\n return aL < bR && aR > bL;\n}\n\nfunction verticalOverlap(a: Rect, b: Rect): number {\n if (a.height <= 0 || b.height <= 0) return 0;\n const u = Math.max(a.y + a.height, b.y + b.height) - Math.min(a.y, b.y);\n if (u === a.height || u === b.height) return 1;\n const i = Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));\n return i / u;\n}\n\nconst isZero = (r: Rect): boolean => r.width === 0 && r.height === 0;\n\nfunction overlapV(top1: number, bottom1: number, top2: number, bottom2: number): boolean {\n const u = Math.max(bottom1, bottom2) - Math.min(top1, top2);\n if (u === 0) return false;\n const i = Math.max(0, Math.min(bottom1, bottom2) - Math.max(top1, top2));\n return i / u >= LINE_OVERLAP_THRESHOLD;\n}\n","import type { PageObjectNumber, PluginContext } from '@embedpdf/core';\nimport type { Point, Rect } from '@embedpdf/core-geometry';\nimport {\n buildPageText,\n expandToLine,\n expandToWord,\n glyphAt,\n rectsForRange,\n type PageText,\n} from './geometry';\nimport type {\n GlyphPointer,\n SelectionAction,\n SelectionCapability,\n SelectionEndpoint,\n SelectionRange,\n SelectionSnapshot,\n SelectionState,\n} from './types';\n\nconst EMPTY: Rect[] = [];\n\n/**\n * The selection capability. The reducer state holds the selection range, the\n * derived content-space rects (per page), and per-page loaded flags; the (large,\n * non-serializable) per-page text geometry is cached HERE in the closure.\n *\n * Selection is cross-page: glyphs are ordered globally by (pageIndex, glyph), so\n * a drag from page 2 into page 4 selects the tail of 2, all of 3, and the head of\n * 4. `recompute` rebuilds the merged line rects for every loaded page in the span\n * and re-runs whenever a mid-span page finishes loading.\n */\nexport function createSelectionCapability(\n ctx: PluginContext<SelectionState, SelectionAction>,\n): SelectionCapability {\n const cache = new Map<number, PageText>();\n const pending = new Set<number>();\n // Consumers (e.g. text-markup) observe the selection without selection knowing\n // about them: `change` fires whenever the rects change, `commit` when a gesture\n // ends (pointer-up). One typed callback each — not an event bus.\n const changeCbs = new Set<() => void>();\n const commitCbs = new Set<() => void>();\n const fireChange = (): void => changeCbs.forEach((cb) => cb());\n\n const pageIndexOf = (pon: PageObjectNumber): number =>\n ctx.document()?.pages.findIndex((p) => p.pageObjectNumber === pon) ?? -1;\n const ponAtIndex = (i: number): PageObjectNumber | undefined =>\n ctx.document()?.pages[i]?.pageObjectNumber;\n\n // Order the two ends of a selection by document position (page, then glyph).\n function orderedEnds(sel: SelectionRange): {\n start: GlyphPointer;\n end: GlyphPointer;\n direction: 'forward' | 'backward';\n } {\n const ai = pageIndexOf(sel.anchor.pon);\n const fi = pageIndexOf(sel.focus.pon);\n const anchorFirst = ai < fi || (ai === fi && sel.anchor.glyph <= sel.focus.glyph);\n return anchorFirst\n ? { start: sel.anchor, end: sel.focus, direction: 'forward' }\n : { start: sel.focus, end: sel.anchor, direction: 'backward' };\n }\n\n function endpointFor(ptr: GlyphPointer, which: 'start' | 'end'): SelectionEndpoint | null {\n const rects = ctx.getState().rects[ptr.pon] ?? EMPTY;\n if (!rects.length) return null;\n return { pon: ptr.pon, rect: which === 'start' ? rects[0] : rects[rects.length - 1] };\n }\n\n function snapshot(): SelectionSnapshot {\n const { selection, rects } = ctx.getState();\n const pages = Object.keys(rects)\n .map(Number)\n .filter((pon) => (rects[pon]?.length ?? 0) > 0)\n .map((pon) => ({ pon: pon as PageObjectNumber, rects: rects[pon] }));\n if (!selection) return { pages, start: null, end: null, direction: 'forward' };\n const { start, end, direction } = orderedEnds(selection);\n return {\n pages,\n start: endpointFor(start, 'start'),\n end: endpointFor(end, 'end'),\n direction,\n };\n }\n\n function ensurePage(pon: PageObjectNumber): void {\n if (cache.has(pon) || pending.has(pon)) return;\n const doc = ctx.doc;\n const layout = ctx.document()?.pages.find((p) => p.pageObjectNumber === pon);\n if (!doc || !layout) return;\n pending.add(pon);\n doc\n .page(pon)\n .geometry.read()\n .then(\n (snapshot) => {\n pending.delete(pon);\n cache.set(\n pon,\n buildPageText(snapshot, layout.boxes.crop, layout.rotation, layout.userUnit),\n );\n ctx.dispatch({ type: 'PAGE_LOADED', pon });\n if (ctx.getState().selection) recompute(); // a mid-span page arrived → fill its rects\n },\n () => {\n pending.delete(pon); // doc closed / read aborted — ignore\n },\n );\n }\n\n // Rebuild merged line rects for every loaded page in the span; ensure the rest.\n function recompute(sel: SelectionRange | null = ctx.getState().selection): void {\n if (!sel) return;\n const { start, end } = orderedEnds(sel);\n const si = pageIndexOf(start.pon);\n const ei = pageIndexOf(end.pon);\n if (si < 0 || ei < 0) return;\n const rects: Record<number, Rect[]> = {};\n for (let i = si; i <= ei; i++) {\n const pon = ponAtIndex(i);\n if (pon == null) continue;\n const text = cache.get(pon);\n if (!text) {\n ensurePage(pon); // not loaded yet — it'll recompute when ready\n continue;\n }\n const from = i === si ? start.glyph : 0;\n const to = i === ei ? end.glyph : text.glyphs.length - 1;\n rects[pon] = rectsForRange(text, from, to);\n }\n ctx.dispatch({ type: 'SET', selection: sel, rects });\n fireChange();\n }\n\n // Set the selection to a flat [from,to] glyph span on one page (word/line).\n function selectSpan(pon: PageObjectNumber, point: Point, expand: 'word' | 'line'): void {\n const text = cache.get(pon);\n if (!text) return;\n const i = glyphAt(text, point);\n if (i == null) return;\n const [from, to] = expand === 'word' ? expandToWord(text, i) : expandToLine(text, i);\n recompute({ anchor: { pon, glyph: from }, focus: { pon, glyph: to } });\n }\n\n return {\n ensurePage,\n\n isLoaded: (pon) => !!ctx.getState().loaded[pon],\n\n isOverText: (pon, point: Point) => {\n const text = cache.get(pon);\n return text ? glyphAt(text, point) != null : false;\n },\n\n beginAt: (pon, point: Point) => {\n const text = cache.get(pon);\n if (!text) return false;\n const i = glyphAt(text, point);\n if (i == null) return false; // not near text — caller deselects, doesn't capture\n recompute({ anchor: { pon, glyph: i }, focus: { pon, glyph: i } });\n return true;\n },\n\n selectWord: (pon, point: Point) => selectSpan(pon, point, 'word'),\n selectLine: (pon, point: Point) => selectSpan(pon, point, 'line'),\n\n extendTo: (pon, point: Point) => {\n const cur = ctx.getState().selection;\n if (!cur) return;\n const text = cache.get(pon);\n if (!text) {\n ensurePage(pon); // dragged onto a not-yet-loaded page — warm it, recompute on load\n return;\n }\n const i = glyphAt(text, point);\n if (i == null) return; // off-text — keep the last focus\n recompute({ anchor: cur.anchor, focus: { pon, glyph: i } });\n },\n\n end: () => commitCbs.forEach((cb) => cb()), // the gesture ended (pointer-up) → notify consumers\n\n clear: () => {\n ctx.dispatch({ type: 'CLEAR' });\n fireChange();\n },\n\n snapshot,\n\n rectsForPage: (pon) => ctx.getState().rects[pon] ?? EMPTY,\n\n hasSelection: () => ctx.getState().selection != null,\n\n selectedPages: () => {\n const { rects } = ctx.getState();\n return Object.keys(rects)\n .map(Number)\n .filter((pon) => (rects[pon]?.length ?? 0) > 0) as PageObjectNumber[];\n },\n\n onChange: (cb) => {\n changeCbs.add(cb);\n return () => changeCbs.delete(cb);\n },\n onCommit: (cb) => {\n commitCbs.add(cb);\n return () => commitCbs.delete(cb);\n },\n\n setHighlightVisible: (visible) =>\n ctx.dispatch({ type: 'SET_HIGHLIGHT_HIDDEN', hidden: !visible }),\n highlightVisible: () => !ctx.getState().highlightHidden,\n };\n}\n","import type { InteractionCapability, InteractionHandler } from '@embedpdf/plugin-interaction';\nimport type { SelectionCapability } from './types';\n\nconst CURSOR_TOKEN = 'selection-text';\nconst DRAG_THRESHOLD_PX = 4; // viewport px the pointer must move before a drag-select begins\n\n/**\n * The text-selection pointer handler. It is live only under tools that enable the\n * `'text-select'` tag (the built-in `pointer` tool does; `pan` does not — so\n * switching to pan disables text selection with zero special-casing here).\n *\n * - single click → deselect; records an anchor but selects NOTHING until\n * the pointer moves past the drag threshold (Chrome/Acrobat feel)\n * - single-click + drag → caret selection from the anchor (extends across pages)\n * - double-click → select the word\n * - triple-click → select the visual line\n * - down off-text → deselect, and DON'T capture (so it can't block)\n * - hover → I-beam only when over text, else the pointer cursor\n */\nexport function createTextSelectHandler(\n selection: SelectionCapability,\n interaction: InteractionCapability,\n): InteractionHandler {\n // Per-gesture drag-threshold state (one active gesture at a time — the hub owner).\n let anchor: { pon: number; point: { x: number; y: number }; vx: number; vy: number } | null =\n null;\n let dragging = false;\n\n return {\n id: 'text-select',\n priority: 60,\n enabledFor: (tool) => tool.enables.has('text-select'),\n onDown: (s) => {\n anchor = null;\n dragging = false;\n if (!s.page) return false; // over a gap — let a lower handler (e.g. scroll) try\n const { pon, point } = s.page;\n const clicks = s.clickCount ?? 1;\n if (clicks >= 3) {\n selection.selectLine(pon, point);\n return true;\n }\n if (clicks === 2) {\n selection.selectWord(pon, point);\n return true;\n }\n // Single click: clear immediately (clicking deselects), then record an anchor\n // ONLY if over text — but begin no selection until the drag threshold is met.\n selection.clear();\n if (!selection.isOverText(pon, point)) return false; // empty space → don't capture\n anchor = { pon, point, vx: s.viewport.x, vy: s.viewport.y };\n return true;\n },\n onMove: (s) => {\n if (!s.page || !anchor) return;\n if (!dragging) {\n if (Math.hypot(s.viewport.x - anchor.vx, s.viewport.y - anchor.vy) < DRAG_THRESHOLD_PX) {\n return; // still a click, not a drag — select nothing yet\n }\n dragging = true;\n selection.beginAt(anchor.pon, anchor.point); // open the selection at the anchor\n }\n selection.extendTo(s.page.pon, s.page.point);\n },\n onUp: () => {\n anchor = null;\n dragging = false;\n selection.end();\n },\n onHover: (s) => {\n if (!s.page) {\n interaction.setCursor(CURSOR_TOKEN, null); // off the page → pointer\n return;\n }\n // Warm geometry on first hover; show the I-beam ONLY when actually over text.\n selection.ensurePage(s.page.pon);\n const overText = selection.isOverText(s.page.pon, s.page.point);\n interaction.setCursor(CURSOR_TOKEN, overText ? 'text' : null, 10);\n },\n };\n}\n","import type { SelectionAction, SelectionState } from './types';\n\nexport const initialSelectionState: SelectionState = {\n selection: null,\n rects: {},\n loaded: {},\n highlightHidden: false,\n};\n\nexport const selectionReducer = (\n state: SelectionState,\n action: SelectionAction,\n): SelectionState => {\n switch (action.type) {\n case 'PAGE_LOADED':\n return state.loaded[action.pon]\n ? state\n : { ...state, loaded: { ...state.loaded, [action.pon]: true } };\n case 'SET':\n return { ...state, selection: action.selection, rects: action.rects };\n case 'CLEAR':\n return state.selection === null && Object.keys(state.rects).length === 0\n ? state\n : { ...state, selection: null, rects: {} };\n case 'SET_HIGHLIGHT_HIDDEN':\n return state.highlightHidden === action.hidden\n ? state\n : { ...state, highlightHidden: action.hidden };\n default:\n return state;\n }\n};\n","import { createCapabilityToken, type PageObjectNumber } from '@embedpdf/core';\nimport type { Point, Rect } from '@embedpdf/core-geometry';\n\n/** A glyph address: a page + a flat glyph index within that page's geometry. */\nexport interface GlyphPointer {\n pon: PageObjectNumber;\n glyph: number;\n}\n\n/** Anchor = where the drag began, focus = the current end. Inclusive. */\nexport interface SelectionRange {\n anchor: GlyphPointer;\n focus: GlyphPointer;\n}\n\nexport interface SelectionEndpoint {\n pon: PageObjectNumber;\n rect: Rect;\n}\n\nexport interface SelectionSnapshot {\n pages: Array<{ pon: PageObjectNumber; rects: Rect[] }>;\n start: SelectionEndpoint | null;\n end: SelectionEndpoint | null;\n direction: 'forward' | 'backward';\n}\n\nexport interface SelectionState {\n selection: SelectionRange | null;\n /** Derived highlight rects per page, in CONTENT space (y-down, PDF units). */\n rects: Record<number, Rect[]>;\n /** Pages whose text geometry has loaded (so the layer re-renders when ready). */\n loaded: Record<number, boolean>;\n /** When a consumer owns the selection visual (e.g. a markup tool draws its own\n * preview), the default highlight rects are suppressed. */\n highlightHidden: boolean;\n}\n\nexport type SelectionAction =\n | { type: 'PAGE_LOADED'; pon: PageObjectNumber }\n | { type: 'SET'; selection: SelectionRange; rects: Record<number, Rect[]> }\n | { type: 'CLEAR' }\n | { type: 'SET_HIGHLIGHT_HIDDEN'; hidden: boolean };\n\nexport interface SelectionCapability {\n /** Warm a page's text geometry (idempotent). Layers call this when a page mounts. */\n ensurePage(pon: PageObjectNumber): void;\n isLoaded(pon: PageObjectNumber): boolean;\n /** Is a content-space point on (or near) text? Drives the I-beam vs pointer cursor. */\n isOverText(pon: PageObjectNumber, point: Point): boolean;\n /** Begin a caret selection at a page point. Returns false if not near any text. */\n beginAt(pon: PageObjectNumber, point: Point): boolean;\n /** Double-click: select the word around the point. */\n selectWord(pon: PageObjectNumber, point: Point): void;\n /** Triple-click: select the whole visual line around the point. */\n selectLine(pon: PageObjectNumber, point: Point): void;\n /** Extend the current selection to a page point (drag). */\n extendTo(pon: PageObjectNumber, point: Point): void;\n end(): void;\n clear(): void;\n /** Coherent read-model for consumers that create annotations or selection UI. */\n snapshot(): SelectionSnapshot;\n /** Highlight rects for a page, in content space — the layer's only input. */\n rectsForPage(pon: PageObjectNumber): Rect[];\n hasSelection(): boolean;\n /** The pages the current selection covers (those with at least one rect) — so a\n * cross-page action (e.g. text-markup creation) can fan out per page. */\n selectedPages(): PageObjectNumber[];\n /** Fires whenever the selection rects change (e.g. drag-extend) — for live preview. */\n onChange(cb: () => void): () => void;\n /** Fires when a selection gesture ends (pointer-up) — the commit point. */\n onCommit(cb: () => void): () => void;\n /** Suppress / restore the default highlight visual (a consumer drawing its own). */\n setHighlightVisible(visible: boolean): void;\n highlightVisible(): boolean;\n}\n\nexport const SelectionToken = createCapabilityToken<SelectionCapability>('selection');\n","import { definePlugin } from '@embedpdf/core';\nimport { InteractionToken } from '@embedpdf/plugin-interaction';\nimport { createSelectionCapability } from './capability';\nimport { createTextSelectHandler } from './handler';\nimport { initialSelectionState, selectionReducer } from './reducer';\nimport { SelectionToken } from './types';\nimport type { SelectionAction, SelectionCapability, SelectionState } from './types';\n\n/**\n * Text selection — document-scoped, requires the interaction hub. In `init` it\n * registers ITS pointer handler with the hub; the hub owns the pointer stream\n * and arbitration. Works with `<Stage>` or a standalone `<PageView>` — selection\n * only needs the page coordinate context + the engine's text geometry.\n */\nexport const selectionPlugin = () =>\n definePlugin<SelectionState, SelectionAction, SelectionCapability>({\n id: 'selection',\n token: SelectionToken,\n scope: 'document',\n requires: [InteractionToken],\n initialState: initialSelectionState,\n reduce: selectionReducer,\n capability: createSelectionCapability,\n init: (ctx) => {\n const interaction = ctx.get(InteractionToken);\n const selection = ctx.get(SelectionToken); // our own capability (built before init)\n interaction.registerHandler(createTextSelectHandler(selection, interaction));\n },\n });\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,MAAM,aAAa;AACnB,MAAM,cAAc,WAA4B,QAAS,OAA8B;AACvF,MAAM,WAAW,WAA4B,QAAQ,gBAAgB;AAuBrE,MAAM,aAAa,GAAoC,MACrD,UACE,GACA;CACE,GAAG,EAAE;CACL,GAAG,EAAE;CACL,OAAO,EAAE,QAAQ,EAAE;CACnB,QAAQ,EAAE,MAAM,EAAE;AACpB,CACF;;;;;;AAOF,SAAgB,cACd,UACA,MACA,UACA,UACU;CAGV,MAAM,EAAE,iB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F,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["SelectionToken","SelectionHostToken"],"sources":["../src/selection.plugin.ts","../src/index.ts"],"sourcesContent":["import { definePlugin } from '@embedpdf/core';\nimport { InteractionToken } from '@embedpdf/plugin-interaction';\nimport { createSelectionCapability } from './capability';\nimport { createTextSelectHandler } from './handler';\nimport { initialSelectionState, selectionReducer } from './reducer';\nimport { SelectionToken } from './types';\nimport type { SelectionAction, SelectionHostCapability, SelectionState } from './types';\n\n/**\n * Text selection — document-scoped, requires the interaction hub. In `init` it\n * registers ITS pointer handler with the hub; the hub owns the pointer stream\n * and arbitration. Works with `<Stage>` or a standalone `<PageView>` — selection\n * only needs the page coordinate context + the engine's text geometry.\n *\n * Registry/content invalidation is wired inside the capability itself\n * (revision watch + document event subscription), so headless/programmatic\n * use gets the same reconciliation as the full viewer.\n */\nexport const selectionPlugin = () =>\n definePlugin<SelectionState, SelectionAction, SelectionHostCapability>({\n id: 'selection',\n token: SelectionToken,\n scope: 'document',\n requires: [InteractionToken],\n initialState: initialSelectionState,\n reduce: selectionReducer,\n capability: createSelectionCapability,\n init: (ctx) => {\n const interaction = ctx.get(InteractionToken);\n const selection = ctx.get(SelectionToken); // our own capability (built before init)\n interaction.registerHandler(createTextSelectHandler(selection, interaction));\n },\n });\n","/**\n * @embedpdf/plugin-selection — text selection over the engine's text geometry.\n *\n * The PUBLIC surface: the plugin factory, the capability token (narrowed to\n * the public lens), and the range/read vocabulary. Selection ranges live in\n * CHARACTER space (half-open `TextRange` — the same space search hits\n * address), geometry needs `doc.text.select`, text extraction needs\n * `doc.text.copy`, and neither permission implies the other.\n *\n * Framework/host plumbing (gesture intents, geometry warming, the reducer,\n * the coordinate seam) lives behind `@embedpdf/plugin-selection/internal`.\n * Clipboard writes live in `@embedpdf/web` — this package is DOM-free.\n */\nimport type { CapabilityToken } from '@embedpdf/core';\nimport { SelectionToken as SelectionHostToken } from './types';\nimport type { SelectionCapability } from './types';\n\nexport { selectionPlugin } from './selection.plugin';\nexport type {\n SelectionCapability,\n SelectionEndpoint,\n SelectionMenuAnchor,\n SelectionRangeInput,\n SelectionSnapshot,\n TextPosition,\n TextRange,\n} from './types';\nexport type { SelectionSegment } from './geometry';\n\n/**\n * The selection capability token, narrowed to the public\n * {@link SelectionCapability} lens. It is the SAME runtime token the plugin\n * provides — the host-only surface (pointer gestures, geometry warming) is\n * reachable only via `@embedpdf/plugin-selection/internal`.\n */\nexport const SelectionToken =\n SelectionHostToken as unknown as CapabilityToken<SelectionCapability>;\n"],"mappings":";;;;;;;;;;;;;;AAkBA,MAAa,wBACX,aAAuE;CACrE,IAAI;CACJ,OAAOA;CACP,OAAO;CACP,UAAU,CAAC,gBAAgB;CAC3B,cAAc;CACd,QAAQ;CACR,YAAY;CACZ,OAAO,QAAQ;EACb,MAAM,cAAc,IAAI,IAAI,gBAAgB;EAC5C,MAAM,YAAY,IAAI,IAAIA,gBAAc;EACxC,YAAY,gBAAgB,wBAAwB,WAAW,WAAW,CAAC;CAC7E;AACF,CAAC;;;;;;;;;ACGH,MAAa,iBACXC"}
|