@embedpdf/plugin-selection 3.0.0-next.3 → 3.0.0-next.4

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["InteractionToken"],"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,OAAA,GAAA,wBAAA,UAAA,CAEnD,GACA;CACE,GAAG,EAAE;CACL,GAAG,EAAE;CACL,OAAO,EAAE,QAAQ,EAAE;CACnB,QAAQ,EAAE,MAA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AQ;CACR,YAAY;CACZ,OAAO,QAAQ;EACb,MAAM,cAAc,IAAI,IAAIA,6BAAAA,gBAAgB;EAC5C,MAAM,YAAY,IAAI,IAAI,cAAc;EACxC,YAAY,gBAAgB,wBAAwB,WAAW,WAAW,CAAC;CAC7E;AACF,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["InteractionToken"],"sources":["../src/geometry.ts","../src/capability.ts","../src/handler.ts","../src/reducer.ts","../src/types.ts","../src/selection.plugin.ts"],"sourcesContent":["/**\n * The selection plugin's COORDINATE SEAM — and nothing else.\n *\n * Segmentation, hit-testing, and word/line expansion live in the canonical\n * engine-core text layout (`@embedpdf/engine-core` `text/layout`): a text\n * range has exactly one segmentation whether it came from a drag or a\n * search. This module only converts between the viewer's content space\n * (y-down, crop-relative) and the engine's PDF space (y-up) — pointer\n * points inward, canonical segments outward. The PDF↔content y-flip is the\n * geometry package's `pageGeometry` (the one place that math lives), never\n * hand-rolled here.\n */\nimport {\n applyPoint,\n invert,\n pageGeometry,\n textQuadBounds,\n type Mat2D,\n type Point,\n type PointIn,\n type Rect,\n type TextQuad,\n} from '@embedpdf/core-geometry';\nimport {\n buildPageTextLayout,\n type PageGeometrySnapshot,\n type PageTextLayout,\n type PdfPoint,\n type PdfQuad,\n type PdfRect,\n type PdfTextSegment,\n} from '@embedpdf/engine-core/runtime';\n\n/**\n * One merged visual line of a selection, in content space — the structural\n * twin of the engine's `PdfTextSegment`. `quad` carries frame-geometric\n * corner semantics (upper = ascent side, start = the frame's −x); `advance`\n * is the READING direction along the baseline (+1 = toward `end`), derived\n * from the glyph sequence — geometry and bidi stay separate concerns.\n * `rect` is the content-space AABB.\n */\nexport interface SelectionSegment {\n quad: TextQuad;\n rect: Rect;\n advance: 1 | -1;\n}\n\n/** A page's cached selection geometry: the canonical layout + the seam. */\nexport interface SelectionPageGeometry {\n layout: PageTextLayout;\n toContent: Mat2D<'pdf', 'content'>;\n fromContent: Mat2D<'content', 'pdf'>;\n}\n\n/**\n * Build a page's selection geometry. Page display rotation does NOT enter\n * here — the overlay rides the page's CSS rotation, so content space stays\n * un-rotated (the crop-relative y-flip is the only conversion; zoom = 1,\n * the viewer's zoom is applied later by `PageTransform.pageToContent`).\n */\nexport function buildSelectionPageGeometry(\n snapshot: PageGeometrySnapshot,\n crop: PdfRect,\n rotation: 0 | 90 | 180 | 270,\n userUnit: number,\n): SelectionPageGeometry {\n const { pdfToContent } = pageGeometry({ crop, rotation, userUnit }, 1);\n return {\n layout: buildPageTextLayout(snapshot),\n toContent: pdfToContent,\n fromContent: invert(pdfToContent),\n };\n}\n\n/** A content-space pointer point in the layout's PDF space. */\nexport function contentPointToPdf(geom: SelectionPageGeometry, p: Point): PdfPoint {\n return applyPoint(geom.fromContent, p as PointIn<'content'>);\n}\n\n/**\n * A canonical PDF quad in content space. Engine quads carry frame-geometric\n * slot semantics (`p1..p4` = upper-start, upper-end, lower-start,\n * lower-end) — a trusted producer, so the y-flip maps corners straight onto\n * their names; imported-annotation normalization does NOT apply here.\n */\nexport function toContentTextQuad(geom: SelectionPageGeometry, quad: PdfQuad): TextQuad {\n const pt = (p: PdfPoint): Point => applyPoint(geom.toContent, p as PointIn<'pdf'>);\n return {\n upperStart: pt(quad.p1),\n upperEnd: pt(quad.p2),\n lowerStart: pt(quad.p3),\n lowerEnd: pt(quad.p4),\n };\n}\n\n/** A canonical segment in content space (`rect` recomputed from the mapped\n * quad so the pair can never drift). */\nexport function toContentSegment(\n geom: SelectionPageGeometry,\n segment: PdfTextSegment,\n): SelectionSegment {\n const quad = toContentTextQuad(geom, segment.quad);\n return { quad, rect: textQuadBounds(quad), advance: segment.advance };\n}\n","import type { PageObjectNumber, PluginContext } from '@embedpdf/core';\nimport { textQuadBounds, type Point } from '@embedpdf/core-geometry';\nimport {\n expandTextRangeToLine,\n expandTextRangeToWord,\n textGlyphAt,\n textGlyphQuad,\n textSegmentsForRange,\n} from '@embedpdf/engine-core/runtime';\nimport {\n buildSelectionPageGeometry,\n contentPointToPdf,\n toContentSegment,\n toContentTextQuad,\n type SelectionPageGeometry,\n type SelectionSegment,\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_SEGMENTS: SelectionSegment[] = [];\n\n/**\n * The selection capability. The reducer state holds the selection range, the\n * derived content-space segments (per page), and per-page loaded flags; the\n * (large, non-serializable) per-page canonical layout is cached HERE in the\n * closure. Segmentation itself is the engine-core text layout — selection\n * owns gestures and state, never how glyphs become lines.\n *\n * Selection is cross-page: glyphs are ordered globally by (pageIndex, glyph),\n * so a drag from page 2 into page 4 selects the tail of 2, all of 3, and the\n * head of 4. `recompute` rebuilds the merged line segments for every loaded\n * page in the span 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, SelectionPageGeometry>();\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 segments change, `commit` when a\n // gesture 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 const glyphAt = (geom: SelectionPageGeometry, point: Point): number | null =>\n textGlyphAt(geom.layout, contentPointToPdf(geom, point));\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 segments = ctx.getState().segments[ptr.pon] ?? EMPTY_SEGMENTS;\n if (!segments.length) return null;\n const segment = which === 'start' ? segments[0] : segments[segments.length - 1];\n\n // Anchor the endpoint to the boundary GLYPH's own oriented cell so caret\n // placement lands on the exact character edge; fall back to the segment\n // when the glyph is degenerate (e.g. a generated space).\n const geom = cache.get(ptr.pon);\n const cell = geom ? textGlyphQuad(geom.layout, ptr.glyph) : null;\n if (geom && cell) {\n const glyphQuad = toContentTextQuad(geom, cell);\n return {\n pon: ptr.pon,\n glyphQuad,\n advance: segment.advance,\n rect: textQuadBounds(glyphQuad),\n };\n }\n return { pon: ptr.pon, glyphQuad: segment.quad, advance: segment.advance, rect: segment.rect };\n }\n\n function snapshot(): SelectionSnapshot {\n const { selection, segments } = ctx.getState();\n const pages = Object.keys(segments)\n .map(Number)\n .filter((pon) => (segments[pon]?.length ?? 0) > 0)\n .map((pon) => ({ pon: pon as PageObjectNumber, segments: segments[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 buildSelectionPageGeometry(\n snapshot,\n layout.boxes.crop,\n layout.rotation,\n layout.userUnit,\n ),\n );\n ctx.dispatch({ type: 'PAGE_LOADED', pon });\n if (ctx.getState().selection) recompute(); // a mid-span page arrived → fill its segments\n },\n () => {\n pending.delete(pon); // doc closed / read aborted — ignore\n },\n );\n }\n\n // Rebuild merged line segments 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 segments: Record<number, SelectionSegment[]> = {};\n for (let i = si; i <= ei; i++) {\n const pon = ponAtIndex(i);\n if (pon == null) continue;\n const geom = cache.get(pon);\n if (!geom) {\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 : geom.layout.glyphs.length - 1;\n segments[pon] = textSegmentsForRange(geom.layout, from, to - from + 1).map((s) =>\n toContentSegment(geom, s),\n );\n }\n ctx.dispatch({ type: 'SET', selection: sel, segments });\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 geom = cache.get(pon);\n if (!geom) return;\n const i = glyphAt(geom, point);\n if (i == null) return;\n const [from, to] =\n expand === 'word'\n ? expandTextRangeToWord(geom.layout, i)\n : expandTextRangeToLine(geom.layout, 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 geom = cache.get(pon);\n return geom ? glyphAt(geom, point) != null : false;\n },\n\n beginAt: (pon, point: Point) => {\n const geom = cache.get(pon);\n if (!geom) return false;\n const i = glyphAt(geom, 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 geom = cache.get(pon);\n if (!geom) {\n ensurePage(pon); // dragged onto a not-yet-loaded page — warm it, recompute on load\n return;\n }\n const i = glyphAt(geom, 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 segmentsForPage: (pon) => ctx.getState().segments[pon] ?? EMPTY_SEGMENTS,\n\n rectsForPage: (pon) =>\n (ctx.getState().segments[pon] ?? EMPTY_SEGMENTS).map((s) => s.rect),\n\n hasSelection: () => ctx.getState().selection != null,\n\n selectedPages: () => {\n const { segments } = ctx.getState();\n return Object.keys(segments)\n .map(Number)\n .filter((pon) => (segments[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 segments: {},\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, segments: action.segments };\n case 'CLEAR':\n return state.selection === null && Object.keys(state.segments).length === 0\n ? state\n : { ...state, selection: null, segments: {} };\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, TextQuad } from '@embedpdf/core-geometry';\nimport type { SelectionSegment } from './geometry';\n\nexport type { SelectionSegment } from './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\n/**\n * A selection boundary, anchored to the boundary GLYPH's own oriented cell.\n * `advance` is the reading direction of the segment it belongs to (+1 = the\n * frame's +x), so caret consumers place at the trailing edge without\n * re-deriving bidi from geometry. `rect` is the AABB (scroll targets).\n */\nexport interface SelectionEndpoint {\n pon: PageObjectNumber;\n glyphQuad: TextQuad;\n advance: 1 | -1;\n rect: Rect;\n}\n\nexport interface SelectionSnapshot {\n /** Per-page canonical segments — the ONE geometry consumers act on.\n * Boxes are derived views (`segment.rect`, or `rectsForPage()`). */\n pages: Array<{ pon: PageObjectNumber; segments: SelectionSegment[] }>;\n start: SelectionEndpoint | null;\n end: SelectionEndpoint | null;\n direction: 'forward' | 'backward';\n}\n\nexport interface SelectionState {\n selection: SelectionRange | null;\n /** Derived per-line segments per page, in CONTENT space (y-down, PDF units). */\n segments: Record<number, SelectionSegment[]>;\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; segments: Record<number, SelectionSegment[]> }\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 /** Per-line oriented segments for a page, in content space — the layer's input. */\n segmentsForPage(pon: PageObjectNumber): SelectionSegment[];\n /** The segments' AABBs — for consumers that genuinely want boxes (scroll,\n * conservative regions). Never a substitute for the oriented quads in\n * geometry that gets drawn or persisted. */\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":";;;;;;;;;;;;;;;;;;;;;;;;AA4DA,SAAgB,2BACd,UACA,MACA,UACA,UACuB;CACvB,MAAM,EAAE,kBAAA,GAAA,wBAAA,aAAA,CAA8B;EAAE;EAAM;EAAU;CAAS,GAAG,CAAC;CACrE,OAAO;EACL,SAAA,GAAA,8BAAA,oBAAA,CAA4B,QAAQ;EACpC,WAAW;EACX,cAAA,GAAA,wBAAA,OAAA,CAAoB,YAAY;CAClC;AACF;;AAGA,SAAgB,kBAAkB,MAA6B,GAAoB;CACjF,QAAA,GAAA,wBAAA,WAAA,CAAkB,KAAK,aAAa,CAAuB;AAC7D;;;;;;;AAQA,SAAgB,kBAAkB,MAA6B,MAAyB;CACtF,MAAM,MAAM,OAAA,GAAA,wBAAA,WAAA,CAAkC,KAAK,WAAW,CAAmB;CACjF,OAAO;EACL,YAAY,GAAG,KAAK,EAAE;EACtB,UAAU,GAAG,KAAK,EAAE;EACpB,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OAAO;EAAO;EACjD,SACE,OAAO;CACX;AACF;;;AC+DA,MAAa,kBAAA,GAAA,eAAA,sBAAA,CAA4D,WAAW;;;;;;;;;AChFpF,MAAa,yBAAA,GAAA,eAAA,aAAA,CACwD;CACjE,IAAI;CACJ,OAAO;CACP,OAAO;CACP,UAAU,CAACA,6BAAAA,gBAAgB;CAC3B,cAAc;CACd,QAAQ;CACR,YAAY;CACZ,OAAO,QAAQ;EACb,MAAM,cAAc,IAAI,IAAIA,6BAAAA,gBAAgB;EAC5C,MAAM,YAAY,IAAI,IAAI,cAAc;EACxC,YAAY,gBAAgB,wBAAwB,WAAW,WAAW,CAAC;CAC7E;AACF,CAAC"}
package/dist/index.d.cts CHANGED
@@ -1,7 +1,47 @@
1
1
  import { PageObjectNumber, PluginContext } from "@embedpdf/core";
2
- import { Point, Rect } from "@embedpdf/core-geometry";
2
+ import { Mat2D, Point, Rect, TextQuad } from "@embedpdf/core-geometry";
3
+ import { PageGeometrySnapshot, PageTextLayout, PdfPoint, PdfQuad, PdfRect, PdfTextSegment } from "@embedpdf/engine-core/runtime";
3
4
  import { InteractionCapability, InteractionHandler } from "@embedpdf/plugin-interaction";
4
- import { PageGeometrySnapshot, PdfRect } from "@embedpdf/engine-core/runtime";
5
+ //#region src/geometry.d.ts
6
+ /**
7
+ * One merged visual line of a selection, in content space — the structural
8
+ * twin of the engine's `PdfTextSegment`. `quad` carries frame-geometric
9
+ * corner semantics (upper = ascent side, start = the frame's −x); `advance`
10
+ * is the READING direction along the baseline (+1 = toward `end`), derived
11
+ * from the glyph sequence — geometry and bidi stay separate concerns.
12
+ * `rect` is the content-space AABB.
13
+ */
14
+ interface SelectionSegment {
15
+ quad: TextQuad;
16
+ rect: Rect;
17
+ advance: 1 | -1;
18
+ }
19
+ /** A page's cached selection geometry: the canonical layout + the seam. */
20
+ interface SelectionPageGeometry {
21
+ layout: PageTextLayout;
22
+ toContent: Mat2D<'pdf', 'content'>;
23
+ fromContent: Mat2D<'content', 'pdf'>;
24
+ }
25
+ /**
26
+ * Build a page's selection geometry. Page display rotation does NOT enter
27
+ * here — the overlay rides the page's CSS rotation, so content space stays
28
+ * un-rotated (the crop-relative y-flip is the only conversion; zoom = 1,
29
+ * the viewer's zoom is applied later by `PageTransform.pageToContent`).
30
+ */
31
+ declare function buildSelectionPageGeometry(snapshot: PageGeometrySnapshot, crop: PdfRect, rotation: 0 | 90 | 180 | 270, userUnit: number): SelectionPageGeometry;
32
+ /** A content-space pointer point in the layout's PDF space. */
33
+ declare function contentPointToPdf(geom: SelectionPageGeometry, p: Point): PdfPoint;
34
+ /**
35
+ * A canonical PDF quad in content space. Engine quads carry frame-geometric
36
+ * slot semantics (`p1..p4` = upper-start, upper-end, lower-start,
37
+ * lower-end) — a trusted producer, so the y-flip maps corners straight onto
38
+ * their names; imported-annotation normalization does NOT apply here.
39
+ */
40
+ declare function toContentTextQuad(geom: SelectionPageGeometry, quad: PdfQuad): TextQuad;
41
+ /** A canonical segment in content space (`rect` recomputed from the mapped
42
+ * quad so the pair can never drift). */
43
+ declare function toContentSegment(geom: SelectionPageGeometry, segment: PdfTextSegment): SelectionSegment;
44
+ //#endregion
5
45
  //#region src/types.d.ts
6
46
  /** A glyph address: a page + a flat glyph index within that page's geometry. */
7
47
  interface GlyphPointer {
@@ -13,14 +53,24 @@ interface SelectionRange {
13
53
  anchor: GlyphPointer;
14
54
  focus: GlyphPointer;
15
55
  }
56
+ /**
57
+ * A selection boundary, anchored to the boundary GLYPH's own oriented cell.
58
+ * `advance` is the reading direction of the segment it belongs to (+1 = the
59
+ * frame's +x), so caret consumers place at the trailing edge without
60
+ * re-deriving bidi from geometry. `rect` is the AABB (scroll targets).
61
+ */
16
62
  interface SelectionEndpoint {
17
63
  pon: PageObjectNumber;
64
+ glyphQuad: TextQuad;
65
+ advance: 1 | -1;
18
66
  rect: Rect;
19
67
  }
20
68
  interface SelectionSnapshot {
69
+ /** Per-page canonical segments — the ONE geometry consumers act on.
70
+ * Boxes are derived views (`segment.rect`, or `rectsForPage()`). */
21
71
  pages: Array<{
22
72
  pon: PageObjectNumber;
23
- rects: Rect[];
73
+ segments: SelectionSegment[];
24
74
  }>;
25
75
  start: SelectionEndpoint | null;
26
76
  end: SelectionEndpoint | null;
@@ -28,8 +78,8 @@ interface SelectionSnapshot {
28
78
  }
29
79
  interface SelectionState {
30
80
  selection: SelectionRange | null;
31
- /** Derived highlight rects per page, in CONTENT space (y-down, PDF units). */
32
- rects: Record<number, Rect[]>;
81
+ /** Derived per-line segments per page, in CONTENT space (y-down, PDF units). */
82
+ segments: Record<number, SelectionSegment[]>;
33
83
  /** Pages whose text geometry has loaded (so the layer re-renders when ready). */
34
84
  loaded: Record<number, boolean>;
35
85
  /** When a consumer owns the selection visual (e.g. a markup tool draws its own
@@ -42,7 +92,7 @@ type SelectionAction = {
42
92
  } | {
43
93
  type: 'SET';
44
94
  selection: SelectionRange;
45
- rects: Record<number, Rect[]>;
95
+ segments: Record<number, SelectionSegment[]>;
46
96
  } | {
47
97
  type: 'CLEAR';
48
98
  } | {
@@ -67,7 +117,11 @@ interface SelectionCapability {
67
117
  clear(): void;
68
118
  /** Coherent read-model for consumers that create annotations or selection UI. */
69
119
  snapshot(): SelectionSnapshot;
70
- /** Highlight rects for a page, in content space — the layer's only input. */
120
+ /** Per-line oriented segments for a page, in content space — the layer's input. */
121
+ segmentsForPage(pon: PageObjectNumber): SelectionSegment[];
122
+ /** The segments' AABBs — for consumers that genuinely want boxes (scroll,
123
+ * conservative regions). Never a substitute for the oriented quads in
124
+ * geometry that gets drawn or persisted. */
71
125
  rectsForPage(pon: PageObjectNumber): Rect[];
72
126
  hasSelection(): boolean;
73
127
  /** The pages the current selection covers (those with at least one rect) — so a
@@ -95,13 +149,15 @@ declare const selectionPlugin: () => import("@embedpdf/core").PluginDef<Selectio
95
149
  //#region src/capability.d.ts
96
150
  /**
97
151
  * The selection capability. The reducer state holds the selection range, the
98
- * derived content-space rects (per page), and per-page loaded flags; the (large,
99
- * non-serializable) per-page text geometry is cached HERE in the closure.
152
+ * derived content-space segments (per page), and per-page loaded flags; the
153
+ * (large, non-serializable) per-page canonical layout is cached HERE in the
154
+ * closure. Segmentation itself is the engine-core text layout — selection
155
+ * owns gestures and state, never how glyphs become lines.
100
156
  *
101
- * Selection is cross-page: glyphs are ordered globally by (pageIndex, glyph), so
102
- * a drag from page 2 into page 4 selects the tail of 2, all of 3, and the head of
103
- * 4. `recompute` rebuilds the merged line rects for every loaded page in the span
104
- * and re-runs whenever a mid-span page finishes loading.
157
+ * Selection is cross-page: glyphs are ordered globally by (pageIndex, glyph),
158
+ * so a drag from page 2 into page 4 selects the tail of 2, all of 3, and the
159
+ * head of 4. `recompute` rebuilds the merged line segments for every loaded
160
+ * page in the span and re-runs whenever a mid-span page finishes loading.
105
161
  */
106
162
  declare function createSelectionCapability(ctx: PluginContext<SelectionState, SelectionAction>): SelectionCapability;
107
163
  //#endregion
@@ -125,43 +181,5 @@ declare function createTextSelectHandler(selection: SelectionCapability, interac
125
181
  declare const initialSelectionState: SelectionState;
126
182
  declare const selectionReducer: (state: SelectionState, action: SelectionAction) => SelectionState;
127
183
  //#endregion
128
- //#region src/geometry.d.ts
129
- /** One glyph in content space. `loose` builds selection rects; `tight` hit-tests. */
130
- interface GlyphInfo {
131
- loose: Rect;
132
- tight?: Rect;
133
- flags: number;
134
- }
135
- /** A contiguous run of glyphs (a text object). `rect` is its loose enclosing box. */
136
- interface RunInfo {
137
- start: number;
138
- count: number;
139
- rect: Rect;
140
- fontSize?: number;
141
- }
142
- /** A page's text laid out in content space: a flat glyph list + the run structure. */
143
- interface PageText {
144
- glyphs: GlyphInfo[];
145
- runs: RunInfo[];
146
- }
147
- /**
148
- * Flatten a page's text geometry into content-space glyphs + runs. Rotation does
149
- * NOT enter here — the overlay rides the page's CSS rotation, so glyphs stay in
150
- * un-rotated content space (the crop-relative y-flip is the only conversion).
151
- */
152
- declare function buildPageText(snapshot: PageGeometrySnapshot, crop: PdfRect, rotation: 0 | 90 | 180 | 270, userUnit: number): PageText;
153
- /**
154
- * The glyph index at a content-space point, or null when nothing is near (so the
155
- * caller can show the pointer cursor off-text). PDFium `GetIndexAtPos`: exact
156
- * tight-box containment first, then a tolerance pass (closest by Manhattan
157
- * distance within `toleranceFactor × average glyph height`).
158
- */
159
- declare function glyphAt(text: PageText, p: Point, toleranceFactor?: number): number | null;
160
- /** Double-click: the word around `i` (walk to space/empty glyphs both ways). */
161
- declare function expandToWord(text: PageText, i: number): [number, number];
162
- /** Triple-click: the full visual line — runs whose vertical extent overlaps the anchor run's. */
163
- declare function expandToLine(text: PageText, i: number): [number, number];
164
- declare function rectsForRange(text: PageText, from: number, to: number): Rect[];
165
- //#endregion
166
- export { type GlyphInfo, type GlyphPointer, type PageText, type RunInfo, type SelectionAction, type SelectionCapability, type SelectionEndpoint, type SelectionRange, type SelectionSnapshot, type SelectionState, SelectionToken, buildPageText, createSelectionCapability, createTextSelectHandler, expandToLine, expandToWord, glyphAt, initialSelectionState, rectsForRange, selectionPlugin, selectionReducer };
184
+ export { type GlyphPointer, type SelectionAction, type SelectionCapability, type SelectionEndpoint, type SelectionPageGeometry, type SelectionRange, type SelectionSegment, type SelectionSnapshot, type SelectionState, SelectionToken, buildSelectionPageGeometry, contentPointToPdf, createSelectionCapability, createTextSelectHandler, initialSelectionState, selectionPlugin, selectionReducer, toContentSegment, toContentTextQuad };
167
185
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -1,7 +1,47 @@
1
1
  import { PageObjectNumber, PluginContext } from "@embedpdf/core";
2
2
  import { InteractionCapability, InteractionHandler } from "@embedpdf/plugin-interaction";
3
- import { Point, Rect } from "@embedpdf/core-geometry";
4
- import { PageGeometrySnapshot, PdfRect } from "@embedpdf/engine-core/runtime";
3
+ import { Mat2D, Point, Rect, TextQuad } from "@embedpdf/core-geometry";
4
+ import { PageGeometrySnapshot, PageTextLayout, PdfPoint, PdfQuad, PdfRect, PdfTextSegment } from "@embedpdf/engine-core/runtime";
5
+ //#region src/geometry.d.ts
6
+ /**
7
+ * One merged visual line of a selection, in content space — the structural
8
+ * twin of the engine's `PdfTextSegment`. `quad` carries frame-geometric
9
+ * corner semantics (upper = ascent side, start = the frame's −x); `advance`
10
+ * is the READING direction along the baseline (+1 = toward `end`), derived
11
+ * from the glyph sequence — geometry and bidi stay separate concerns.
12
+ * `rect` is the content-space AABB.
13
+ */
14
+ interface SelectionSegment {
15
+ quad: TextQuad;
16
+ rect: Rect;
17
+ advance: 1 | -1;
18
+ }
19
+ /** A page's cached selection geometry: the canonical layout + the seam. */
20
+ interface SelectionPageGeometry {
21
+ layout: PageTextLayout;
22
+ toContent: Mat2D<'pdf', 'content'>;
23
+ fromContent: Mat2D<'content', 'pdf'>;
24
+ }
25
+ /**
26
+ * Build a page's selection geometry. Page display rotation does NOT enter
27
+ * here — the overlay rides the page's CSS rotation, so content space stays
28
+ * un-rotated (the crop-relative y-flip is the only conversion; zoom = 1,
29
+ * the viewer's zoom is applied later by `PageTransform.pageToContent`).
30
+ */
31
+ declare function buildSelectionPageGeometry(snapshot: PageGeometrySnapshot, crop: PdfRect, rotation: 0 | 90 | 180 | 270, userUnit: number): SelectionPageGeometry;
32
+ /** A content-space pointer point in the layout's PDF space. */
33
+ declare function contentPointToPdf(geom: SelectionPageGeometry, p: Point): PdfPoint;
34
+ /**
35
+ * A canonical PDF quad in content space. Engine quads carry frame-geometric
36
+ * slot semantics (`p1..p4` = upper-start, upper-end, lower-start,
37
+ * lower-end) — a trusted producer, so the y-flip maps corners straight onto
38
+ * their names; imported-annotation normalization does NOT apply here.
39
+ */
40
+ declare function toContentTextQuad(geom: SelectionPageGeometry, quad: PdfQuad): TextQuad;
41
+ /** A canonical segment in content space (`rect` recomputed from the mapped
42
+ * quad so the pair can never drift). */
43
+ declare function toContentSegment(geom: SelectionPageGeometry, segment: PdfTextSegment): SelectionSegment;
44
+ //#endregion
5
45
  //#region src/types.d.ts
6
46
  /** A glyph address: a page + a flat glyph index within that page's geometry. */
7
47
  interface GlyphPointer {
@@ -13,14 +53,24 @@ interface SelectionRange {
13
53
  anchor: GlyphPointer;
14
54
  focus: GlyphPointer;
15
55
  }
56
+ /**
57
+ * A selection boundary, anchored to the boundary GLYPH's own oriented cell.
58
+ * `advance` is the reading direction of the segment it belongs to (+1 = the
59
+ * frame's +x), so caret consumers place at the trailing edge without
60
+ * re-deriving bidi from geometry. `rect` is the AABB (scroll targets).
61
+ */
16
62
  interface SelectionEndpoint {
17
63
  pon: PageObjectNumber;
64
+ glyphQuad: TextQuad;
65
+ advance: 1 | -1;
18
66
  rect: Rect;
19
67
  }
20
68
  interface SelectionSnapshot {
69
+ /** Per-page canonical segments — the ONE geometry consumers act on.
70
+ * Boxes are derived views (`segment.rect`, or `rectsForPage()`). */
21
71
  pages: Array<{
22
72
  pon: PageObjectNumber;
23
- rects: Rect[];
73
+ segments: SelectionSegment[];
24
74
  }>;
25
75
  start: SelectionEndpoint | null;
26
76
  end: SelectionEndpoint | null;
@@ -28,8 +78,8 @@ interface SelectionSnapshot {
28
78
  }
29
79
  interface SelectionState {
30
80
  selection: SelectionRange | null;
31
- /** Derived highlight rects per page, in CONTENT space (y-down, PDF units). */
32
- rects: Record<number, Rect[]>;
81
+ /** Derived per-line segments per page, in CONTENT space (y-down, PDF units). */
82
+ segments: Record<number, SelectionSegment[]>;
33
83
  /** Pages whose text geometry has loaded (so the layer re-renders when ready). */
34
84
  loaded: Record<number, boolean>;
35
85
  /** When a consumer owns the selection visual (e.g. a markup tool draws its own
@@ -42,7 +92,7 @@ type SelectionAction = {
42
92
  } | {
43
93
  type: 'SET';
44
94
  selection: SelectionRange;
45
- rects: Record<number, Rect[]>;
95
+ segments: Record<number, SelectionSegment[]>;
46
96
  } | {
47
97
  type: 'CLEAR';
48
98
  } | {
@@ -67,7 +117,11 @@ interface SelectionCapability {
67
117
  clear(): void;
68
118
  /** Coherent read-model for consumers that create annotations or selection UI. */
69
119
  snapshot(): SelectionSnapshot;
70
- /** Highlight rects for a page, in content space — the layer's only input. */
120
+ /** Per-line oriented segments for a page, in content space — the layer's input. */
121
+ segmentsForPage(pon: PageObjectNumber): SelectionSegment[];
122
+ /** The segments' AABBs — for consumers that genuinely want boxes (scroll,
123
+ * conservative regions). Never a substitute for the oriented quads in
124
+ * geometry that gets drawn or persisted. */
71
125
  rectsForPage(pon: PageObjectNumber): Rect[];
72
126
  hasSelection(): boolean;
73
127
  /** The pages the current selection covers (those with at least one rect) — so a
@@ -95,13 +149,15 @@ declare const selectionPlugin: () => import("@embedpdf/core").PluginDef<Selectio
95
149
  //#region src/capability.d.ts
96
150
  /**
97
151
  * The selection capability. The reducer state holds the selection range, the
98
- * derived content-space rects (per page), and per-page loaded flags; the (large,
99
- * non-serializable) per-page text geometry is cached HERE in the closure.
152
+ * derived content-space segments (per page), and per-page loaded flags; the
153
+ * (large, non-serializable) per-page canonical layout is cached HERE in the
154
+ * closure. Segmentation itself is the engine-core text layout — selection
155
+ * owns gestures and state, never how glyphs become lines.
100
156
  *
101
- * Selection is cross-page: glyphs are ordered globally by (pageIndex, glyph), so
102
- * a drag from page 2 into page 4 selects the tail of 2, all of 3, and the head of
103
- * 4. `recompute` rebuilds the merged line rects for every loaded page in the span
104
- * and re-runs whenever a mid-span page finishes loading.
157
+ * Selection is cross-page: glyphs are ordered globally by (pageIndex, glyph),
158
+ * so a drag from page 2 into page 4 selects the tail of 2, all of 3, and the
159
+ * head of 4. `recompute` rebuilds the merged line segments for every loaded
160
+ * page in the span and re-runs whenever a mid-span page finishes loading.
105
161
  */
106
162
  declare function createSelectionCapability(ctx: PluginContext<SelectionState, SelectionAction>): SelectionCapability;
107
163
  //#endregion
@@ -125,43 +181,5 @@ declare function createTextSelectHandler(selection: SelectionCapability, interac
125
181
  declare const initialSelectionState: SelectionState;
126
182
  declare const selectionReducer: (state: SelectionState, action: SelectionAction) => SelectionState;
127
183
  //#endregion
128
- //#region src/geometry.d.ts
129
- /** One glyph in content space. `loose` builds selection rects; `tight` hit-tests. */
130
- interface GlyphInfo {
131
- loose: Rect;
132
- tight?: Rect;
133
- flags: number;
134
- }
135
- /** A contiguous run of glyphs (a text object). `rect` is its loose enclosing box. */
136
- interface RunInfo {
137
- start: number;
138
- count: number;
139
- rect: Rect;
140
- fontSize?: number;
141
- }
142
- /** A page's text laid out in content space: a flat glyph list + the run structure. */
143
- interface PageText {
144
- glyphs: GlyphInfo[];
145
- runs: RunInfo[];
146
- }
147
- /**
148
- * Flatten a page's text geometry into content-space glyphs + runs. Rotation does
149
- * NOT enter here — the overlay rides the page's CSS rotation, so glyphs stay in
150
- * un-rotated content space (the crop-relative y-flip is the only conversion).
151
- */
152
- declare function buildPageText(snapshot: PageGeometrySnapshot, crop: PdfRect, rotation: 0 | 90 | 180 | 270, userUnit: number): PageText;
153
- /**
154
- * The glyph index at a content-space point, or null when nothing is near (so the
155
- * caller can show the pointer cursor off-text). PDFium `GetIndexAtPos`: exact
156
- * tight-box containment first, then a tolerance pass (closest by Manhattan
157
- * distance within `toleranceFactor × average glyph height`).
158
- */
159
- declare function glyphAt(text: PageText, p: Point, toleranceFactor?: number): number | null;
160
- /** Double-click: the word around `i` (walk to space/empty glyphs both ways). */
161
- declare function expandToWord(text: PageText, i: number): [number, number];
162
- /** Triple-click: the full visual line — runs whose vertical extent overlaps the anchor run's. */
163
- declare function expandToLine(text: PageText, i: number): [number, number];
164
- declare function rectsForRange(text: PageText, from: number, to: number): Rect[];
165
- //#endregion
166
- export { type GlyphInfo, type GlyphPointer, type PageText, type RunInfo, type SelectionAction, type SelectionCapability, type SelectionEndpoint, type SelectionRange, type SelectionSnapshot, type SelectionState, SelectionToken, buildPageText, createSelectionCapability, createTextSelectHandler, expandToLine, expandToWord, glyphAt, initialSelectionState, rectsForRange, selectionPlugin, selectionReducer };
184
+ export { type GlyphPointer, type SelectionAction, type SelectionCapability, type SelectionEndpoint, type SelectionPageGeometry, type SelectionRange, type SelectionSegment, type SelectionSnapshot, type SelectionState, SelectionToken, buildSelectionPageGeometry, contentPointToPdf, createSelectionCapability, createTextSelectHandler, initialSelectionState, selectionPlugin, selectionReducer, toContentSegment, toContentTextQuad };
167
185
  //# sourceMappingURL=index.d.ts.map