@embedpdf/plugin-annotation 3.0.0-next.9 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +129 -0
  2. package/dist/authoring.cjs +26 -0
  3. package/dist/authoring.d.cts +2 -0
  4. package/dist/authoring.d.ts +2 -0
  5. package/dist/authoring.js +2 -0
  6. package/dist/contract/host.cjs +19 -0
  7. package/dist/contract/host.d.cts +3 -0
  8. package/dist/contract/host.d.ts +3 -0
  9. package/dist/contract/host.js +3 -0
  10. package/dist/contract-BK2g1Rem.d.ts +1169 -0
  11. package/dist/contract-BtAl3Yo2.cjs +692 -0
  12. package/dist/contract-BtAl3Yo2.cjs.map +1 -0
  13. package/dist/contract-CBYEqnev.d.cts +1169 -0
  14. package/dist/contract-OwgW3JE8.js +651 -0
  15. package/dist/contract-OwgW3JE8.js.map +1 -0
  16. package/dist/contract.cjs +13 -0
  17. package/dist/contract.d.cts +2 -0
  18. package/dist/contract.d.ts +2 -0
  19. package/dist/contract.js +2 -0
  20. package/dist/host-contract-BzM2upsA.cjs +87 -0
  21. package/dist/host-contract-BzM2upsA.cjs.map +1 -0
  22. package/dist/host-contract-COF2Prd-.d.ts +335 -0
  23. package/dist/host-contract-CSKiuu3g.js +52 -0
  24. package/dist/host-contract-CSKiuu3g.js.map +1 -0
  25. package/dist/host-contract-CxOrR_pp.d.cts +335 -0
  26. package/dist/index.cjs +5434 -419
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +13 -59
  29. package/dist/index.d.ts +13 -59
  30. package/dist/index.js +5386 -398
  31. package/dist/index.js.map +1 -1
  32. package/package.json +24 -11
  33. package/dist/capability-2FkTVblD.cjs +0 -2806
  34. package/dist/capability-2FkTVblD.cjs.map +0 -1
  35. package/dist/capability-BNMRdnKf.js +0 -2741
  36. package/dist/capability-BNMRdnKf.js.map +0 -1
  37. package/dist/internal.cjs +0 -5
  38. package/dist/internal.d.cts +0 -13
  39. package/dist/internal.d.ts +0 -13
  40. package/dist/internal.js +0 -2
  41. package/dist/types-CvtDbnF5.d.cts +0 -912
  42. package/dist/types-Dy1RganE.d.ts +0 -912
@@ -1,2741 +0,0 @@
1
- import { CONTINUOUS_RENDER_POLICY, createCapabilityToken, snapAppearanceScale } from "@embedpdf/core";
2
- import { InteractionToken } from "@embedpdf/plugin-interaction";
3
- import { resolveBinarySource, sniffBinaryMetadata } from "@embedpdf/engine-core/runtime";
4
- import { SelectionToken } from "@embedpdf/plugin-selection";
5
- import { FLAG_KEYS, calloutLinePoints, canMove, chrome, clickCreateGeom, cloudyBorderExtent, contentToPdfPoint, contentToPdfRect, contentToPdfRect as contentToPdfRect$1, creationDraftAnchor, cursorAt, defaultsFor, expandGroups, fitStampBox, geomPdfBounds, geomRotation, geomVisualBounds, groupKeyOf, hitTest, initialTextStyle, normalizeDeg, pageItems, pdfToContentPoint, pdfToContentPoint as pdfToContentPoint$1, pdfToContentRect, pdfToContentRect as pdfToContentRect$1, propsFor, readProp, resolveClickPlacement, rotatedAabb, selectionAnchor, selectionQuad, sharedProps, styleFromProps, textBoxes, unionRect, update, uprightRotation, viewable } from "@embedpdf/core-annotation";
6
- import { normalizeQuad, textQuadBounds } from "@embedpdf/core-geometry";
7
- //#region src/types.ts
8
- /**
9
- * The annotation capability token. Typed to the full {@link AnnotationHostCapability}
10
- * here (the package internals + the `/internal` entry use this view). The package
11
- * root re-exports the SAME token narrowed to {@link AnnotationCapability}.
12
- */
13
- const AnnotationToken = createCapabilityToken("annotation", { hint: `add annotationPlugin() from '@embedpdf/plugin-annotation' to your plugins list` });
14
- //#endregion
15
- //#region src/repository/seam.ts
16
- function refKey(ref) {
17
- return ref.kind === "objectNumber" ? `obj:${ref.annotObjectNumber}` : ref.kind === "nm" ? `nm:${ref.nm}` : `idx:${ref.pageObjectNumber}:${ref.index}`;
18
- }
19
- const h2 = (n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, "0");
20
- const colorToCss = (c) => `#${h2(c.r)}${h2(c.g)}${h2(c.b)}`;
21
- function cssToColor(css) {
22
- const s = css.trim();
23
- const m6 = /^#?([0-9a-f]{6})$/i.exec(s);
24
- if (m6) {
25
- const n = parseInt(m6[1], 16);
26
- return {
27
- r: n >> 16 & 255,
28
- g: n >> 8 & 255,
29
- b: n & 255
30
- };
31
- }
32
- const m3 = /^#?([0-9a-f]{3})$/i.exec(s);
33
- if (m3) {
34
- const [a, b, c] = m3[1];
35
- return {
36
- r: parseInt(a + a, 16),
37
- g: parseInt(b + b, 16),
38
- b: parseInt(c + c, 16)
39
- };
40
- }
41
- return {
42
- r: 0,
43
- g: 0,
44
- b: 0
45
- };
46
- }
47
- const toPdfRotation = (rotCW) => normalizeDeg(-rotCW);
48
- const fromPdfRotation = (rotPdf) => normalizeDeg(-rotPdf);
49
- /** Advisory `rot` for a vertex geom, from a DTO's (PDF-convention) `rotation`.
50
- * Absent → no `rot` key (kept off the geom so unrotated shapes stay clean). */
51
- const rotFromDTO = (rotation) => rotation ? { rot: fromPdfRotation(rotation) } : {};
52
- /**
53
- * Geometry/rotation fields for a BOX kind (square/circle/plain free-text). The
54
- * model's `rect` is the UNROTATED logical box and `rot` the applied tilt, so:
55
- * - rot == 0 → `/Rect` IS the box; the transform pair is stated as `null`
56
- * (TOTAL projection — the engine's tri-state writes preserve omissions, so
57
- * an omitted field would keep a stale rotation instead of flattening it).
58
- * - rot != 0 → `/Rect` is the rotated visual AABB (PDFium clips the baked /AP
59
- * to it), `unrotatedRect` the logical box, `rotation` the PDF angle.
60
- */
61
- function boxGeomFields(rect, rot, crop) {
62
- if (!rot) return {
63
- rect: contentToPdfRect(rect, crop),
64
- rotation: null,
65
- unrotatedRect: null
66
- };
67
- return {
68
- rect: contentToPdfRect(rotatedAabb(rect, rot), crop),
69
- unrotatedRect: contentToPdfRect(rect, crop),
70
- rotation: toPdfRotation(rot)
71
- };
72
- }
73
- /** A box geom (square/circle/stamp) from its DTO: when rotated, the LOCAL box
74
- * is the stored `unrotatedRect` (the AABB `/Rect` is the rendered envelope)
75
- * and `rot` the converted tilt; unrotated, `/Rect` IS the box. */
76
- function boxGeomFromDTO(dto, rotation, unrotatedRect, crop, ellipse) {
77
- const rot = rotation ? fromPdfRotation(rotation) : 0;
78
- return {
79
- t: "rect",
80
- rect: pdfToContentRect(rot && unrotatedRect ? unrotatedRect : dto.rect, crop),
81
- ellipse,
82
- ...rot ? { rot } : {}
83
- };
84
- }
85
- /** Inset a PdfRect by a `/RD` (PDF user space, y-up: all four are non-negative
86
- * insets from the matching `/Rect` edge). Used to recover the callout text box. */
87
- const insetPdfRectByRD = (r, rd) => rd ? {
88
- left: r.left + rd.left,
89
- bottom: r.bottom + rd.bottom,
90
- right: r.right - rd.right,
91
- top: r.top - rd.top
92
- } : r;
93
- /** Engine border fields (`/BS /S`, `/BS /D`, `/BE /I`) → the `Border` union. A
94
- * cloudy effect wins over the underlying border style (which stays solid). */
95
- function borderFromDTO(d) {
96
- if ((d.cloudyIntensity ?? 0) > 0) return {
97
- kind: "cloudy",
98
- intensity: d.cloudyIntensity
99
- };
100
- if (d.borderStyle === "dashed") return {
101
- kind: "dashed",
102
- dash: d.dashArray?.length ? d.dashArray : [3, 3]
103
- };
104
- return { kind: "solid" };
105
- }
106
- /** The writable projection of a `link` value: `goto`/`uri` pass through,
107
- * read-only arms (`javascript`, `named`, `goto-remote`, `launch`,
108
- * `unsupported`) yield `null` — they can be carried, never (re)written. */
109
- function writableTarget(t) {
110
- return t && (t.kind === "goto" || t.kind === "uri") ? t : null;
111
- }
112
- const TEXT_MARKUP = /* @__PURE__ */ new Set([
113
- "highlight",
114
- "underline",
115
- "squiggly",
116
- "strikeout"
117
- ]);
118
- const STROKE_KINDS = /* @__PURE__ */ new Set([
119
- "square",
120
- "circle",
121
- "line",
122
- "polygon",
123
- "polyline",
124
- "ink"
125
- ]);
126
- /** Engine DTO → content-space `Style` (CSS colours, `Border` union). Exported so
127
- * selection-aware UIs can read display values straight off a {@link AnnotationDTO}
128
- * without re-deriving the colour/border mapping. */
129
- function styleFromDTO(dto) {
130
- if (dto.subtype === "widget") return {
131
- color: dto.color ? colorToCss(dto.color) : "#1a1a1a",
132
- interiorColor: dto.interiorColor ? colorToCss(dto.interiorColor) : null,
133
- strokeWidth: dto.strokeWidth,
134
- opacity: 1,
135
- blendMode: dto.blendMode,
136
- border: dto.borderStyle === "dashed" ? {
137
- kind: "dashed",
138
- dash: [3, 3]
139
- } : { kind: "solid" }
140
- };
141
- if (STROKE_KINDS.has(dto.subtype)) {
142
- const d = dto;
143
- return {
144
- color: colorToCss(d.color),
145
- interiorColor: d.interiorColor ? colorToCss(d.interiorColor) : null,
146
- strokeWidth: d.strokeWidth,
147
- opacity: d.opacity,
148
- blendMode: dto.blendMode,
149
- border: borderFromDTO(d)
150
- };
151
- }
152
- if (TEXT_MARKUP.has(dto.subtype)) {
153
- const d = dto;
154
- return {
155
- color: colorToCss(d.color),
156
- interiorColor: null,
157
- strokeWidth: 0,
158
- opacity: d.opacity,
159
- blendMode: dto.blendMode,
160
- border: { kind: "solid" }
161
- };
162
- }
163
- if (dto.subtype === "caret") {
164
- const d = dto;
165
- return {
166
- color: colorToCss(d.color),
167
- interiorColor: null,
168
- strokeWidth: 1,
169
- opacity: d.opacity,
170
- blendMode: dto.blendMode,
171
- border: { kind: "solid" }
172
- };
173
- }
174
- if (dto.subtype === "free-text") {
175
- const d = dto;
176
- return {
177
- color: colorToCss(d.color),
178
- interiorColor: d.interiorColor ? colorToCss(d.interiorColor) : null,
179
- strokeWidth: d.strokeWidth,
180
- opacity: d.opacity,
181
- blendMode: dto.blendMode,
182
- border: borderFromDTO(d)
183
- };
184
- }
185
- if (dto.subtype === "redact") {
186
- const d = dto;
187
- return {
188
- color: colorToCss(d.color),
189
- interiorColor: d.interiorColor ? colorToCss(d.interiorColor) : null,
190
- strokeWidth: 1.5,
191
- opacity: d.opacity,
192
- blendMode: dto.blendMode,
193
- border: { kind: "solid" }
194
- };
195
- }
196
- if (dto.subtype === "text" || dto.subtype === "file-attachment") {
197
- const d = dto;
198
- return {
199
- color: colorToCss(d.color),
200
- interiorColor: null,
201
- strokeWidth: 1,
202
- opacity: d.opacity,
203
- blendMode: dto.blendMode,
204
- border: { kind: "solid" }
205
- };
206
- }
207
- return {
208
- color: "#444444",
209
- interiorColor: null,
210
- strokeWidth: 1,
211
- opacity: 1,
212
- blendMode: dto.blendMode,
213
- border: { kind: "solid" }
214
- };
215
- }
216
- /**
217
- * The flat props vocabulary (CSS colours, house keys) → the engine's widget
218
- * appearance for `doc.forms` authoring — the SAME mapping the widget patch
219
- * lowering uses, exported as a boundary utility so the form plugin can style
220
- * `placeField` from a tool's `currentDefaults` without growing a second CSS
221
- * parser. Absent keys stay absent (the engine writes nothing for them).
222
- */
223
- function widgetAppearanceFromProps(props) {
224
- return {
225
- ...props.color !== void 0 ? { color: cssToColor(props.color) } : {},
226
- ...props.interiorColor !== void 0 ? { interiorColor: props.interiorColor ? cssToColor(props.interiorColor) : null } : {},
227
- ...props.strokeWidth !== void 0 ? { strokeWidth: props.strokeWidth } : {},
228
- ...props.border !== void 0 ? { borderStyle: props.border.kind === "dashed" ? "dashed" : "solid" } : {},
229
- ...props.fontFamily !== void 0 ? { fontFamily: props.fontFamily } : {},
230
- ...props.fontSize !== void 0 ? { fontSize: props.fontSize } : {},
231
- ...props.fontColor !== void 0 ? { fontColor: cssToColor(props.fontColor) } : {},
232
- ...props.textAlign !== void 0 ? { textAlign: props.textAlign } : {}
233
- };
234
- }
235
- //#endregion
236
- //#region src/repository/props.ts
237
- /**
238
- * GENERIC per-key prop lowerings — the 1:1 mappings from the flat props
239
- * vocabulary to wire fields that hold for every kind that declares the key.
240
- * Kind modules override ONLY their exceptions (a coupling lives in its
241
- * owner's file: cloudy `/RD` in shape.ts, visual-bounds `/Rect` in stroke.ts,
242
- * the link target in link.ts).
243
- */
244
- /** /BS slice of the style — a cloudy border keeps a solid underlying stroke
245
- * (the scallops are the /BE effect, layered on by the shape kinds). */
246
- const borderSlice = (style) => ({
247
- borderStyle: style.border.kind === "dashed" ? "dashed" : "solid",
248
- ...style.border.kind === "dashed" ? { dashArray: style.border.dash } : {}
249
- });
250
- /** The `/DA`-styled text slice falls back to the draw-time seed exactly like
251
- * the old projections did (a fresh draft may not carry `text` yet). */
252
- const textOf = (a) => a.text ?? initialTextStyle;
253
- const GENERIC_PROPS = {
254
- color: (a) => ({ color: cssToColor(a.style.color) }),
255
- opacity: (a) => ({ opacity: a.style.opacity }),
256
- blendMode: (a) => ({ blendMode: a.style.blendMode }),
257
- interiorColor: (a) => ({ interiorColor: a.style.interiorColor ? cssToColor(a.style.interiorColor) : null }),
258
- strokeWidth: (a) => ({ strokeWidth: a.style.strokeWidth }),
259
- border: (a) => borderSlice(a.style),
260
- fontFamily: (a) => ({ fontFamily: textOf(a).fontFamily }),
261
- fontSize: (a) => ({ fontSize: textOf(a).fontSize }),
262
- fontColor: (a) => ({ fontColor: cssToColor(textOf(a).fontColor) }),
263
- textAlign: (a) => ({ textAlign: textOf(a).textAlign }),
264
- icon: (a) => a.icon !== void 0 ? { icon: a.icon } : {},
265
- link: () => ({})
266
- };
267
- //#endregion
268
- //#region src/repository/projection.ts
269
- /** Box-kind geometry emission: the model's unrotated `rect` + applied tilt →
270
- * `/Rect`(+`unrotatedRect`+`rotation`), total (nulls state the clears). */
271
- const boxEmit = (a, crop) => {
272
- const g = a.geom;
273
- return boxGeomFields(g.rect, geomRotation(a.geom), crop);
274
- };
275
- //#endregion
276
- //#region src/repository/kinds/shape.ts
277
- /** Cloudy `/BE` + `/RD` for a rect shape — TOTAL: the non-cloudy state is
278
- * stated as `null` (tri-state remove), never omitted, so toggling cloudy OFF
279
- * removes the stale inset (the Adobe phantom-padding bug). */
280
- function cloudyExtras(a) {
281
- if (a.geom.t !== "rect") return {};
282
- if (a.style.border.kind === "cloudy") {
283
- const inset = cloudyBorderExtent(a.style.border.intensity, a.style.strokeWidth, a.geom.ellipse);
284
- return {
285
- cloudyIntensity: a.style.border.intensity,
286
- rectDifferences: {
287
- left: inset,
288
- top: inset,
289
- right: inset,
290
- bottom: inset
291
- }
292
- };
293
- }
294
- return {
295
- cloudyIntensity: null,
296
- rectDifferences: null
297
- };
298
- }
299
- const ingest = (dto, crop, ellipse) => {
300
- const d = dto;
301
- return { geom: boxGeomFromDTO(d, d.rotation, d.unrotatedRect, crop, ellipse) };
302
- };
303
- const projection = (ellipse) => ({
304
- ingest: (dto, crop) => ingest(dto, crop, ellipse),
305
- geometry: (a, crop) => boxEmit(a, crop),
306
- prop: {
307
- strokeWidth: (a) => ({
308
- strokeWidth: a.style.strokeWidth,
309
- ...cloudyExtras(a)
310
- }),
311
- border: (a) => ({
312
- ...borderSlice(a.style),
313
- ...cloudyExtras(a)
314
- })
315
- }
316
- });
317
- const square = projection(false);
318
- const circle = projection(true);
319
- //#endregion
320
- //#region src/repository/kinds/stroke.ts
321
- /** Advisory rotation, TOTAL: rotation 0 states `null` (tri-state clear) —
322
- * omission would preserve a stale advisory angle. */
323
- const advisoryRotation = (g) => {
324
- const rot = geomRotation(g);
325
- return { rotation: rot ? toPdfRotation(rot) : null };
326
- };
327
- /** `/BE` intensity for a closed poly (polygon): the curls are generated from
328
- * /Vertices + /BE alone — per ISO 32000 no /RD applies — and the /Rect
329
- * (geomPdfBounds WITH the border) already includes the outward cloud extent. */
330
- const polyCloudy = (a) => a.geom.t === "poly" && a.geom.closed ? { cloudyIntensity: a.style.border.kind === "cloudy" ? a.style.border.intensity : null } : {};
331
- /** The visual-bounds `/Rect` (stroke + border included) of a stroke geom. */
332
- const visualRect = (a, crop) => {
333
- const g = a.geom;
334
- if (g.t === "line" || g.t === "ink") return { rect: geomPdfBounds(g, a.style.strokeWidth, crop) };
335
- if (g.t === "poly") return { rect: geomPdfBounds(g, a.style.strokeWidth, crop, a.style.border) };
336
- return {};
337
- };
338
- /** Stroke-family prop exceptions: width and border feed the derived /Rect. */
339
- const strokeProps = {
340
- strokeWidth: (a, crop) => ({
341
- strokeWidth: a.style.strokeWidth,
342
- ...visualRect(a, crop)
343
- }),
344
- border: (a, crop) => ({
345
- ...borderSlice(a.style),
346
- ...polyCloudy(a),
347
- ...a.geom.t === "poly" && a.geom.closed ? visualRect(a, crop) : {}
348
- }),
349
- lineEndings: (a) => (a.geom.t === "line" || a.geom.t === "poly") && a.geom.ends ? { lineEndings: a.geom.ends } : {}
350
- };
351
- const line = {
352
- ingest: (dto, crop) => {
353
- const d = dto;
354
- return { geom: {
355
- t: "line",
356
- a: pdfToContentPoint(d.linePoints.start, crop),
357
- b: pdfToContentPoint(d.linePoints.end, crop),
358
- ends: d.lineEndings,
359
- ...rotFromDTO(d.rotation)
360
- } };
361
- },
362
- geometry: (a, crop) => {
363
- const g = a.geom;
364
- if (g.t !== "line") return null;
365
- return {
366
- linePoints: {
367
- start: contentToPdfPoint(g.a, crop),
368
- end: contentToPdfPoint(g.b, crop)
369
- },
370
- ...visualRect(a, crop),
371
- ...advisoryRotation(g)
372
- };
373
- },
374
- prop: strokeProps
375
- };
376
- const polyProjection = (closed) => ({
377
- ingest: (dto, crop) => {
378
- const d = dto;
379
- return { geom: {
380
- t: "poly",
381
- points: d.vertices.map((p) => pdfToContentPoint(p, crop)),
382
- closed,
383
- ..."lineEndings" in d ? { ends: d.lineEndings } : {},
384
- ...rotFromDTO(d.rotation)
385
- } };
386
- },
387
- geometry: (a, crop) => {
388
- const g = a.geom;
389
- if (g.t !== "poly") return null;
390
- return {
391
- vertices: g.points.map((p) => contentToPdfPoint(p, crop)),
392
- ...visualRect(a, crop),
393
- ...advisoryRotation(g)
394
- };
395
- },
396
- prop: strokeProps
397
- });
398
- const polygon = polyProjection(true);
399
- const polyline = polyProjection(false);
400
- const ink = {
401
- ingest: (dto, crop) => {
402
- const d = dto;
403
- return {
404
- geom: {
405
- t: "ink",
406
- strokes: d.inkList.map((stroke) => stroke.map((p) => pdfToContentPoint(p, crop))),
407
- ...rotFromDTO(d.rotation)
408
- },
409
- ...d.intent ? { intent: d.intent } : {}
410
- };
411
- },
412
- geometry: (a, crop) => {
413
- const g = a.geom;
414
- if (g.t !== "ink") return null;
415
- return {
416
- inkList: g.strokes.map((stroke) => stroke.map((p) => contentToPdfPoint(p, crop))),
417
- ...visualRect(a, crop),
418
- ...advisoryRotation(g)
419
- };
420
- },
421
- prop: strokeProps,
422
- draftExtras: (a) => a.intent === "ink-highlight" ? { intent: a.intent } : {}
423
- };
424
- //#endregion
425
- //#region src/repository/kinds/freeText.ts
426
- /** Free-text `/DA` fields → content {@link TextStyle}. An absent `fontColor`
427
- * falls back to the `/DA` colour — the same rule the CPVT renderer applies. */
428
- function textFromDTO(dto) {
429
- return {
430
- fontFamily: dto.fontFamily,
431
- fontSize: dto.fontSize,
432
- fontColor: colorToCss(dto.fontColor ?? dto.color),
433
- textAlign: dto.textAlign
434
- };
435
- }
436
- /**
437
- * The engine geometry for a callout: the overall `/Rect` (text box ∪ leader ∪
438
- * arrow), the `/RD` inset that recovers the text box from it, the `/CL` leader
439
- * (`[tip, knee, conn]` with the connection point derived), and the `/LE`
440
- * ending. All in PDF user space (y-up), with every `/RD` inset clamped
441
- * non-negative.
442
- *
443
- * A tilted box (the upright policy) additionally emits `rotation` +
444
- * `unrotatedRect` (the logical text box) — the engine bakes the box + text
445
- * under an INLINE rotation about the box centre while the leader stays
446
- * page-space, so (unlike plain boxes) the /AP form `/Matrix` stays identity
447
- * and the raster stays placed by `/Rect`. `/RD` then insets to the ROTATED
448
- * box's AABB — the best axis-aligned text box a foreign viewer regenerating
449
- * the AP can draw (spec-conformant degradation). The transform pair is TOTAL
450
- * (nulls state the clears) like every box emission.
451
- */
452
- function calloutFields(a, crop) {
453
- const g = a.geom;
454
- if (g.t !== "text" || !g.callout) return null;
455
- const rot = geomRotation(g);
456
- const overall = geomPdfBounds(g, a.style.strokeWidth, crop);
457
- const tb = contentToPdfRect$1(rot ? rotatedAabb(g.rect, rot) : g.rect, crop);
458
- const nn = (n) => Math.max(0, n);
459
- const pts = calloutLinePoints(g).map((p) => contentToPdfPoint(p, crop));
460
- const calloutLine = pts.length === 3 ? [
461
- pts[0],
462
- pts[1],
463
- pts[2]
464
- ] : [pts[0], pts[1]];
465
- return {
466
- rect: overall,
467
- rectDifferences: {
468
- left: nn(tb.left - overall.left),
469
- bottom: nn(tb.bottom - overall.bottom),
470
- right: nn(overall.right - tb.right),
471
- top: nn(overall.top - tb.top)
472
- },
473
- calloutLine,
474
- lineEnding: g.callout.ending,
475
- ...rot ? {
476
- rotation: toPdfRotation(rot),
477
- unrotatedRect: contentToPdfRect$1(g.rect, crop)
478
- } : {
479
- rotation: null,
480
- unrotatedRect: null
481
- }
482
- };
483
- }
484
- const freeText = {
485
- ingest: (dto, crop) => {
486
- const d = dto;
487
- if (d.intent === "free-text-callout" && d.calloutLine && d.calloutLine.length >= 2) {
488
- const cl = d.calloutLine;
489
- const rot = d.rotation ? fromPdfRotation(d.rotation) : 0;
490
- return {
491
- geom: {
492
- t: "text",
493
- rect: rot && d.unrotatedRect ? pdfToContentRect$1(d.unrotatedRect, crop) : pdfToContentRect$1(insetPdfRectByRD(d.rect, d.rectDifferences), crop),
494
- callout: {
495
- tip: pdfToContentPoint$1(cl[0], crop),
496
- knee: cl.length === 3 ? pdfToContentPoint$1(cl[1], crop) : void 0,
497
- ending: d.lineEnding ?? "none"
498
- },
499
- ...rot && d.unrotatedRect ? { rot } : {}
500
- },
501
- text: textFromDTO(d)
502
- };
503
- }
504
- const rot = d.rotation ? fromPdfRotation(d.rotation) : 0;
505
- return {
506
- geom: {
507
- t: "text",
508
- rect: pdfToContentRect$1(rot && d.unrotatedRect ? d.unrotatedRect : d.rect, crop),
509
- ...rot ? { rot } : {}
510
- },
511
- text: textFromDTO(d)
512
- };
513
- },
514
- geometry: (a, crop) => {
515
- if (a.geom.t !== "text") return null;
516
- const cf = calloutFields(a, crop);
517
- if (cf) return { ...cf };
518
- return boxEmit(a, crop);
519
- },
520
- draftExtras: (a, crop) => ({
521
- intent: calloutFields(a, crop) ? "free-text-callout" : "free-text",
522
- contents: a.data?.contents ?? ""
523
- })
524
- };
525
- //#endregion
526
- //#region src/repository/kinds/quads.ts
527
- /**
528
- * Imported `/QuadPoints` → semantic TextQuads. `normalizeQuad` is a
529
- * NORMALIZER, not a cast: the de-facto zigzag order passes through, ring-order
530
- * producers are repaired, and garbage gets a deterministic labeling — so
531
- * drawing code can never put an underline on the wrong edge of a well-formed
532
- * quad, rotated ones included.
533
- */
534
- const quadsFromDTO = (quadPoints, crop) => quadPoints.map((q) => normalizeQuad({
535
- p1: pdfToContentPoint$1(q.p1, crop),
536
- p2: pdfToContentPoint$1(q.p2, crop),
537
- p3: pdfToContentPoint$1(q.p3, crop),
538
- p4: pdfToContentPoint$1(q.p4, crop)
539
- }));
540
- /** Content quads → engine `/QuadPoints` (PDF user space, zigzag slot order:
541
- * p1..p4 = upper-start, upper-end, lower-start, lower-end — under the y-flip
542
- * exactly PDFium's documented TL, TR, BL, BR); null off quads geom. */
543
- function quadPointsFor(a, crop) {
544
- if (a.geom.t !== "quads") return null;
545
- return a.geom.quads.map((q) => ({
546
- p1: contentToPdfPoint(q.upperStart, crop),
547
- p2: contentToPdfPoint(q.upperEnd, crop),
548
- p3: contentToPdfPoint(q.lowerStart, crop),
549
- p4: contentToPdfPoint(q.lowerEnd, crop)
550
- }));
551
- }
552
- /** PDF-space bounding box of a set of `/QuadPoints` quads — the `/Rect` a
553
- * quad-bearing draft must carry alongside its quads. */
554
- const pdfBoundsOfQuads = (quads) => {
555
- let left = Infinity;
556
- let bottom = Infinity;
557
- let right = -Infinity;
558
- let top = -Infinity;
559
- for (const q of quads) for (const p of [
560
- q.p1,
561
- q.p2,
562
- q.p3,
563
- q.p4
564
- ]) {
565
- if (p.x < left) left = p.x;
566
- if (p.x > right) right = p.x;
567
- if (p.y < bottom) bottom = p.y;
568
- if (p.y > top) top = p.y;
569
- }
570
- return {
571
- left,
572
- bottom,
573
- right,
574
- top
575
- };
576
- };
577
- const markupProjection = (subtype) => {
578
- return {
579
- ingest: (dto, crop) => {
580
- const d = dto;
581
- return {
582
- geom: {
583
- t: "quads",
584
- quads: quadsFromDTO(d.quadPoints, crop)
585
- },
586
- ...subtype === "strikeout" && "intent" in d && d.intent ? { intent: d.intent } : {}
587
- };
588
- },
589
- geometry: () => null,
590
- draftExtras: (a, crop) => {
591
- const quads = quadPointsFor(a, crop);
592
- if (!quads) return null;
593
- return {
594
- quadPoints: quads,
595
- ...subtype === "strikeout" && a.intent === "strikeout-text-edit" ? { intent: a.intent } : {}
596
- };
597
- }
598
- };
599
- };
600
- const highlight = markupProjection("highlight");
601
- const underline = markupProjection("underline");
602
- const squiggly = markupProjection("squiggly");
603
- const strikeout = markupProjection("strikeout");
604
- const caret = {
605
- ingest: (dto, crop) => {
606
- const d = dto;
607
- const rot = d.rotation ? fromPdfRotation(d.rotation) : 0;
608
- return {
609
- geom: {
610
- t: "caret",
611
- rect: pdfToContentRect$1(rot && d.unrotatedRect ? d.unrotatedRect : d.rect, crop),
612
- ...rot ? { rot } : {}
613
- },
614
- ...d.intent ? { intent: d.intent } : {}
615
- };
616
- },
617
- geometry: (a, crop) => a.geom.t === "caret" ? boxGeomFields(a.geom.rect, a.geom.rot ?? 0, crop) : null,
618
- draftExtras: (a) => ({
619
- rectDifferences: {
620
- left: .5,
621
- top: .5,
622
- right: .5,
623
- bottom: .5
624
- },
625
- ...a.intent === "replace" ? { intent: a.intent } : {},
626
- ...a.data?.contents != null ? { contents: a.data.contents } : {}
627
- })
628
- };
629
- const redact = {
630
- ingest: (dto, crop) => {
631
- const d = dto;
632
- return {
633
- geom: d.quadPoints.length > 0 ? {
634
- t: "quads",
635
- quads: quadsFromDTO(d.quadPoints, crop)
636
- } : {
637
- t: "rect",
638
- rect: pdfToContentRect$1(d.rect, crop),
639
- ellipse: false
640
- },
641
- text: {
642
- fontFamily: d.fontFamily,
643
- fontSize: d.fontSize,
644
- fontColor: colorToCss(d.fontColor),
645
- textAlign: d.textAlign
646
- },
647
- ...d.overlayText ? { label: {
648
- text: d.overlayText,
649
- repeat: d.repeat
650
- } } : {}
651
- };
652
- },
653
- geometry: (a, crop) => a.geom.t === "rect" ? { rect: contentToPdfRect$1(a.geom.rect, crop) } : null,
654
- draftExtras: (a, crop) => {
655
- const quads = quadPointsFor(a, crop);
656
- return quads ? {
657
- quadPoints: quads,
658
- rect: pdfBoundsOfQuads(quads)
659
- } : {};
660
- }
661
- };
662
- //#endregion
663
- //#region src/repository/kinds/misc.ts
664
- const rectGeometry = (a, crop) => "rect" in a.geom ? { rect: contentToPdfRect$1(a.geom.rect, crop) } : null;
665
- const iconProjection = (subtype) => ({
666
- ingest: (dto, crop) => {
667
- const d = dto;
668
- return {
669
- geom: {
670
- t: "rect",
671
- rect: pdfToContentRect$1(d.rect, crop),
672
- ellipse: false
673
- },
674
- icon: d.icon
675
- };
676
- },
677
- geometry: rectGeometry,
678
- createable: false
679
- });
680
- const textNote = iconProjection("text");
681
- const fileAttachment = iconProjection("file-attachment");
682
- const stamp = {
683
- ingest: (dto, crop) => {
684
- const d = dto;
685
- return { geom: boxGeomFromDTO(d, d.rotation, d.unrotatedRect, crop, false) };
686
- },
687
- geometry: (a, crop) => boxEmit(a, crop),
688
- createable: false
689
- };
690
- const link = {
691
- ingest: (dto, crop) => {
692
- const d = dto;
693
- return {
694
- geom: {
695
- t: "rect",
696
- rect: pdfToContentRect$1(d.rect, crop),
697
- ellipse: false
698
- },
699
- link: d.target
700
- };
701
- },
702
- geometry: rectGeometry,
703
- prop: { link: (a) => {
704
- const target = writableTarget(a.link);
705
- return target ? { target } : a.link == null ? { target: null } : {};
706
- } },
707
- draftExtras: (a) => ({ target: writableTarget(a.link) })
708
- };
709
- /** One PDF `widget` subtype → per-family CLIENT kinds (radios have no font). */
710
- const WIDGET_KIND_BY_FAMILY = {
711
- text: "widget-text",
712
- combobox: "widget-choice",
713
- listbox: "widget-choice",
714
- pushbutton: "widget-button",
715
- checkbox: "widget-toggle",
716
- radio: "widget-toggle"
717
- };
718
- const widgetKindOf = (family) => WIDGET_KIND_BY_FAMILY[family] ?? "widget-box";
719
- const WIDGET_TEXT_KINDS = /* @__PURE__ */ new Set([
720
- "widget-text",
721
- "widget-choice",
722
- "widget-button"
723
- ]);
724
- function widgetTextFromDTO(dto) {
725
- return {
726
- fontFamily: dto.fontFamily ?? "helvetica",
727
- fontSize: dto.fontSize ?? 0,
728
- fontColor: dto.fontColor ? colorToCss(dto.fontColor) : "#000000",
729
- textAlign: dto.textAlign
730
- };
731
- }
732
- const widget = {
733
- ingest: (dto, crop) => {
734
- const d = dto;
735
- return {
736
- geom: boxGeomFromDTO(d, void 0, void 0, crop, false),
737
- ...WIDGET_TEXT_KINDS.has(widgetKindOf(d.fieldFamily)) ? { text: widgetTextFromDTO(d) } : {}
738
- };
739
- },
740
- geometry: rectGeometry,
741
- createable: false
742
- };
743
- const unsupported = {
744
- ingest: (dto, crop) => ({ geom: {
745
- t: "rect",
746
- rect: pdfToContentRect$1(dto.rect, crop),
747
- ellipse: false
748
- } }),
749
- geometry: () => null,
750
- createable: false
751
- };
752
- //#endregion
753
- //#region src/repository/links.ts
754
- /**
755
- * Attached-link folding + desired-state derivation — RELATIONSHIP logic, not
756
- * projection: a `/Link` child grouped under a linkable parent becomes the
757
- * parent's `link` prop, and the reconciler derives the children it should
758
- * have from the parent's committed geometry.
759
- */
760
- /** Does this kind's table declare the `link` prop (may it carry an attached
761
- * link)? Widgets/caret/redact/file-attachment deliberately don't. */
762
- const takesLink = (subtype) => propsFor(subtype).some((s) => s.key === "link");
763
- /**
764
- * Fold attached link children onto their parents: a `/Link` annotation
765
- * grouped (`/RT /Group`) under a linkable non-link parent is not an object
766
- * in the client model — it becomes the parent's `link` prop value plus the
767
- * `linkRefs` join keys the write side needs. Folded children are REMOVED
768
- * from the returned list, so they never render, hit-test, or select.
769
- * Anything that doesn't match (orphans, links grouped under widgets or
770
- * other links) stays a standalone annotation — nothing is ever hidden.
771
- *
772
- * Multi-segment parents (markup) carry several children with one shared
773
- * target; the first child's target wins and the next write heals any
774
- * foreign disagreement.
775
- */
776
- function foldAttachedLinks(annots) {
777
- const byId = new Map(annots.map((a) => [a.id, a]));
778
- const folded = /* @__PURE__ */ new Set();
779
- const patched = /* @__PURE__ */ new Map();
780
- for (const a of annots) {
781
- if (a.subtype !== "link" || a.data?.subtype !== "link") continue;
782
- if (a.data.replyType !== "group" || !a.data.inReplyTo || !a.ref) continue;
783
- const parentId = refKey(a.data.inReplyTo);
784
- const parent = patched.get(parentId) ?? byId.get(parentId);
785
- if (!parent || parent.subtype === "link" || !takesLink(parent.subtype)) continue;
786
- patched.set(parentId, {
787
- ...parent,
788
- link: parent.link ?? a.data.target,
789
- linkRefs: [...parent.linkRefs ?? [], a.ref]
790
- });
791
- folded.add(a.id);
792
- }
793
- if (!folded.size) return annots;
794
- return annots.filter((a) => !folded.has(a.id)).map((a) => patched.get(a.id) ?? a);
795
- }
796
- /**
797
- * The DESIRED hit rects (content space) of a parent's attached link
798
- * children — derived fresh from the parent's committed geometry, never
799
- * tracked: markup gets one child per quad (per-line hit areas, the v2
800
- * segment behaviour), every other kind one child over its visual bounds.
801
- * The reconciler and the navigation lens both read THIS, so the clickable
802
- * area and the written `/Rect`s can never disagree.
803
- *
804
- * A link's `/Rect` is axis-aligned by spec (no rotation exists for links),
805
- * so a ROTATED parent gets the AABB of its rotated footprint — the
806
- * `selectionQuad` corners (rotation + stroke included), the same envelope
807
- * the selection chrome outlines. Exact rotated hit regions need
808
- * `/QuadPoints` (tier 2).
809
- */
810
- function linkChildRects(a) {
811
- if (a.geom.t === "quads") return a.geom.quads.map(textQuadBounds);
812
- return [unionRect(selectionQuad(a.geom, a.style.strokeWidth, a.style.border))];
813
- }
814
- //#endregion
815
- //#region src/repository/index.ts
816
- /** Every wire subtype declares exactly one projection — a missing kind is a
817
- * COMPILE error, not a silent fall-through. */
818
- const KINDS = {
819
- square,
820
- circle,
821
- line,
822
- polygon,
823
- polyline,
824
- ink,
825
- "free-text": freeText,
826
- highlight,
827
- underline,
828
- squiggly,
829
- strikeout,
830
- caret,
831
- redact,
832
- text: textNote,
833
- "file-attachment": fileAttachment,
834
- stamp,
835
- link,
836
- widget,
837
- unsupported
838
- };
839
- /** Model subtypes are wire subtypes except the widget CLIENT kinds
840
- * (`widget-text`…), which all project through the widget family. */
841
- const projectionOf = (subtype) => subtype.startsWith("widget") ? KINDS.widget : KINDS[subtype] ?? KINDS.unsupported;
842
- const wireSubtypeOf = (a) => a.subtype.startsWith("widget") ? "widget" : a.subtype;
843
- /**
844
- * Engine DTO → content-space Annot. `source` decides how it renders: `'baked'`
845
- * shows the engine's appearance raster (a page load, or a remote edit — trust
846
- * the authored AP); `'vector'` renders live from geom/style (we authored or
847
- * changed it). `apBox` is the raster's content-space box, used while baked.
848
- */
849
- function fromDTO(dto, crop, source = "baked") {
850
- const slice = projectionOf(dto.subtype).ingest(dto, crop);
851
- const strippedRect = !(dto.subtype === "free-text" && dto.intent === "free-text-callout") && "unrotatedRect" in dto && "rotation" in dto && dto.rotation ? dto.unrotatedRect : void 0;
852
- return {
853
- id: refKey(dto.ref),
854
- ref: dto.ref,
855
- pon: dto.pageObjectNumber,
856
- subtype: dto.subtype === "widget" ? widgetKindOf(dto.fieldFamily) : dto.subtype,
857
- flags: dto.flags,
858
- source,
859
- data: dto,
860
- ...dto.inReplyTo ? { irt: refKey(dto.inReplyTo) } : {},
861
- ...dto.replyType === "group" && dto.inReplyTo ? { group: refKey(dto.inReplyTo) } : {},
862
- style: styleFromDTO(dto),
863
- ...slice,
864
- apBox: pdfToContentRect$1(strippedRect ?? dto.rect, crop),
865
- ...strippedRect ? { apRot: geomRotation(slice.geom) } : {}
866
- };
867
- }
868
- /** Lower `keys` through the kind's overrides + the generic table. `null` =
869
- * some key has no lowering — the caller degrades to the full projection. */
870
- function emitProps(a, crop, keys) {
871
- const kind = projectionOf(a.subtype);
872
- const out = {};
873
- for (const key of keys) {
874
- const lower = kind.prop?.[key] ?? GENERIC_PROPS[key];
875
- if (!lower) return null;
876
- Object.assign(out, lower(a, crop));
877
- }
878
- return out;
879
- }
880
- const editableKeys = (subtype) => propsFor(subtype).map((s) => s.key);
881
- /** Content Annot → the FULL engine patch: the kind's geometry group plus every
882
- * prop it declares editable. The reference statement — scoped emission and
883
- * drafts both build on it. */
884
- function toPatch(a, crop) {
885
- const geo = projectionOf(a.subtype).geometry(a, crop);
886
- const props = emitProps(a, crop, editableKeys(a.subtype)) ?? {};
887
- if (!geo && Object.keys(props).length === 0) return null;
888
- return {
889
- subtype: wireSubtypeOf(a),
890
- ...geo,
891
- ...props
892
- };
893
- }
894
- /**
895
- * Content Annot + a {@link PatchScope} → the SPARSE patch for exactly that
896
- * intent (the shell's `patch` effect emitter): the reducer says WHAT changed —
897
- * geometry, or the props keys verbatim — and this lowers only that. Kinds
898
- * without editable geometry (text markup) and unlowerable keys degrade to the
899
- * full patch: verbose, never a dropped write.
900
- */
901
- function toScopedPatch(a, scope, crop) {
902
- const kind = projectionOf(a.subtype);
903
- if (scope.kind === "geometry") {
904
- const geo = kind.geometry(a, crop);
905
- return geo ? {
906
- subtype: wireSubtypeOf(a),
907
- ...geo
908
- } : toPatch(a, crop);
909
- }
910
- const props = emitProps(a, crop, scope.keys);
911
- if (props === null) return toPatch(a, crop);
912
- if (Object.keys(props).length === 0) return null;
913
- return {
914
- subtype: wireSubtypeOf(a),
915
- ...props
916
- };
917
- }
918
- /** Content Annot → engine create draft: the full statement plus the kind's
919
- * create-only extras, with the model's `/F` emitted verbatim, once, for every
920
- * kind (a fresh draw carries DRAWN_FLAGS plus any tool seed). `null` for the
921
- * kinds whose creates travel their own path (stamps, widgets, icon place). */
922
- function toCreateDraft(a, crop) {
923
- const kind = projectionOf(a.subtype);
924
- if (kind.createable === false) return null;
925
- const base = toPatch(a, crop);
926
- if (!base) return null;
927
- const extras = kind.draftExtras?.(a, crop);
928
- if (kind.draftExtras && extras === null) return null;
929
- return {
930
- ...base,
931
- ...extras,
932
- flags: a.flags
933
- };
934
- }
935
- //#endregion
936
- //#region src/text-item.ts
937
- /**
938
- * The free-text presentation projection: the core's geometry-only `textBoxes`
939
- * joined with the DTO-derived font + CSS into render-ready {@link TextItem}s. This
940
- * is the text analogue of the core's `scene()` "paint" for shapes — it lives in
941
- * the plugin (not the portable core) because the font→CSS stack mapping and the
942
- * engine `Color`→CSS seam are web concerns, shared across every web framework.
943
- */
944
- /** Map a free-text `/DA` font to a CSS font-family. A standard PDF font → a web
945
- * stack with the same metrics; anything else is a registered font key → mount it
946
- * as a `@font-face` of that family (see the framework `mountWebFont` helper). */
947
- const STANDARD_FONT_CSS = {
948
- helvetica: "Helvetica, Arial, sans-serif",
949
- "helvetica-bold": "Helvetica, Arial, sans-serif",
950
- courier: "\"Courier New\", Courier, monospace",
951
- "times-roman": "\"Times New Roman\", Times, serif",
952
- symbol: "serif",
953
- "zapf-dingbats": "serif"
954
- };
955
- const cssFontFor = (font) => STANDARD_FONT_CSS[font] ?? `"${font}", sans-serif`;
956
- /** Project the model's free-text boxes into render-ready {@link TextItem}s — the
957
- * core geometry (`textBoxes`) joined with the DTO-derived CSS. Pure; memoized by
958
- * model identity at the call site so selectors get a stable reference. */
959
- function buildTextItems(m, pon, view) {
960
- return textBoxes(m, pon, view).map((tb) => {
961
- const a = m.byId[tb.id];
962
- const t = a?.text ?? initialTextStyle;
963
- return {
964
- id: tb.id,
965
- ref: a?.ref ?? null,
966
- box: tb.box,
967
- contents: a?.data?.contents ?? "",
968
- editing: tb.editing,
969
- ...tb.rot ? { rot: tb.rot } : {},
970
- css: {
971
- fontFamily: cssFontFor(t.fontFamily),
972
- fontSize: t.fontSize,
973
- lineHeight: t.fontSize,
974
- color: t.fontColor,
975
- align: t.textAlign,
976
- padding: 2,
977
- background: a?.style.interiorColor ?? null
978
- }
979
- };
980
- });
981
- }
982
- //#endregion
983
- //#region src/tools.ts
984
- /**
985
- * The creation properties each known authoring kind actually consumes. This is
986
- * deliberately separate from the flat internal patch vocabulary: it gives tool
987
- * configuration precise compile-time and runtime validation while mixed-selection
988
- * edits can keep using `AnnotationPropsPatch`.
989
- */
990
- const TOOL_DEFAULT_KEYS = {
991
- square: [
992
- "color",
993
- "interiorColor",
994
- "opacity",
995
- "strokeWidth",
996
- "border"
997
- ],
998
- circle: [
999
- "color",
1000
- "interiorColor",
1001
- "opacity",
1002
- "strokeWidth",
1003
- "border"
1004
- ],
1005
- line: [
1006
- "color",
1007
- "interiorColor",
1008
- "opacity",
1009
- "strokeWidth",
1010
- "border",
1011
- "lineEndings"
1012
- ],
1013
- polygon: [
1014
- "color",
1015
- "interiorColor",
1016
- "opacity",
1017
- "strokeWidth",
1018
- "border"
1019
- ],
1020
- polyline: [
1021
- "color",
1022
- "interiorColor",
1023
- "opacity",
1024
- "strokeWidth",
1025
- "border",
1026
- "lineEndings"
1027
- ],
1028
- ink: [
1029
- "color",
1030
- "opacity",
1031
- "strokeWidth",
1032
- "blendMode"
1033
- ],
1034
- "free-text": [
1035
- "fontFamily",
1036
- "fontSize",
1037
- "fontColor",
1038
- "textAlign",
1039
- "opacity",
1040
- "interiorColor",
1041
- "color",
1042
- "strokeWidth",
1043
- "border"
1044
- ],
1045
- "free-text-callout": [
1046
- "fontFamily",
1047
- "fontSize",
1048
- "fontColor",
1049
- "textAlign",
1050
- "opacity",
1051
- "interiorColor",
1052
- "color",
1053
- "strokeWidth",
1054
- "border",
1055
- "lineEndings"
1056
- ],
1057
- highlight: [
1058
- "color",
1059
- "opacity",
1060
- "blendMode"
1061
- ],
1062
- underline: [
1063
- "color",
1064
- "opacity",
1065
- "blendMode"
1066
- ],
1067
- strikeout: [
1068
- "color",
1069
- "opacity",
1070
- "blendMode"
1071
- ],
1072
- squiggly: [
1073
- "color",
1074
- "opacity",
1075
- "blendMode"
1076
- ],
1077
- caret: ["color", "opacity"],
1078
- redact: [
1079
- "color",
1080
- "interiorColor",
1081
- "opacity",
1082
- "fontFamily",
1083
- "fontSize",
1084
- "fontColor",
1085
- "textAlign"
1086
- ],
1087
- stamp: [],
1088
- link: ["link"],
1089
- text: [
1090
- "icon",
1091
- "color",
1092
- "opacity"
1093
- ],
1094
- "file-attachment": [
1095
- "icon",
1096
- "color",
1097
- "opacity"
1098
- ],
1099
- "widget-text": [
1100
- "color",
1101
- "interiorColor",
1102
- "strokeWidth",
1103
- "border",
1104
- "fontFamily",
1105
- "fontSize",
1106
- "fontColor",
1107
- "textAlign"
1108
- ],
1109
- "widget-choice": [
1110
- "color",
1111
- "interiorColor",
1112
- "strokeWidth",
1113
- "border",
1114
- "fontFamily",
1115
- "fontSize",
1116
- "fontColor",
1117
- "textAlign"
1118
- ],
1119
- "widget-toggle": [
1120
- "color",
1121
- "interiorColor",
1122
- "strokeWidth",
1123
- "border"
1124
- ]
1125
- };
1126
- const DRAW_TAGS = ["annotation-draw", "annotation-edit"];
1127
- const MARKUP_TAGS = ["text-select", "annotation-edit"];
1128
- /**
1129
- * Whether arming this ANNOTATION tool is touch consent (`Tool.touchDirect`):
1130
- * drag-CREATE tools — shape/ink draw and text-markup select — take
1131
- * single-finger touch wholesale (finger draws/marks, two fingers navigate:
1132
- * the drawing-app convention). Click-to-PLACE tools (stamp, note) do not: a
1133
- * tap places without any claim, and drags keep scrolling. Derived from the
1134
- * gesture tags, so custom registered tools inherit the right behavior. Only
1135
- * annotation-owned tools run through this — the built-in `pointer` tool also
1136
- * enables `text-select`, but it is registered by the hub, not here.
1137
- */
1138
- const isTouchDirect = (enables) => enables.has("annotation-draw") || enables.has("text-select");
1139
- /**
1140
- * The built-in tools — a data mirror of v2's registrations (shapes + lines + ink
1141
- * + free text in the draw channel, text markup + caret behind text selection, and
1142
- * the click-to-place stamp). Order is display-neutral; the toolbar owns layout.
1143
- */
1144
- const DEFAULT_TOOLS = [
1145
- {
1146
- id: "square",
1147
- subtype: "square",
1148
- cursor: "crosshair",
1149
- enables: DRAW_TAGS,
1150
- defaults: { strokeWidth: 6 },
1151
- clickCreate: {
1152
- width: 80,
1153
- height: 60
1154
- }
1155
- },
1156
- {
1157
- id: "circle",
1158
- subtype: "circle",
1159
- cursor: "crosshair",
1160
- enables: DRAW_TAGS,
1161
- defaults: { strokeWidth: 6 },
1162
- clickCreate: {
1163
- width: 80,
1164
- height: 60
1165
- }
1166
- },
1167
- {
1168
- id: "line",
1169
- subtype: "line",
1170
- cursor: "crosshair",
1171
- enables: DRAW_TAGS,
1172
- defaults: { strokeWidth: 6 },
1173
- clickCreate: { length: 80 }
1174
- },
1175
- {
1176
- id: "polygon",
1177
- subtype: "polygon",
1178
- cursor: "crosshair",
1179
- enables: DRAW_TAGS,
1180
- defaults: { strokeWidth: 6 }
1181
- },
1182
- {
1183
- id: "polyline",
1184
- subtype: "polyline",
1185
- cursor: "crosshair",
1186
- enables: DRAW_TAGS,
1187
- defaults: { strokeWidth: 6 }
1188
- },
1189
- {
1190
- id: "ink",
1191
- subtype: "ink",
1192
- cursor: "crosshair",
1193
- enables: DRAW_TAGS,
1194
- defaults: {
1195
- color: "#ef4444",
1196
- strokeWidth: 6,
1197
- blendMode: "normal"
1198
- },
1199
- ink: { groupStrokesMs: 800 }
1200
- },
1201
- {
1202
- id: "ink-highlight",
1203
- extends: "ink",
1204
- intent: "ink-highlight",
1205
- defaults: {
1206
- color: "#ffcd45",
1207
- strokeWidth: 14,
1208
- blendMode: "multiply"
1209
- },
1210
- ink: { straighten: {
1211
- deviationThreshold: .15,
1212
- axisSnapDegrees: 15
1213
- } }
1214
- },
1215
- {
1216
- id: "free-text",
1217
- subtype: "free-text",
1218
- cursor: "crosshair",
1219
- enables: DRAW_TAGS,
1220
- defaults: { fontColor: "#ef4444" },
1221
- upright: true,
1222
- clickCreate: {
1223
- width: 180,
1224
- height: 40,
1225
- anchor: "top-left"
1226
- }
1227
- },
1228
- {
1229
- id: "free-text-callout",
1230
- subtype: "free-text-callout",
1231
- propsKind: "free-text",
1232
- cursor: "crosshair",
1233
- enables: DRAW_TAGS,
1234
- defaults: {
1235
- strokeWidth: 6,
1236
- lineEndings: { end: "open-arrow" }
1237
- },
1238
- upright: true
1239
- },
1240
- {
1241
- id: "highlight",
1242
- subtype: "highlight",
1243
- cursor: "default",
1244
- enables: MARKUP_TAGS,
1245
- defaults: {
1246
- color: "#ffe16a",
1247
- blendMode: "multiply"
1248
- },
1249
- selection: { kind: "markup" }
1250
- },
1251
- {
1252
- id: "redact",
1253
- subtype: "redact",
1254
- cursor: "crosshair",
1255
- enables: [
1256
- "text-select",
1257
- "annotation-draw",
1258
- "annotation-edit"
1259
- ],
1260
- defaults: {
1261
- color: "#e44234",
1262
- interiorColor: "#000000",
1263
- fontColor: "#ffffff",
1264
- opacity: 1
1265
- },
1266
- selection: { kind: "markup" }
1267
- },
1268
- {
1269
- id: "underline",
1270
- subtype: "underline",
1271
- cursor: "default",
1272
- enables: MARKUP_TAGS,
1273
- defaults: { color: "#ef4444" },
1274
- selection: { kind: "markup" }
1275
- },
1276
- {
1277
- id: "strikeout",
1278
- subtype: "strikeout",
1279
- cursor: "default",
1280
- enables: MARKUP_TAGS,
1281
- defaults: { color: "#ef4444" },
1282
- selection: { kind: "markup" }
1283
- },
1284
- {
1285
- id: "squiggly",
1286
- subtype: "squiggly",
1287
- cursor: "default",
1288
- enables: MARKUP_TAGS,
1289
- defaults: { color: "#ef4444" },
1290
- selection: { kind: "markup" }
1291
- },
1292
- {
1293
- id: "insert-text",
1294
- subtype: "caret",
1295
- propsKind: "caret",
1296
- preset: "caret",
1297
- cursor: "default",
1298
- enables: MARKUP_TAGS,
1299
- defaults: { color: "#ef4444" },
1300
- selection: {
1301
- kind: "text-edit",
1302
- operation: "insert"
1303
- }
1304
- },
1305
- {
1306
- id: "replace-text",
1307
- subtype: "strikeout",
1308
- propsKind: "strikeout",
1309
- cursor: "default",
1310
- enables: MARKUP_TAGS,
1311
- defaults: { color: "#ef4444" },
1312
- selection: {
1313
- kind: "text-edit",
1314
- operation: "replace"
1315
- }
1316
- },
1317
- {
1318
- id: "stamp",
1319
- subtype: "stamp",
1320
- cursor: "copy",
1321
- enables: ["annotation-place", "annotation-edit"],
1322
- source: {
1323
- kind: "prompt",
1324
- accept: "image/png,image/jpeg,application/pdf"
1325
- },
1326
- upright: true,
1327
- ghost: { mode: "footprint" }
1328
- },
1329
- {
1330
- id: "link",
1331
- subtype: "link",
1332
- cursor: "crosshair",
1333
- enables: DRAW_TAGS
1334
- },
1335
- {
1336
- id: "note",
1337
- subtype: "text",
1338
- cursor: "crosshair",
1339
- enables: ["annotation-place", "annotation-edit"],
1340
- defaults: {
1341
- icon: "comment",
1342
- color: "#facc15"
1343
- },
1344
- flags: {
1345
- noZoom: true,
1346
- noRotate: true
1347
- },
1348
- upright: true,
1349
- ghost: { mode: "footprint" }
1350
- },
1351
- {
1352
- id: "attachment",
1353
- subtype: "file-attachment",
1354
- cursor: "copy",
1355
- enables: ["annotation-place", "annotation-edit"],
1356
- source: { kind: "prompt" },
1357
- defaults: {
1358
- icon: "paperclip",
1359
- color: "#facc15"
1360
- },
1361
- flags: {
1362
- noZoom: true,
1363
- noRotate: true
1364
- },
1365
- upright: true,
1366
- ghost: { mode: "footprint" }
1367
- }
1368
- ];
1369
- /** Merge two default patches, `b` over `a`, with line endings merged per side. */
1370
- function mergeDefaults(a, b) {
1371
- if (!a) return b;
1372
- if (!b) return a;
1373
- const merged = {
1374
- ...a,
1375
- ...b
1376
- };
1377
- if (a.lineEndings || b.lineEndings) merged.lineEndings = {
1378
- ...a.lineEndings,
1379
- ...b.lineEndings
1380
- };
1381
- return merged;
1382
- }
1383
- /** Overlay a same-id override onto a base definition (configure a built-in). */
1384
- function mergeDef(base, over) {
1385
- return {
1386
- ...base,
1387
- ...over,
1388
- enables: over.enables ?? base.enables,
1389
- meta: base.meta || over.meta ? {
1390
- ...base.meta,
1391
- ...over.meta
1392
- } : void 0,
1393
- defaults: mergeDefaults(base.defaults, over.defaults),
1394
- flags: base.flags || over.flags ? {
1395
- ...base.flags,
1396
- ...over.flags
1397
- } : void 0,
1398
- ink: base.ink || over.ink ? {
1399
- ...base.ink,
1400
- ...over.ink
1401
- } : void 0
1402
- };
1403
- }
1404
- function validateDefaults(tool) {
1405
- if (!tool.defaults) return;
1406
- const allowed = TOOL_DEFAULT_KEYS[tool.subtype];
1407
- if (!allowed) return;
1408
- const keys = new Set(allowed);
1409
- for (const key of Object.keys(tool.defaults)) if (!keys.has(key)) throw new Error(`[annotation] tool '${tool.id}' does not support default '${key}' for '${tool.subtype}'`);
1410
- }
1411
- /**
1412
- * Resolve {@link DEFAULT_TOOLS} + embedder overrides into the ready-to-use table.
1413
- * A same-id override merges over the built-in; a new id adds a tool; `extends`
1414
- * inherits from an already-defined tool. Keyed by id, so lookups are O(1).
1415
- */
1416
- function buildToolRegistry(overrides = []) {
1417
- const defs = /* @__PURE__ */ new Map();
1418
- for (const d of DEFAULT_TOOLS) defs.set(d.id, d);
1419
- for (const o of overrides) {
1420
- const prev = defs.get(o.id);
1421
- defs.set(o.id, prev ? mergeDef(prev, o) : o);
1422
- }
1423
- const out = /* @__PURE__ */ new Map();
1424
- const resolving = /* @__PURE__ */ new Set();
1425
- const resolve = (id) => {
1426
- const cached = out.get(id);
1427
- if (cached) return cached;
1428
- const def = defs.get(id);
1429
- if (!def) throw new Error(`[annotation] tool '${id}' extends an unknown tool`);
1430
- let base;
1431
- if (def.extends && def.extends !== id && !resolving.has(def.extends)) {
1432
- resolving.add(id);
1433
- base = resolve(def.extends);
1434
- resolving.delete(id);
1435
- }
1436
- const subtype = def.subtype ?? base?.subtype ?? def.id;
1437
- const resolved = {
1438
- id: def.id,
1439
- subtype,
1440
- preset: def.preset ?? def.id,
1441
- propsKind: def.propsKind ?? base?.propsKind ?? subtype,
1442
- cursor: def.cursor ?? base?.cursor ?? "crosshair",
1443
- enables: new Set(def.enables ?? (base ? [...base.enables] : [])),
1444
- defaults: mergeDefaults(base?.defaults, def.defaults),
1445
- flags: base?.flags || def.flags ? {
1446
- ...base?.flags,
1447
- ...def.flags
1448
- } : void 0,
1449
- source: def.source ?? base?.source,
1450
- selection: def.selection ?? base?.selection,
1451
- intent: def.intent ?? base?.intent,
1452
- ink: base?.ink || def.ink ? {
1453
- ...base?.ink,
1454
- ...def.ink
1455
- } : void 0,
1456
- upright: def.upright ?? base?.upright ?? false,
1457
- clickCreate: def.clickCreate ?? base?.clickCreate ?? false,
1458
- ghost: def.ghost ?? base?.ghost ?? false,
1459
- meta: base?.meta || def.meta ? {
1460
- ...base?.meta,
1461
- ...def.meta
1462
- } : void 0
1463
- };
1464
- validateDefaults(resolved);
1465
- out.set(id, resolved);
1466
- return resolved;
1467
- };
1468
- for (const id of defs.keys()) resolve(id);
1469
- return out;
1470
- }
1471
- //#endregion
1472
- //#region src/placement.ts
1473
- /**
1474
- * Per-kind CODE for the click-to-place ICON kinds (note / file attachment)
1475
- * — the `props.ts`/`repository.ts` pattern: all tool CONFIG stays in the
1476
- * tool table; this module only interprets it. The stamp keeps its own
1477
- * sizing/sniffing path in the capability; everything funnels through the
1478
- * one `placeAt` entry there.
1479
- */
1480
- /**
1481
- * Icon kinds place at the generator's fixed box: the engine forces the
1482
- * `/Rect` to 20×20 from its bottom-left corner (the spec's note-icon rule),
1483
- * so the footprint ghost and the placement use exactly this size.
1484
- */
1485
- const ICON_PLACE_SIZE = {
1486
- width: 20,
1487
- height: 20
1488
- };
1489
- const isIconPlaceKind = (subtype) => subtype === "text" || subtype === "file-attachment";
1490
- /**
1491
- * Build the engine create draft for a placed icon annotation. `geom` is the
1492
- * repository's `boxGeomFields` emit (the `/Rect` + upright rotation pair);
1493
- * `defaults` is the tool's resolved flat props bag (`defaultsFor`) — the
1494
- * colour seam is crossed here via the repository's `cssToColor`, and the
1495
- * icon falls back to the kind's own default when the bag carries none.
1496
- */
1497
- function iconPlacementDraft(subtype, geom, defaults, flags, file) {
1498
- const shared = {
1499
- ...geom,
1500
- color: cssToColor(defaults.color),
1501
- opacity: defaults.opacity,
1502
- flags: {
1503
- print: true,
1504
- ...flags
1505
- }
1506
- };
1507
- if (subtype === "text") return {
1508
- subtype: "text",
1509
- icon: defaults.icon ?? "comment",
1510
- ...shared
1511
- };
1512
- if (!file) throw new Error("[annotation] a file-attachment placement requires a file payload");
1513
- return {
1514
- subtype: "file-attachment",
1515
- icon: defaults.icon ?? "paperclip",
1516
- file,
1517
- ...shared
1518
- };
1519
- }
1520
- //#endregion
1521
- //#region src/capability.ts
1522
- /** Fold `zoom`/`rotation` host args into the core's ViewEnv (or none).
1523
- * `zoom` is the page's RELATIVE zoom (`transform.zoom`) — never the
1524
- * px-per-point `scale` (that one only converts CSS-px chrome settings). */
1525
- const viewEnv = (zoom, rotation) => zoom != null || rotation != null ? {
1526
- zoom: zoom ?? 1,
1527
- rotation: rotation ?? 0
1528
- } : void 0;
1529
- /** Broad annotate-write capability (PDF bit 6). The engine independently
1530
- * enforces this AND the per-owner collab rules; `canEdit`/`canDelete` are the
1531
- * UI mirror of the coarse gate. */
1532
- const ANNOTATE_MODIFY = "doc.annotate.modify";
1533
- const TEXT_COMMIT_DEBOUNCE_MS = 250;
1534
- /**
1535
- * The annotation shell. The pure `update` runs HERE (so it can emit effects);
1536
- * the resulting model is dispatched to the store, and each effect is performed
1537
- * against the engine repository — optimistic create → reconcile to the durable
1538
- * ref, patch/delete fire-and-forget.
1539
- */
1540
- function createAnnotationCapability(ctx, config = {}) {
1541
- const loaded = /* @__PURE__ */ new Set();
1542
- const behaviors = [];
1543
- /** Per-annotation debounce timer for the engine `contents` write while typing. */
1544
- const textTimers = /* @__PURE__ */ new Map();
1545
- const configTools = config.tools ?? [];
1546
- const registry = buildToolRegistry(configTools);
1547
- /** The installed file-picker port (a DOM file dialog, wired by the framework
1548
- * adapter), or null — every click-then-pick tool resolves through this ONE
1549
- * slot. See {@link FilePickerProvider}. */
1550
- let filePickerProvider = null;
1551
- const model = () => ctx.getState().model;
1552
- const chromeSettings = () => ctx.getState().chrome;
1553
- /**
1554
- * Ids on a page whose Behavior is currently ENGAGED (form widgets under a
1555
- * fill tool): they render their own DOM, so hit-test/marquee must not see
1556
- * them. Resolved per event — engagement follows the active tool live.
1557
- */
1558
- const inertIdsAt = (pon) => {
1559
- if (!behaviors.length) return void 0;
1560
- const m = model();
1561
- let out;
1562
- for (const id of m.order) {
1563
- const a = m.byId[id];
1564
- if (!a || a.pon !== pon) continue;
1565
- if (behaviors.some((b) => b.matches({
1566
- subtype: a.subtype,
1567
- ref: a.ref
1568
- }) && b.engaged())) (out ?? (out = /* @__PURE__ */ new Set())).add(id);
1569
- }
1570
- return out;
1571
- };
1572
- /** The CSS-px chrome settings converted to CONTENT units by the page's view
1573
- * scale (px per content unit) — screen-constant grab zones + stalk at every
1574
- * zoom. No scale → the values are read as content units (headless callers).
1575
- * `boost` widens the GRAB tolerances only (never the drawn chrome or the
1576
- * knob's position) — the touch path passes {@link TOUCH_GRAB_BOOST} so
1577
- * handles present finger-sized targets. */
1578
- const chromeGeomAt = (scale, boost = 1) => {
1579
- const cs = chromeSettings();
1580
- const s = scale || 1;
1581
- return {
1582
- handleTol: cs.handles.hitSize / 2 / s * boost,
1583
- knobTol: cs.knob.hitSize / 2 / s * boost,
1584
- knobOffset: cs.knob.offset / s
1585
- };
1586
- };
1587
- /** Finger-sized grab zones: 2× the mouse tolerances lands a ~24px handle hit
1588
- * box in Apple's ~44pt-target territory without moving any visuals. */
1589
- const TOUCH_GRAB_BOOST = 2;
1590
- const grabBoost = (touch) => touch ? TOUCH_GRAB_BOOST : 1;
1591
- const itemsCache = /* @__PURE__ */ new Map();
1592
- const chromeCache = /* @__PURE__ */ new Map();
1593
- const memoItems = (pon, view) => {
1594
- const m = model();
1595
- const g = ctx.getState().toolGhost;
1596
- const c = itemsCache.get(pon);
1597
- if (c && c.model === m && c.ghost === g && c.zoom === view?.zoom && c.rotation === view?.rotation) return c.v;
1598
- const v = pageItems(m, pon, view);
1599
- if (g && g.pon === pon && g.kind === "vector") {
1600
- const tool = registry.get(g.toolId);
1601
- const style = styleFromProps(defaultsFor(m, tool?.preset ?? g.toolId));
1602
- v.push({
1603
- id: "tool-ghost",
1604
- ref: null,
1605
- subtype: tool?.subtype ?? "square",
1606
- geom: g.geom,
1607
- box: g.box,
1608
- style,
1609
- source: "ghost",
1610
- selected: false
1611
- });
1612
- }
1613
- itemsCache.set(pon, {
1614
- model: m,
1615
- ghost: g,
1616
- zoom: view?.zoom,
1617
- rotation: view?.rotation,
1618
- v
1619
- });
1620
- return v;
1621
- };
1622
- const memoChrome = (pon, scale, rotation, zoom) => {
1623
- const m = model();
1624
- const cs = chromeSettings();
1625
- const c = chromeCache.get(pon);
1626
- if (c && c.model === m && c.cs === cs && c.scale === scale && c.rotation === rotation && c.zoom === zoom) return c.v;
1627
- let v = chrome(m, pon, pageBoxOf(pon), chromeGeomAt(scale).knobOffset, viewEnv(zoom, rotation));
1628
- if (!cs.guides.enabled) v = v.filter((n) => n.kind !== "rotate-guides");
1629
- chromeCache.set(pon, {
1630
- model: m,
1631
- cs,
1632
- scale,
1633
- rotation,
1634
- zoom,
1635
- v
1636
- });
1637
- return v;
1638
- };
1639
- let anchorCache = null;
1640
- const memoAnchor = (scale, rotation, zoom) => {
1641
- const m = model();
1642
- const cs = chromeSettings();
1643
- if (anchorCache && anchorCache.model === m && anchorCache.cs === cs && anchorCache.scale === scale && anchorCache.rotation === rotation && anchorCache.zoom === zoom) return anchorCache.v;
1644
- const v = selectionAnchor(m, pageBoxOf, () => chromeGeomAt(scale).knobOffset, () => viewEnv(zoom, rotation));
1645
- anchorCache = {
1646
- model: m,
1647
- cs,
1648
- scale,
1649
- rotation,
1650
- zoom,
1651
- v
1652
- };
1653
- return v;
1654
- };
1655
- let draftAnchorCache = null;
1656
- const memoDraftAnchor = () => {
1657
- const m = model();
1658
- if (draftAnchorCache && draftAnchorCache.model === m) return draftAnchorCache.v;
1659
- const v = creationDraftAnchor(m);
1660
- draftAnchorCache = {
1661
- model: m,
1662
- v
1663
- };
1664
- return v;
1665
- };
1666
- let selPropsCache = null;
1667
- const memoSelectionProps = () => {
1668
- const m = model();
1669
- if (selPropsCache && selPropsCache.model === m) return selPropsCache.v;
1670
- const members = m.selected.map((id) => m.byId[id]).filter((a) => !!a);
1671
- const specs = sharedProps(members.map((a) => a.subtype));
1672
- const values = {};
1673
- const mixed = [];
1674
- for (const spec of specs) {
1675
- const first = readProp(members[0], spec.key);
1676
- values[spec.key] = first;
1677
- const firstJson = JSON.stringify(first);
1678
- if (members.some((a) => JSON.stringify(readProp(a, spec.key)) !== firstJson)) mixed.push(spec.key);
1679
- }
1680
- const v = {
1681
- specs,
1682
- values,
1683
- mixed
1684
- };
1685
- selPropsCache = {
1686
- model: m,
1687
- v
1688
- };
1689
- return v;
1690
- };
1691
- const linkItemsCache = /* @__PURE__ */ new Map();
1692
- const memoLinkItems = (pon) => {
1693
- const m = model();
1694
- const c = linkItemsCache.get(pon);
1695
- if (c && c.model === m) return c.v;
1696
- const v = [];
1697
- for (const id of m.order) {
1698
- const a = m.byId[id];
1699
- if (!a || a.pon !== pon || a.link == null) continue;
1700
- if (!viewable(a.flags, false)) continue;
1701
- if (a.subtype === "link") {
1702
- if (a.geom.t === "rect") v.push({
1703
- id,
1704
- rect: a.geom.rect,
1705
- target: a.link
1706
- });
1707
- } else linkChildRects(a).forEach((rect, i) => v.push({
1708
- id: `${id}#${i}`,
1709
- rect,
1710
- target: a.link
1711
- }));
1712
- }
1713
- linkItemsCache.set(pon, {
1714
- model: m,
1715
- v
1716
- });
1717
- return v;
1718
- };
1719
- const textsCache = /* @__PURE__ */ new Map();
1720
- const memoTexts = (pon, view) => {
1721
- const m = model();
1722
- const c = textsCache.get(pon);
1723
- if (c && c.model === m && c.zoom === view?.zoom && c.rotation === view?.rotation) return c.v;
1724
- const v = buildTextItems(m, pon, view);
1725
- textsCache.set(pon, {
1726
- model: m,
1727
- zoom: view?.zoom,
1728
- rotation: view?.rotation,
1729
- v
1730
- });
1731
- return v;
1732
- };
1733
- let selFlagsCache = null;
1734
- const memoSelectionFlags = () => {
1735
- const m = model();
1736
- if (selFlagsCache && selFlagsCache.model === m) return selFlagsCache.v;
1737
- const members = m.selected.map((id) => m.byId[id]).filter((a) => !!a);
1738
- let v = null;
1739
- if (members.length) {
1740
- v = {};
1741
- for (const key of FLAG_KEYS) {
1742
- const first = members[0].flags[key];
1743
- v[key] = members.every((a) => a.flags[key] === first) ? first : null;
1744
- }
1745
- }
1746
- selFlagsCache = {
1747
- model: m,
1748
- v
1749
- };
1750
- return v;
1751
- };
1752
- const cropOf = (pon) => ctx.document()?.pages.find((p) => p.pageObjectNumber === pon)?.boxes.crop ?? null;
1753
- /** The page's box in content space (origin at the crop top-left) — the box
1754
- * pointer gestures clamp to, so annotations stay page-bound. */
1755
- const pageBoxOf = (pon) => {
1756
- const crop = cropOf(pon);
1757
- return crop ? {
1758
- x: 0,
1759
- y: 0,
1760
- width: crop.right - crop.left,
1761
- height: crop.top - crop.bottom
1762
- } : void 0;
1763
- };
1764
- /**
1765
- * The armed stamp-tool payload: the bytes the next click places, plus the
1766
- * PDF-point placement size (derived from the sniffed intrinsic aspect).
1767
- * Transient tool state — deliberately NOT in the model: it is never
1768
- * rendered, never synced, and dies with the tool.
1769
- */
1770
- let armedStamp = null;
1771
- /**
1772
- * The desired stamp size (PDF points) from sniffed bytes: the image's
1773
- * INTRINSIC pixel dimensions taken 1:1 as points (the v2 rule — keep the
1774
- * artwork's own size, then clamp to the page at placement). A `targetWidth`
1775
- * override scales to that width, aspect preserved. Vector (PDF) stamps carry
1776
- * no sniffable dimensions — a caller-supplied `intrinsic` override (a stamp
1777
- * library knows its page size) keeps the true aspect; without one they fall
1778
- * back to a square target.
1779
- */
1780
- const desiredStampSize = (meta, targetWidth, intrinsicOverride) => {
1781
- const intrinsic = intrinsicOverride && intrinsicOverride.width > 0 && intrinsicOverride.height > 0 ? intrinsicOverride : "width" in meta && meta.width > 0 ? {
1782
- width: meta.width,
1783
- height: meta.height
1784
- } : {
1785
- width: targetWidth ?? 150,
1786
- height: targetWidth ?? 150
1787
- };
1788
- if (targetWidth === void 0) return intrinsic;
1789
- return {
1790
- width: targetWidth,
1791
- height: targetWidth * (intrinsic.height / intrinsic.width)
1792
- };
1793
- };
1794
- const armStamp = async (input) => {
1795
- const resolved = await resolveBinarySource(input.source);
1796
- const meta = sniffBinaryMetadata(resolved.bytes);
1797
- if (!meta) throw new Error("[annotation] stamp source must be PNG, JPEG, or single-page PDF bytes");
1798
- let preview = null;
1799
- if (input.preview) {
1800
- const p = await resolveBinarySource(input.preview);
1801
- preview = {
1802
- bytes: new Uint8Array(p.bytes),
1803
- mimeType: p.mimeType
1804
- };
1805
- } else if (meta.mimeType !== "application/pdf") preview = {
1806
- bytes: new Uint8Array(resolved.bytes),
1807
- mimeType: meta.mimeType
1808
- };
1809
- armedStamp = {
1810
- source: input.source,
1811
- ...desiredStampSize(meta, input.targetWidth, input.intrinsicSize),
1812
- preview
1813
- };
1814
- ctx.dispatch({ type: "STAMP_ARM_CHANGED" });
1815
- ctx.tryGet(InteractionToken)?.activateTool("stamp");
1816
- };
1817
- const disarmStamp = () => {
1818
- if (!armedStamp) return;
1819
- armedStamp = null;
1820
- ctx.dispatch({ type: "STAMP_ARM_CHANGED" });
1821
- };
1822
- /** Move the hover FOOTPRINT ghost to a content point. The box/geometry is
1823
- * computed by the SAME rules the click's placement uses ({@link createStampAt}
1824
- * fit + clamp for an armed stamp; the click-create anchor + page clamp for a
1825
- * draw tool), so the ghost is the placement, not an approximation of it. */
1826
- const ghostHoverAt = (toolId, pon, point, displayRotation) => {
1827
- const tool = registry.get(toolId);
1828
- const crop = cropOf(pon);
1829
- if (!tool || tool.ghost === false || !crop) {
1830
- clearGhost();
1831
- return;
1832
- }
1833
- const page = {
1834
- width: crop.right - crop.left,
1835
- height: crop.top - crop.bottom
1836
- };
1837
- if (armedStamp) {
1838
- const rot = uprightRotFor(displayRotation);
1839
- const box = fitStampBox(point, {
1840
- width: armedStamp.width,
1841
- height: armedStamp.height
1842
- }, page, rot);
1843
- ctx.dispatch({
1844
- type: "SET_TOOL_GHOST",
1845
- ghost: {
1846
- pon,
1847
- box,
1848
- rot,
1849
- kind: "image"
1850
- }
1851
- });
1852
- return;
1853
- }
1854
- if (isIconPlaceKind(tool.subtype)) {
1855
- const box = fitStampBox(point, ICON_PLACE_SIZE, page, uprightRotFor(displayRotation));
1856
- dispatchVectorGhost(pon, toolId, {
1857
- t: "rect",
1858
- rect: box,
1859
- ellipse: false
1860
- });
1861
- return;
1862
- }
1863
- if (!tool.clickCreate) {
1864
- clearGhost();
1865
- return;
1866
- }
1867
- const placement = resolveClickPlacement(point, tool.clickCreate, {
1868
- pageBox: {
1869
- x: 0,
1870
- y: 0,
1871
- width: page.width,
1872
- height: page.height
1873
- },
1874
- upright: tool.upright,
1875
- displayRotation
1876
- });
1877
- const geom = clickCreateGeom(tool.subtype, placement, defaultsFor(model(), tool.preset));
1878
- if (!geom) {
1879
- clearGhost();
1880
- return;
1881
- }
1882
- dispatchVectorGhost(pon, toolId, geom);
1883
- };
1884
- /** Paint a vector ghost item for a tool's would-be geometry — shared by the
1885
- * hover footprint and the externally-driven placement preview. */
1886
- const dispatchVectorGhost = (pon, toolId, geom) => {
1887
- const tool = registry.get(toolId);
1888
- const style = styleFromProps(defaultsFor(model(), tool?.preset ?? toolId));
1889
- ctx.dispatch({
1890
- type: "SET_TOOL_GHOST",
1891
- ghost: {
1892
- pon,
1893
- box: geomVisualBounds(geom, style.strokeWidth, style.border),
1894
- rot: 0,
1895
- kind: "vector",
1896
- toolId,
1897
- geom
1898
- }
1899
- });
1900
- };
1901
- /**
1902
- * Drive the placement preview during an EXTERNALLY-owned creation gesture
1903
- * (the form plugin's drag-to-place): paint the box the commit would use,
1904
- * styled from the TOOL's defaults, through the same ghost pipeline as every
1905
- * footprint. The box is clamped to the page (a drag may overshoot).
1906
- */
1907
- const setPlacementPreview = (toolId, pon, box) => {
1908
- const crop = cropOf(pon);
1909
- if (!crop) return;
1910
- const page = {
1911
- width: crop.right - crop.left,
1912
- height: crop.top - crop.bottom
1913
- };
1914
- const x = Math.max(0, Math.min(box.x, page.width));
1915
- const y = Math.max(0, Math.min(box.y, page.height));
1916
- const rect = {
1917
- x,
1918
- y,
1919
- width: Math.max(0, Math.min(box.x + box.width, page.width) - x),
1920
- height: Math.max(0, Math.min(box.y + box.height, page.height) - y)
1921
- };
1922
- dispatchVectorGhost(pon, toolId, {
1923
- t: "rect",
1924
- rect,
1925
- ellipse: false
1926
- });
1927
- };
1928
- const clearGhost = () => {
1929
- if (ctx.getState().toolGhost) ctx.dispatch({
1930
- type: "SET_TOOL_GHOST",
1931
- ghost: null
1932
- });
1933
- };
1934
- /** Place a stamp of `desired` PDF-point size centred on a content point — the
1935
- * one engine-write both the armed and click-to-place paths funnel through.
1936
- * The size is fit to the page and clamped fully onto it (v2 rubber-stamp
1937
- * rule: never larger than the page, aspect preserved), and never spills off
1938
- * the edge. `rotCW` (the tool's upright counter-rotation, CW content degrees)
1939
- * emits the repository's box rotation fields — the engine bakes the tilted
1940
- * /AP exactly as an interactively rotated stamp round-trips, and the fit uses
1941
- * the ROTATED footprint. Returns false when the page/document isn't ready. */
1942
- const createStampAt = (pon, point, source, desired, rotCW = 0) => {
1943
- const doc = ctx.doc;
1944
- const crop = cropOf(pon);
1945
- if (!doc || !crop) return false;
1946
- const box = fitStampBox(point, desired, {
1947
- width: crop.right - crop.left,
1948
- height: crop.top - crop.bottom
1949
- }, rotCW);
1950
- doc.page(pon).annotations.create({
1951
- subtype: "stamp",
1952
- ...boxGeomFields(box, rotCW, crop),
1953
- source,
1954
- fit: "contain"
1955
- }).then((res) => {
1956
- syncDTO(res.created, "baked");
1957
- apply({
1958
- t: "select",
1959
- ids: [refKey(res.created.ref)]
1960
- });
1961
- }, (err) => console.error("[annotation] stamp placement failed:", err));
1962
- return true;
1963
- };
1964
- /** The active tool's upright counter-rotation for a click at `displayRotation`
1965
- * (0 when the tool doesn't ask for upright, or the display isn't rotated). */
1966
- const uprightRotFor = (displayRotation) => {
1967
- if (!displayRotation) return 0;
1968
- const ix = ctx.tryGet(InteractionToken);
1969
- return (ix ? registry.get(ix.activeToolId()) : void 0)?.upright ? uprightRotation(displayRotation) : 0;
1970
- };
1971
- const placeArmedStamp = (pon, point, displayRotation) => {
1972
- const armed = armedStamp;
1973
- if (!armed) return false;
1974
- return createStampAt(pon, point, armed.source, {
1975
- width: armed.width,
1976
- height: armed.height
1977
- }, uprightRotFor(displayRotation));
1978
- };
1979
- /** Sniff a stamp source (rejecting non-image bytes) and place it at its
1980
- * intrinsic size (fit to the page in {@link createStampAt}); `targetWidth`
1981
- * overrides the width, aspect preserved. */
1982
- const placeStampSource = async (pon, point, source, rotCW, targetWidth) => {
1983
- const meta = sniffBinaryMetadata((await resolveBinarySource(source)).bytes);
1984
- if (!meta) {
1985
- console.error("[annotation] stamp source must be PNG, JPEG, or single-page PDF bytes");
1986
- return;
1987
- }
1988
- createStampAt(pon, point, source, desiredStampSize(meta, targetWidth), rotCW);
1989
- };
1990
- /**
1991
- * Click-to-place: resolve the ACTIVE tool's source spec. Fixed `bytes` place
1992
- * immediately; a `'prompt'` source asks the installed provider, then places on
1993
- * resolve — dropping the placement if it was cancelled, or if the tool or
1994
- * document changed while the picker was open (the intent expired).
1995
- */
1996
- const requestStampAt = (pon, point, displayRotation) => {
1997
- const ix = ctx.tryGet(InteractionToken);
1998
- const tool = ix ? registry.get(ix.activeToolId()) : void 0;
1999
- const spec = tool?.source;
2000
- if (!spec) return false;
2001
- const rotCW = tool.upright && displayRotation ? uprightRotation(displayRotation) : 0;
2002
- if (spec.kind === "bytes") {
2003
- placeStampSource(pon, point, spec.source, rotCW);
2004
- return true;
2005
- }
2006
- return promptFileAt(tool, pon, point, (picked) => void placeStampSource(pon, point, picked.data, rotCW));
2007
- };
2008
- /**
2009
- * Run the installed file-picker port for a click-then-pick tool, with the
2010
- * shared expiry rule: the placement is dropped if the picker cancels, or if
2011
- * the document or the active tool changed while it was open (the intent
2012
- * expired with the click). No provider installed → decline the click (let a
2013
- * lower-priority handler act) rather than swallow it.
2014
- */
2015
- const promptFileAt = (tool, pon, point, place) => {
2016
- const provider = filePickerProvider;
2017
- if (!provider) return false;
2018
- const spec = tool.source;
2019
- const req = {
2020
- toolId: tool.id,
2021
- subtype: tool.subtype,
2022
- accept: spec?.kind === "prompt" ? spec.accept : void 0,
2023
- pon,
2024
- point
2025
- };
2026
- const docAtClick = ctx.doc;
2027
- provider(req).then((picked) => {
2028
- if (!picked) return;
2029
- if (ctx.doc !== docAtClick) return;
2030
- if (ctx.tryGet(InteractionToken)?.activeToolId() !== tool.id) return;
2031
- place(picked);
2032
- }, (err) => console.error("[annotation] file-picker provider failed:", err));
2033
- return true;
2034
- };
2035
- /** Place a fixed-size ICON annotation (note / file attachment) centred on a
2036
- * content point — the icon-kind sibling of {@link createStampAt}. The
2037
- * engine bakes the 20×20 /AP from /C + /Name; a successful create selects
2038
- * the new annotation (the anchor for its menu / future comment popup). */
2039
- const createIconAt = (tool, pon, point, rotCW, file) => {
2040
- const doc = ctx.doc;
2041
- const crop = cropOf(pon);
2042
- if (!doc || !crop || !isIconPlaceKind(tool.subtype)) return false;
2043
- const box = fitStampBox(point, ICON_PLACE_SIZE, {
2044
- width: crop.right - crop.left,
2045
- height: crop.top - crop.bottom
2046
- }, rotCW);
2047
- const draft = iconPlacementDraft(tool.subtype, boxGeomFields(box, rotCW, crop), defaultsFor(model(), tool.preset), tool.flags, file);
2048
- doc.page(pon).annotations.create(draft).then((res) => {
2049
- syncDTO(res.created, "baked");
2050
- apply({
2051
- t: "select",
2052
- ids: [refKey(res.created.ref)]
2053
- });
2054
- }, (err) => console.error("[annotation] icon placement failed:", err));
2055
- return true;
2056
- };
2057
- /**
2058
- * The ONE click-to-place entry the place handler forwards every down to —
2059
- * armed payload first, then the active tool's kind decides:
2060
- * - stamp → the source spec (fixed bytes, or the file-picker port)
2061
- * - note (text) → place immediately (no payload)
2062
- * - attachment → spot first, file second: the file-picker port opens
2063
- * inside the click gesture, and placement lands when it
2064
- * resolves (dropped on cancel, or if the tool/document
2065
- * changed while the picker was open).
2066
- * Returns whether the click was consumed.
2067
- */
2068
- const placeAt = (pon, point, displayRotation) => {
2069
- if (placeArmedStamp(pon, point, displayRotation)) return true;
2070
- const ix = ctx.tryGet(InteractionToken);
2071
- const tool = ix ? registry.get(ix.activeToolId()) : void 0;
2072
- if (!tool) return false;
2073
- if (tool.subtype === "stamp") return requestStampAt(pon, point, displayRotation);
2074
- if (!isIconPlaceKind(tool.subtype)) return false;
2075
- const rotCW = tool.upright && displayRotation ? uprightRotation(displayRotation) : 0;
2076
- if (tool.subtype === "text") return createIconAt(tool, pon, point, rotCW, null);
2077
- return promptFileAt(tool, pon, point, (picked) => createIconAt(tool, pon, point, rotCW, picked));
2078
- };
2079
- /** The page a ref lives on: from the loaded model first (covers obj/nm refs
2080
- * that don't carry a pon), else the ref itself (index refs do). */
2081
- const ponForRef = (ref) => model().byId[refKey(ref)]?.pon ?? (ref.kind === "index" ? ref.pageObjectNumber : null);
2082
- /**
2083
- * Re-sync one annotation into the model from the authoritative engine DTO,
2084
- * with the render `source` the caller decides: `'vector'` when WE authored or
2085
- * changed the appearance (create / restyle / resize), `'baked'` when the AP is
2086
- * still authoritative (a move, which preserves it, or a remote edit).
2087
- * `bumpAp` marks the upsert as confirming an engine /AP re-bake with new
2088
- * content, so the annotation's `apVersion` — and with it the page's
2089
- * appearance epoch — advances and the shell fetches the fresh raster.
2090
- */
2091
- const syncDTO = (dto, source, bumpAp = false) => {
2092
- const crop = cropOf(dto.pageObjectNumber);
2093
- if (crop) apply({
2094
- t: "upsert",
2095
- annots: [fromDTO(dto, crop, source)],
2096
- bumpAp
2097
- });
2098
- };
2099
- /** The one engine-update path, shared by `update` and `updateSelection`. A
2100
- * programmatic patch changes the appearance → render live (vector). */
2101
- const updateOne = async (ref, patch) => {
2102
- const doc = ctx.doc;
2103
- if (!doc) throw new Error("[annotation] no document bound");
2104
- const pon = ponForRef(ref);
2105
- if (pon == null) throw new Error("[annotation] cannot resolve page for ref");
2106
- const res = await doc.page(pon).annotations.update(ref, patch);
2107
- syncDTO(res.updated, "vector");
2108
- };
2109
- function apply(msg) {
2110
- const [next, effects] = update(model(), msg);
2111
- ctx.dispatch({
2112
- type: "SET_MODEL",
2113
- model: next
2114
- });
2115
- for (const fx of effects) perform(fx, next);
2116
- }
2117
- /**
2118
- * Per-parent serialization of attached-link reconciles: rapid edits chain
2119
- * instead of interleaving (two overlapping runs could double-create
2120
- * children). Each run reads the CURRENT model at execution time, so a
2121
- * chained run converges on the latest desired state.
2122
- */
2123
- const linkSyncChains = /* @__PURE__ */ new Map();
2124
- const scheduleLinkSync = (id) => {
2125
- const next = (linkSyncChains.get(id) ?? Promise.resolve()).then(() => reconcileLinkChildren(id));
2126
- linkSyncChains.set(id, next);
2127
- next.finally(() => {
2128
- if (linkSyncChains.get(id) === next) linkSyncChains.delete(id);
2129
- });
2130
- };
2131
- /**
2132
- * THE one place attached link children are created, retargeted, re-rected,
2133
- * or deleted (the delete-with-parent expansion in the core is the one other
2134
- * consumer of `linkRefs`). Declarative: desired state is derived fresh from
2135
- * the parent's `link` value + committed geometry (`linkChildRects`), then
2136
- * diffed against the join keys the last fold reported. Idempotent — foreign
2137
- * inconsistencies heal on the next local edit.
2138
- */
2139
- const reconcileLinkChildren = async (id) => {
2140
- const doc = ctx.doc;
2141
- const a = model().byId[id];
2142
- if (!doc || !a || !a.ref || a.subtype === "link") return;
2143
- const crop = cropOf(a.pon);
2144
- if (!crop) return;
2145
- const page = doc.page(a.pon);
2146
- const target = writableTarget(a.link);
2147
- const rects = a.link == null ? [] : linkChildRects(a).map((r) => contentToPdfRect(r, crop));
2148
- const current = a.linkRefs ?? [];
2149
- const nextRefs = [];
2150
- try {
2151
- const paired = Math.min(current.length, rects.length);
2152
- for (let i = 0; i < paired; i++) {
2153
- const res = await page.annotations.update(current[i], {
2154
- subtype: "link",
2155
- rect: rects[i],
2156
- ...target ? { target } : {}
2157
- });
2158
- nextRefs.push(res.updated.ref);
2159
- }
2160
- for (let i = current.length; i < rects.length; i++) {
2161
- const res = await page.annotations.create({
2162
- subtype: "link",
2163
- rect: rects[i],
2164
- target,
2165
- inReplyTo: a.ref,
2166
- replyType: "group"
2167
- });
2168
- nextRefs.push(res.created.ref);
2169
- }
2170
- for (let i = rects.length; i < current.length; i++) await page.annotations.delete(current[i]);
2171
- } catch (err) {
2172
- console.error("[annotation] attached-link sync failed:", err);
2173
- }
2174
- const cur = model().byId[id];
2175
- if (cur) apply({
2176
- t: "upsert",
2177
- annots: [{
2178
- ...cur,
2179
- linkRefs: nextRefs
2180
- }]
2181
- });
2182
- };
2183
- /** A relationship-only engine patch (sets/clears `/IRT` + `/RT`) — geometry and
2184
- * style are left untouched, so grouping never re-bakes an appearance. */
2185
- const relationshipPatch = (subtype, rel) => ({
2186
- subtype,
2187
- ...rel
2188
- });
2189
- /** Write a relationship change to one committed annotation and re-sync it from
2190
- * the authoritative DTO (preserving its render source — relationships don't
2191
- * change the appearance). */
2192
- const writeRelationship = async (a, rel) => {
2193
- const doc = ctx.doc;
2194
- if (!doc || !a.ref || !a.data) return;
2195
- const res = await doc.page(a.pon).annotations.update(a.ref, relationshipPatch(a.data.subtype, rel));
2196
- syncDTO(res.updated, a.source);
2197
- };
2198
- /** Committed, data-backed annotations in the current selection. */
2199
- const selectedCommitted = () => {
2200
- const m = model();
2201
- return m.selected.map((id) => m.byId[id]).filter((a) => !!a && !!a.ref && !!a.data);
2202
- };
2203
- function perform(fx, m) {
2204
- const doc = ctx.doc;
2205
- if (!doc) return;
2206
- if (fx.fx === "createGroup") {
2207
- const ids = [fx.primary, ...fx.members];
2208
- const annots = ids.map((id) => m.byId[id]);
2209
- const primary = annots[0];
2210
- if (!primary || annots.some((a) => !a || a.pon !== primary.pon)) {
2211
- apply({
2212
- t: "remove",
2213
- ids
2214
- });
2215
- return;
2216
- }
2217
- const crop = cropOf(primary.pon);
2218
- const drafts = crop ? annots.map((a) => a ? toCreateDraft(a, crop) : null) : annots.map(() => null);
2219
- if (drafts.some((d) => !d)) {
2220
- apply({
2221
- t: "remove",
2222
- ids
2223
- });
2224
- return;
2225
- }
2226
- (async () => {
2227
- const committed = [];
2228
- try {
2229
- const page = doc.page(primary.pon);
2230
- const primaryResult = await page.annotations.create(drafts[0]);
2231
- committed.push({
2232
- tempId: fx.primary,
2233
- ref: primaryResult.created.ref
2234
- });
2235
- apply({
2236
- t: "created",
2237
- tempId: fx.primary,
2238
- id: refKey(primaryResult.created.ref),
2239
- ref: primaryResult.created.ref
2240
- });
2241
- syncDTO(primaryResult.created, "vector");
2242
- for (let i = 0; i < fx.members.length; i++) {
2243
- const tempId = fx.members[i];
2244
- const draft = {
2245
- ...drafts[i + 1],
2246
- inReplyTo: primaryResult.created.ref,
2247
- replyType: "group"
2248
- };
2249
- const result = await page.annotations.create(draft);
2250
- committed.push({
2251
- tempId,
2252
- ref: result.created.ref
2253
- });
2254
- apply({
2255
- t: "created",
2256
- tempId,
2257
- id: refKey(result.created.ref),
2258
- ref: result.created.ref
2259
- });
2260
- syncDTO(result.created, "vector");
2261
- }
2262
- } catch (error) {
2263
- const removeIds = ids.filter((id) => !committed.some((c) => c.tempId === id));
2264
- for (const part of [...committed].reverse()) try {
2265
- await doc.page(primary.pon).annotations.delete(part.ref);
2266
- removeIds.push(refKey(part.ref));
2267
- } catch {}
2268
- if (removeIds.length) apply({
2269
- t: "remove",
2270
- ids: removeIds
2271
- });
2272
- console.error("[annotation] grouped annotation creation failed:", error);
2273
- }
2274
- })();
2275
- } else if (fx.fx === "create") {
2276
- const a = m.byId[fx.id];
2277
- const crop = a && cropOf(a.pon);
2278
- const draft = a && crop ? toCreateDraft(a, crop) : null;
2279
- if (!a || !draft) return;
2280
- doc.page(a.pon).annotations.create(draft).then((res) => {
2281
- apply({
2282
- t: "created",
2283
- tempId: fx.id,
2284
- id: refKey(res.created.ref),
2285
- ref: res.created.ref
2286
- });
2287
- syncDTO(res.created, "vector");
2288
- }, () => apply({
2289
- t: "createFailed",
2290
- tempId: fx.id
2291
- }));
2292
- } else if (fx.fx === "flags") {
2293
- const a = m.byId[fx.id];
2294
- if (!a || !a.ref || !a.data) return;
2295
- doc.page(a.pon).annotations.update(a.ref, {
2296
- subtype: a.data.subtype,
2297
- flags: a.flags
2298
- }).then((res) => syncDTO(res.updated, a.source), (err) => console.error("[annotation] flags write failed:", err));
2299
- } else if (fx.fx === "patch") {
2300
- const a = m.byId[fx.id];
2301
- const crop = a && cropOf(a.pon);
2302
- const patch = a && a.ref && crop ? toScopedPatch(a, fx.scope, crop) : null;
2303
- if (!a || !a.ref || !patch) return;
2304
- doc.page(a.pon).annotations.update(a.ref, patch).then((res) => {
2305
- syncDTO(res.updated, a.source, res.appearance.changed);
2306
- if (a.linkRefs?.length) scheduleLinkSync(fx.id);
2307
- }, () => {});
2308
- } else if (fx.fx === "syncLink") scheduleLinkSync(fx.id);
2309
- else doc.page(fx.ref.pageObjectNumber).annotations.delete(fx.ref).then(() => {}, () => {});
2310
- }
2311
- return {
2312
- create: async (pon, draft) => {
2313
- const doc = ctx.doc;
2314
- if (!doc) throw new Error("[annotation] no document bound");
2315
- const withFlags = draft.flags ? draft : {
2316
- ...draft,
2317
- flags: { print: true }
2318
- };
2319
- const res = await doc.page(pon).annotations.create(withFlags);
2320
- syncDTO(res.created, res.created.subtype === "stamp" ? "baked" : "vector");
2321
- return res.created.ref;
2322
- },
2323
- armStamp,
2324
- disarmStamp,
2325
- placeArmedStamp,
2326
- requestStampAt,
2327
- placeAt,
2328
- hasArmedStamp: () => armedStamp != null,
2329
- ghostHoverAt,
2330
- clearGhost,
2331
- setPlacementPreview,
2332
- clearPlacementPreview: clearGhost,
2333
- toolGhost: (pon) => {
2334
- const g = ctx.getState().toolGhost;
2335
- return g && g.pon === pon ? g : null;
2336
- },
2337
- armedStampPreview: () => armedStamp?.preview ?? null,
2338
- stampArmEpoch: () => ctx.getState().stampArmEpoch,
2339
- setFilePickerProvider: (provider) => {
2340
- filePickerProvider = provider;
2341
- },
2342
- downloadAttachment: async (ref) => {
2343
- const doc = ctx.doc;
2344
- if (!doc) throw new Error("[annotation] no document bound");
2345
- const pon = ponForRef(ref);
2346
- if (pon == null) throw new Error("[annotation] cannot resolve page for ref");
2347
- const annotations = doc.page(pon).annotations;
2348
- if (!annotations.downloadFile) throw new Error("[annotation] this engine does not support attachment download");
2349
- return annotations.downloadFile(ref);
2350
- },
2351
- tools: () => [...registry.values()],
2352
- tool: (id) => registry.get(id) ?? null,
2353
- toolSubtype: (id) => registry.get(id)?.subtype ?? id,
2354
- registerTool: (def) => {
2355
- const resolved = buildToolRegistry([...configTools, def]).get(def.id);
2356
- if (!resolved) throw new Error(`[annotation] could not resolve tool '${def.id}'`);
2357
- registry.set(resolved.id, resolved);
2358
- const un = ctx.tryGet(InteractionToken)?.registerTool({
2359
- id: resolved.id,
2360
- cursor: resolved.cursor,
2361
- enables: resolved.enables,
2362
- touchDirect: isTouchDirect(resolved.enables)
2363
- });
2364
- if (resolved.defaults) apply({
2365
- t: "setDefaults",
2366
- subtype: resolved.preset,
2367
- patch: resolved.defaults
2368
- });
2369
- return () => {
2370
- registry.delete(resolved.id);
2371
- un?.();
2372
- };
2373
- },
2374
- update: (ref, patch) => updateOne(ref, patch),
2375
- updateSelection: (patch) => apply({
2376
- t: "setProps",
2377
- patch
2378
- }),
2379
- updateSelectionFlags: (patch) => apply({
2380
- t: "setFlags",
2381
- patch
2382
- }),
2383
- getSelectionFlags: () => memoSelectionFlags(),
2384
- delete: async (ref) => {
2385
- const doc = ctx.doc;
2386
- if (!doc) throw new Error("[annotation] no document bound");
2387
- const pon = ponForRef(ref);
2388
- if (pon == null) throw new Error("[annotation] cannot resolve page for ref");
2389
- await doc.page(pon).annotations.delete(ref);
2390
- apply({
2391
- t: "remove",
2392
- ids: [refKey(ref)]
2393
- });
2394
- },
2395
- canCreate: () => ctx.doc?.security.allows(ANNOTATE_MODIFY) ?? false,
2396
- canEdit: () => ctx.doc?.security.allows(ANNOTATE_MODIFY) ?? false,
2397
- canDelete: () => ctx.doc?.security.allows(ANNOTATE_MODIFY) ?? false,
2398
- getSelection: () => {
2399
- const m = model();
2400
- return m.selected.map((id) => m.byId[id]?.ref).filter((r) => r != null);
2401
- },
2402
- get: (ref) => model().byId[refKey(ref)]?.data ?? null,
2403
- list: (pon) => {
2404
- const m = model();
2405
- return m.order.map((id) => m.byId[id]).filter((a) => a?.pon === pon).map((a) => a?.data).filter((d) => d != null);
2406
- },
2407
- getSelected: () => {
2408
- const m = model();
2409
- return m.selected.map((id) => m.byId[id]?.data).filter((d) => d != null);
2410
- },
2411
- getSelectionProps: () => memoSelectionProps(),
2412
- propsForTool: (toolId) => propsFor(registry.get(toolId)?.propsKind ?? toolId),
2413
- pageItems: (pon, view) => memoItems(pon, view),
2414
- chrome: (pon, scale, rotation, zoom) => memoChrome(pon, scale, rotation, zoom),
2415
- selectionAnchor: (scale, rotation, zoom) => memoAnchor(scale, rotation, zoom),
2416
- creationDraftAnchor: () => memoDraftAnchor(),
2417
- selection: () => model().selected,
2418
- hitKind: (pon, point, scale, rotation, zoom, touch) => hitTest(model(), pon, point, chromeGeomAt(scale, grabBoost(touch)), model().hitMargin, pageBoxOf(pon), inertIdsAt(pon), viewEnv(zoom, rotation)).t,
2419
- claimsTouchAt: (pon, point, scale, rotation, zoom) => {
2420
- const m = model();
2421
- const t = hitTest(m, pon, point, chromeGeomAt(scale, TOUCH_GRAB_BOOST), m.hitMargin, pageBoxOf(pon), inertIdsAt(pon), viewEnv(zoom, rotation));
2422
- if (t.t === "handle" || t.t === "rotate" || t.t === "group-handle") return true;
2423
- if (t.t === "annot") return m.selected.includes(t.id) && m.selected.every((id) => canMove(m, id));
2424
- return false;
2425
- },
2426
- cursorAt: (pon, point, scale, rotation, zoom) => cursorAt(model(), pon, point, chromeGeomAt(scale), model().hitMargin, pageBoxOf(pon), inertIdsAt(pon), viewEnv(zoom, rotation)),
2427
- hoverAt: (at) => {
2428
- const m = model();
2429
- let id = null;
2430
- if (at) {
2431
- const h = hitTest(m, at.pon, at.point, chromeGeomAt(at.scale), m.hitMargin, pageBoxOf(at.pon), inertIdsAt(at.pon), viewEnv(at.zoom, at.rotation));
2432
- if (h.t === "annot") id = h.id;
2433
- }
2434
- if (m.hovered !== id) apply({
2435
- t: "hover",
2436
- id
2437
- });
2438
- },
2439
- behaviorFor: (a) => behaviors.find((b) => b.matches(a) && b.engaged()) ?? null,
2440
- linkItemsOn: (pon) => memoLinkItems(pon),
2441
- appearanceEpoch: (pon) => {
2442
- const m = model();
2443
- const parts = [];
2444
- for (const id of m.order) {
2445
- const a = m.byId[id];
2446
- if (!a || a.pon !== pon || a.source !== "baked" || !a.ref) continue;
2447
- parts.push(`${id}@${a.apVersion ?? 0}`);
2448
- }
2449
- return parts.sort().join("|");
2450
- },
2451
- bakeScale: (renderScale) => snapAppearanceScale(ctx.document()?.renderPolicy ?? CONTINUOUS_RENDER_POLICY, renderScale),
2452
- appearances: (pon, scale, signal) => {
2453
- const doc = ctx.doc;
2454
- if (!doc) return Promise.resolve([]);
2455
- const task = doc.page(pon).annotations.renderAppearanceImages({ scale });
2456
- if (signal) if (signal.aborted) task.abort(signal.reason);
2457
- else signal.addEventListener("abort", () => task.abort(signal.reason), { once: true });
2458
- return task.then((r) => r.appearances, () => []);
2459
- },
2460
- toContentBox: (pon, rect) => {
2461
- const crop = cropOf(pon);
2462
- return crop ? pdfToContentRect(rect, crop) : null;
2463
- },
2464
- editPointer: (phase, pon, point, shift, scale, rotation, zoom, touch) => apply({
2465
- t: "editPointer",
2466
- phase,
2467
- in: {
2468
- pon,
2469
- point,
2470
- shift,
2471
- pageBox: pageBoxOf(pon),
2472
- chrome: chromeGeomAt(scale, grabBoost(touch)),
2473
- inert: inertIdsAt(pon),
2474
- ...zoom != null ? { zoom } : {},
2475
- ...rotation != null ? { displayRotation: rotation } : {}
2476
- }
2477
- }),
2478
- marqueePointer: (phase, pon, point, shift, scale, rotation, zoom) => apply({
2479
- t: "marqueePointer",
2480
- phase,
2481
- in: {
2482
- pon,
2483
- point,
2484
- shift,
2485
- pageBox: pageBoxOf(pon),
2486
- inert: inertIdsAt(pon),
2487
- ...zoom != null ? { zoom } : {},
2488
- ...rotation != null ? { displayRotation: rotation } : {}
2489
- }
2490
- }),
2491
- createPointer: (tool, phase, pon, point, finish = false, displayRotation) => {
2492
- const t = registry.get(tool);
2493
- apply({
2494
- t: "createPointer",
2495
- phase,
2496
- subtype: t?.subtype ?? tool,
2497
- preset: t?.preset ?? tool,
2498
- intent: t?.intent,
2499
- clickCreate: t?.clickCreate,
2500
- flags: t?.flags,
2501
- deferInkCommit: (t?.ink?.groupStrokesMs ?? 0) > 0,
2502
- straightenInk: t?.ink?.straighten,
2503
- in: {
2504
- pon,
2505
- point,
2506
- shift: false,
2507
- finish,
2508
- pageBox: pageBoxOf(pon),
2509
- displayRotation,
2510
- upright: t?.upright
2511
- }
2512
- });
2513
- },
2514
- finishCreationDraft: () => apply({ t: "finishCreationDraft" }),
2515
- finishInkDraft: () => apply({ t: "finishInkDraft" }),
2516
- cancelCreationDraft: () => apply({ t: "cancel" }),
2517
- markupFromSelection: (subtype, preset) => {
2518
- const selection = ctx.tryGet(SelectionToken);
2519
- if (!selection || !selection.hasSelection()) return false;
2520
- const snapshot = selection.snapshot();
2521
- let created = false;
2522
- for (const page of snapshot.pages) {
2523
- if (!page.segments.length) continue;
2524
- apply({
2525
- t: "createMarkup",
2526
- subtype,
2527
- pon: page.pon,
2528
- quads: page.segments.map((s) => s.quad),
2529
- preset,
2530
- flags: preset ? registry.get(preset)?.flags : void 0
2531
- });
2532
- created = true;
2533
- }
2534
- if (created) selection.clear();
2535
- return created;
2536
- },
2537
- createMarkup: (subtype, pon, quads, preset) => apply({
2538
- t: "createMarkup",
2539
- subtype,
2540
- pon,
2541
- quads,
2542
- preset,
2543
- flags: preset ? registry.get(preset)?.flags : void 0
2544
- }),
2545
- createCaret: (pon, anchor) => apply({
2546
- t: "createCaret",
2547
- pon,
2548
- anchor
2549
- }),
2550
- createReplaceText: (pon, quads, anchor, preset) => apply({
2551
- t: "createReplaceText",
2552
- pon,
2553
- quads,
2554
- anchor,
2555
- preset
2556
- }),
2557
- previewMarkup: (subtype, quadsByPage, preset) => apply({
2558
- t: "setMarkupPreview",
2559
- subtype,
2560
- quadsByPage,
2561
- preset
2562
- }),
2563
- clearMarkupPreview: () => apply({ t: "clearMarkupPreview" }),
2564
- setDefaults: (subtype, patch) => apply({
2565
- t: "setDefaults",
2566
- subtype,
2567
- patch
2568
- }),
2569
- currentDefaults: (toolId) => defaultsFor(model(), registry.get(toolId)?.preset ?? toolId),
2570
- setSnap: (patch) => apply({
2571
- t: "setSnap",
2572
- patch
2573
- }),
2574
- snapSettings: () => model().snap,
2575
- setChrome: (patch) => ctx.dispatch({
2576
- type: "SET_CHROME",
2577
- patch
2578
- }),
2579
- chromeSettings: () => chromeSettings(),
2580
- deleteSelection: () => apply({ t: "delete" }),
2581
- deselect: () => apply({ t: "deselect" }),
2582
- select: (ref, options) => {
2583
- apply({
2584
- t: "select",
2585
- ids: [refKey(ref)],
2586
- add: options?.add
2587
- });
2588
- },
2589
- pruneEngagedSelection: () => {
2590
- const m = model();
2591
- const drop = m.selected.filter((id) => {
2592
- const a = m.byId[id];
2593
- return a && behaviors.some((b) => b.matches({
2594
- subtype: a.subtype,
2595
- ref: a.ref
2596
- }) && b.engaged());
2597
- });
2598
- if (drop.length) apply({
2599
- t: "deselect",
2600
- ids: drop
2601
- });
2602
- },
2603
- cancel: () => apply({ t: "cancel" }),
2604
- rotateSelection90: () => apply({ t: "rotate90" }),
2605
- resetSelectionRotation: () => apply({ t: "resetRotation" }),
2606
- /** Group the current selection into one unit: the bottom-most member becomes
2607
- * the primary, every other member becomes a `/RT /Group` subordinate of it.
2608
- * No-op unless 2+ committed annotations on a single page are selected. */
2609
- group: async () => {
2610
- const m = model();
2611
- const members = selectedCommitted();
2612
- if (members.length < 2) return;
2613
- const pon = members[0].pon;
2614
- if (members.some((a) => a.pon !== pon)) return;
2615
- const [primary, ...rest] = [...members].sort((a, b) => m.order.indexOf(a.id) - m.order.indexOf(b.id));
2616
- if (!primary.ref) return;
2617
- await Promise.all(rest.map((a) => writeRelationship(a, {
2618
- inReplyTo: primary.ref,
2619
- replyType: "group"
2620
- })));
2621
- },
2622
- /** Ungroup: clear `/IRT` (+ `/RT`) on every subordinate in the group(s) the
2623
- * selection touches, so each member becomes top-level again. */
2624
- ungroup: async () => {
2625
- const m = model();
2626
- const subs = expandGroups(m, m.selected).map((id) => m.byId[id]).filter((a) => !!a && !!a.ref && !!a.data && !!a.group);
2627
- await Promise.all(subs.map((a) => writeRelationship(a, { inReplyTo: null })));
2628
- },
2629
- canGroup: () => {
2630
- if (!(ctx.doc?.security.allows(ANNOTATE_MODIFY) ?? false)) return false;
2631
- const m = model();
2632
- const members = selectedCommitted();
2633
- if (members.length < 2) return false;
2634
- if (members.some((a) => a.pon !== members[0].pon)) return false;
2635
- const keys = new Set(m.selected.map((id) => groupKeyOf(m, id)));
2636
- if (keys.size === 1 && !keys.has(null)) return false;
2637
- return true;
2638
- },
2639
- canUngroup: () => {
2640
- if (!(ctx.doc?.security.allows(ANNOTATE_MODIFY) ?? false)) return false;
2641
- const m = model();
2642
- return m.selected.some((id) => groupKeyOf(m, id) != null);
2643
- },
2644
- ensurePage: (pon) => {
2645
- if (loaded.has(pon)) return;
2646
- const doc = ctx.doc;
2647
- const crop = cropOf(pon);
2648
- if (!doc || !crop) return;
2649
- loaded.add(pon);
2650
- doc.page(pon).annotations.list().then((snap) => apply({
2651
- t: "loaded",
2652
- annots: foldAttachedLinks(snap.annotations.map((d) => fromDTO(d, crop)))
2653
- }), () => {
2654
- loaded.delete(pon);
2655
- });
2656
- },
2657
- reloadPage: async (pon) => {
2658
- const doc = ctx.doc;
2659
- const crop = cropOf(pon);
2660
- if (!doc || !crop) return;
2661
- loaded.add(pon);
2662
- try {
2663
- const snap = await doc.page(pon).annotations.list();
2664
- const m = model();
2665
- const stale = m.order.filter((id) => m.byId[id]?.pon === pon);
2666
- if (stale.length) apply({
2667
- t: "remove",
2668
- ids: stale
2669
- });
2670
- apply({
2671
- t: "loaded",
2672
- annots: foldAttachedLinks(snap.annotations.map((d) => fromDTO(d, crop)))
2673
- });
2674
- } catch {
2675
- loaded.delete(pon);
2676
- }
2677
- },
2678
- textItems: (pon, view) => memoTexts(pon, view),
2679
- currentEditing: () => model().editing,
2680
- beginTextEdit: (ref) => apply({
2681
- t: "beginTextEdit",
2682
- id: refKey(ref)
2683
- }),
2684
- beginTextEditAt: (pon, point, scale, rotation, zoom) => {
2685
- const m = model();
2686
- const h = hitTest(m, pon, point, chromeGeomAt(scale), m.hitMargin, pageBoxOf(pon), void 0, viewEnv(zoom, rotation));
2687
- const id = h.t === "annot" || h.t === "handle" ? h.id : null;
2688
- if (id != null && m.byId[id]?.geom.t === "text") {
2689
- apply({
2690
- t: "beginTextEdit",
2691
- id
2692
- });
2693
- return true;
2694
- }
2695
- return false;
2696
- },
2697
- setContents: (ref, text) => {
2698
- apply({
2699
- t: "setText",
2700
- id: refKey(ref),
2701
- text
2702
- });
2703
- const key = refKey(ref);
2704
- clearTimeout(textTimers.get(key));
2705
- textTimers.set(key, setTimeout(() => {
2706
- textTimers.delete(key);
2707
- const pon = ponForRef(ref);
2708
- if (pon != null) ctx.doc?.page(pon).annotations.update(ref, {
2709
- subtype: "free-text",
2710
- contents: text
2711
- }).then(() => {}, () => {});
2712
- }, TEXT_COMMIT_DEBOUNCE_MS));
2713
- },
2714
- endTextEdit: () => {
2715
- for (const t of textTimers.values()) clearTimeout(t);
2716
- const id = model().editing;
2717
- const a = id ? model().byId[id] : null;
2718
- if (a?.ref) {
2719
- const pon = ponForRef(a.ref);
2720
- const text = a.data?.contents ?? "";
2721
- if (pon != null) ctx.doc?.page(pon).annotations.update(a.ref, {
2722
- subtype: "free-text",
2723
- contents: text
2724
- }).then(() => {}, () => {});
2725
- }
2726
- textTimers.clear();
2727
- apply({ t: "endTextEdit" });
2728
- },
2729
- registerBehavior: (b) => {
2730
- behaviors.push(b);
2731
- return () => {
2732
- const i = behaviors.indexOf(b);
2733
- if (i >= 0) behaviors.splice(i, 1);
2734
- };
2735
- }
2736
- };
2737
- }
2738
- //#endregion
2739
- export { fromDTO as a, refKey as c, AnnotationToken as d, isTouchDirect as i, styleFromDTO as l, DEFAULT_TOOLS as n, toCreateDraft as o, buildToolRegistry as r, toPatch as s, createAnnotationCapability as t, widgetAppearanceFromProps as u };
2740
-
2741
- //# sourceMappingURL=capability-BNMRdnKf.js.map