@inkbar/core 0.2.0 → 0.4.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.
@@ -0,0 +1,3922 @@
1
+ import { z } from "zod";
2
+ import { v7 } from "uuid";
3
+ //#region src/model/errors.ts
4
+ var InkError = class extends Error {
5
+ name = "InkError";
6
+ code;
7
+ details;
8
+ constructor(code, message, details = {}, cause) {
9
+ super(message, cause === void 0 ? void 0 : { cause });
10
+ this.code = code;
11
+ this.details = details;
12
+ }
13
+ };
14
+ function isInkError(value) {
15
+ return value instanceof InkError || typeof value === "object" && value !== null && value.name === "InkError";
16
+ }
17
+ //#endregion
18
+ //#region src/model/events.ts
19
+ var Emitter = class {
20
+ listeners = /* @__PURE__ */ new Map();
21
+ on(event, fn) {
22
+ let set = this.listeners.get(event);
23
+ if (!set) {
24
+ set = /* @__PURE__ */ new Set();
25
+ this.listeners.set(event, set);
26
+ }
27
+ set.add(fn);
28
+ return () => {
29
+ set?.delete(fn);
30
+ };
31
+ }
32
+ emit(event, payload) {
33
+ const set = this.listeners.get(event);
34
+ if (!set) return;
35
+ for (const fn of [...set]) fn(payload);
36
+ }
37
+ clear() {
38
+ this.listeners.clear();
39
+ }
40
+ };
41
+ //#endregion
42
+ //#region src/model/geometry.ts
43
+ function approxEqual(a, b, eps = .01) {
44
+ return Math.abs(a - b) <= eps;
45
+ }
46
+ function rectFromPoints(a, b) {
47
+ return {
48
+ x: Math.min(a.x, b.x),
49
+ y: Math.min(a.y, b.y),
50
+ width: Math.abs(a.x - b.x),
51
+ height: Math.abs(a.y - b.y)
52
+ };
53
+ }
54
+ function rectFromQuad(q) {
55
+ const xs = [
56
+ q.p1.x,
57
+ q.p2.x,
58
+ q.p3.x,
59
+ q.p4.x
60
+ ];
61
+ const ys = [
62
+ q.p1.y,
63
+ q.p2.y,
64
+ q.p3.y,
65
+ q.p4.y
66
+ ];
67
+ const x = Math.min(...xs);
68
+ const y = Math.min(...ys);
69
+ return {
70
+ x,
71
+ y,
72
+ width: Math.max(...xs) - x,
73
+ height: Math.max(...ys) - y
74
+ };
75
+ }
76
+ function quadFromRect(r) {
77
+ const top = r.y + r.height;
78
+ const right = r.x + r.width;
79
+ return {
80
+ p1: {
81
+ x: r.x,
82
+ y: top
83
+ },
84
+ p2: {
85
+ x: right,
86
+ y: top
87
+ },
88
+ p3: {
89
+ x: r.x,
90
+ y: r.y
91
+ },
92
+ p4: {
93
+ x: right,
94
+ y: r.y
95
+ }
96
+ };
97
+ }
98
+ function unionRects(rects) {
99
+ if (rects.length === 0) throw new RangeError("unionRects needs at least one rect");
100
+ let x1 = Infinity;
101
+ let y1 = Infinity;
102
+ let x2 = -Infinity;
103
+ let y2 = -Infinity;
104
+ for (const r of rects) {
105
+ x1 = Math.min(x1, r.x);
106
+ y1 = Math.min(y1, r.y);
107
+ x2 = Math.max(x2, r.x + r.width);
108
+ y2 = Math.max(y2, r.y + r.height);
109
+ }
110
+ return {
111
+ x: x1,
112
+ y: y1,
113
+ width: x2 - x1,
114
+ height: y2 - y1
115
+ };
116
+ }
117
+ function rectsIntersect(a, b) {
118
+ return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
119
+ }
120
+ function rectContainsPoint(r, p) {
121
+ return p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height;
122
+ }
123
+ function translateRect(r, dx, dy) {
124
+ return {
125
+ x: r.x + dx,
126
+ y: r.y + dy,
127
+ width: r.width,
128
+ height: r.height
129
+ };
130
+ }
131
+ function translateQuad(q, dx, dy) {
132
+ const t = (p) => ({
133
+ x: p.x + dx,
134
+ y: p.y + dy
135
+ });
136
+ return {
137
+ p1: t(q.p1),
138
+ p2: t(q.p2),
139
+ p3: t(q.p3),
140
+ p4: t(q.p4)
141
+ };
142
+ }
143
+ function applyMatrix(m, p) {
144
+ return {
145
+ x: m[0] * p.x + m[2] * p.y + m[4],
146
+ y: m[1] * p.x + m[3] * p.y + m[5]
147
+ };
148
+ }
149
+ function invertMatrix(m) {
150
+ const det = m[0] * m[3] - m[1] * m[2];
151
+ if (det === 0) throw new RangeError("matrix is not invertible");
152
+ return [
153
+ m[3] / det,
154
+ -m[1] / det,
155
+ -m[2] / det,
156
+ m[0] / det,
157
+ (m[2] * m[5] - m[3] * m[4]) / det,
158
+ (m[1] * m[4] - m[0] * m[5]) / det
159
+ ];
160
+ }
161
+ /** Returns the matrix that applies `a` first, then `b`. */
162
+ function multiplyMatrix(a, b) {
163
+ return [
164
+ a[0] * b[0] + a[1] * b[2],
165
+ a[0] * b[1] + a[1] * b[3],
166
+ a[2] * b[0] + a[3] * b[2],
167
+ a[2] * b[1] + a[3] * b[3],
168
+ a[4] * b[0] + a[5] * b[2] + b[4],
169
+ a[4] * b[1] + a[5] * b[3] + b[5]
170
+ ];
171
+ }
172
+ function pointsFromFlat(flat) {
173
+ const out = [];
174
+ for (let i = 0; i + 1 < flat.length; i += 2) out.push({
175
+ x: flat[i],
176
+ y: flat[i + 1]
177
+ });
178
+ return out;
179
+ }
180
+ /** Eight numbers per quad, in PDF.js's normalised order. Trailing partial quads are dropped. */
181
+ function quadsFromFlat(flat) {
182
+ const pts = pointsFromFlat(flat);
183
+ const out = [];
184
+ for (let i = 0; i + 3 < pts.length; i += 4) out.push({
185
+ p1: pts[i],
186
+ p2: pts[i + 1],
187
+ p3: pts[i + 2],
188
+ p4: pts[i + 3]
189
+ });
190
+ return out;
191
+ }
192
+ //#endregion
193
+ //#region src/model/readable.ts
194
+ function writable(initial) {
195
+ let value = initial;
196
+ const subs = /* @__PURE__ */ new Set();
197
+ const set = (next) => {
198
+ if (Object.is(next, value)) return;
199
+ value = next;
200
+ for (const fn of [...subs]) fn(value);
201
+ };
202
+ return {
203
+ get: () => value,
204
+ set,
205
+ update(fn) {
206
+ set(fn(value));
207
+ },
208
+ subscribe(fn) {
209
+ subs.add(fn);
210
+ return () => {
211
+ subs.delete(fn);
212
+ };
213
+ }
214
+ };
215
+ }
216
+ /**
217
+ * A readable computed from `source`. It subscribes to the source only while it has
218
+ * subscribers of its own, so an unobserved derived value holds no reference to the source.
219
+ */
220
+ function derived(source, fn) {
221
+ const subs = /* @__PURE__ */ new Set();
222
+ let cached;
223
+ let stopSource;
224
+ const onSource = (v) => {
225
+ const next = fn(v);
226
+ if (Object.is(next, cached)) return;
227
+ cached = next;
228
+ for (const sub of [...subs]) sub(next);
229
+ };
230
+ return {
231
+ get: () => stopSource ? cached : fn(source.get()),
232
+ subscribe(sub) {
233
+ if (!stopSource) {
234
+ cached = fn(source.get());
235
+ stopSource = source.subscribe(onSource);
236
+ }
237
+ subs.add(sub);
238
+ return () => {
239
+ if (!subs.delete(sub) || subs.size > 0) return;
240
+ stopSource?.();
241
+ stopSource = void 0;
242
+ };
243
+ }
244
+ };
245
+ }
246
+ function readonly(w) {
247
+ return {
248
+ get: () => w.get(),
249
+ subscribe: (fn) => w.subscribe(fn)
250
+ };
251
+ }
252
+ //#endregion
253
+ //#region src/model/selection.ts
254
+ const union = (a, b) => {
255
+ const x = Math.min(a.x, b.x);
256
+ const y = Math.min(a.y, b.y);
257
+ return {
258
+ x,
259
+ y,
260
+ width: Math.max(a.x + a.width, b.x + b.width) - x,
261
+ height: Math.max(a.y + a.height, b.y + b.height) - y
262
+ };
263
+ };
264
+ const centreY = (r) => r.y + r.height / 2;
265
+ function median(values) {
266
+ const sorted = [...values].sort((a, b) => a - b);
267
+ const mid = sorted.length >> 1;
268
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
269
+ }
270
+ /**
271
+ * Merges glyph boxes that share a line into one quad per run, ordered top to bottom (by
272
+ * vertical centre) then left to right. Boxes whose vertical centres are within `tolerance`
273
+ * points count as the same line; boxes with no area are dropped. Within a line, a horizontal
274
+ * gap wider than `gap` points (default 1.5 × the line's median box height) starts a new run,
275
+ * so text selected across a column gutter yields one quad per column. Pure user-space maths.
276
+ */
277
+ function mergeLineRects(rects, tolerance = 2, gap) {
278
+ const lines = [];
279
+ for (const r of rects) {
280
+ if (!(r.width > 0 && r.height > 0)) continue;
281
+ const line = lines.find((l) => Math.abs(centreY(l.bounds) - centreY(r)) <= tolerance);
282
+ if (!line) {
283
+ lines.push({
284
+ bounds: { ...r },
285
+ boxes: [r]
286
+ });
287
+ continue;
288
+ }
289
+ line.bounds = union(line.bounds, r);
290
+ line.boxes.push(r);
291
+ }
292
+ const runs = [];
293
+ for (const line of lines) {
294
+ const maxGap = gap ?? 1.5 * median(line.boxes.map((b) => b.height));
295
+ const boxes = [...line.boxes].sort((a, b) => a.x - b.x);
296
+ let run = { ...boxes[0] };
297
+ for (const b of boxes.slice(1)) if (b.x - (run.x + run.width) > maxGap) {
298
+ runs.push(run);
299
+ run = { ...b };
300
+ } else run = union(run, b);
301
+ runs.push(run);
302
+ }
303
+ runs.sort((a, b) => centreY(b) - centreY(a) || a.x - b.x);
304
+ return runs.map(quadFromRect);
305
+ }
306
+ //#endregion
307
+ //#region src/pdfjs/load.ts
308
+ const REQUIRED = [
309
+ "worker",
310
+ "cMaps",
311
+ "standardFonts",
312
+ "wasm"
313
+ ];
314
+ function assertAssets(value) {
315
+ const record = typeof value === "object" && value !== null ? value : {};
316
+ const missing = REQUIRED.filter((k) => typeof record[k] !== "string" || record[k] === "");
317
+ if (value === void 0 || value === null || missing.length > 0) throw new InkError("AssetConfigMissing", "openDocument needs an `assets` option naming the PDF.js worker, cMaps, standardFonts and wasm locations. Vite users: add the @inkbar/core/vite plugin and pass `assets` from \"virtual:inkbar-assets\".", { missing: value == null ? [...REQUIRED] : missing });
318
+ }
319
+ let modulePromise;
320
+ let configuredWorker;
321
+ /**
322
+ * Loads PDF.js once. `#pdfjs` resolves to the legacy build in Node and the
323
+ * modern build everywhere else (see package.json "imports").
324
+ */
325
+ async function loadPdfjs(assets) {
326
+ assertAssets(assets);
327
+ modulePromise ??= import("#pdfjs").catch((cause) => {
328
+ modulePromise = void 0;
329
+ throw new InkError("AssetLoadFailed", "PDF.js could not be imported", { url: assets.worker }, cause);
330
+ });
331
+ const pdfjs = await modulePromise;
332
+ if (configuredWorker === void 0) {
333
+ pdfjs.GlobalWorkerOptions.workerSrc = assets.worker;
334
+ configuredWorker = assets.worker;
335
+ } else if (configuredWorker !== assets.worker) throw new InkError("AssetConfigMissing", "PDF.js worker URL cannot change after the first document is opened", {
336
+ configured: configuredWorker,
337
+ requested: assets.worker
338
+ });
339
+ return pdfjs;
340
+ }
341
+ async function openProxy(pdfjs, bytes, options) {
342
+ const { assets, password, verbosity } = options;
343
+ const task = pdfjs.getDocument({
344
+ data: bytes,
345
+ ...password !== void 0 ? { password } : {},
346
+ ...verbosity !== void 0 ? { verbosity } : {},
347
+ cMapUrl: assets.cMaps,
348
+ cMapPacked: true,
349
+ standardFontDataUrl: assets.standardFonts,
350
+ wasmUrl: assets.wasm,
351
+ ...assets.icc !== void 0 ? { iccUrl: assets.icc } : {}
352
+ });
353
+ try {
354
+ return {
355
+ task,
356
+ proxy: await task.promise
357
+ };
358
+ } catch (cause) {
359
+ try {
360
+ await task.destroy();
361
+ } catch {}
362
+ throw mapLoadError(cause, {
363
+ assets,
364
+ passwordSupplied: password !== void 0
365
+ });
366
+ }
367
+ }
368
+ /** `PasswordResponses` values from PDF.js (`NEED_PASSWORD = 1`, `INCORRECT_PASSWORD = 2`). */
369
+ const INCORRECT_PASSWORD = 2;
370
+ /**
371
+ * PDF.js raises these from `task.promise` when the worker script cannot be
372
+ * imported (in browsers after its real Worker fails and the fake-worker
373
+ * fallback also fails to import `workerSrc`).
374
+ */
375
+ const WORKER_FAILURE = /Setting up fake worker failed|No "GlobalWorkerOptions\.workerSrc" specified/i;
376
+ /**
377
+ * Only the worker is mapped here. CMap, standard-font and wasm failures are
378
+ * PDF.js warnings with fallbacks that never reject the open promise, so they
379
+ * cannot be detected at open time.
380
+ *
381
+ * PDF.js 6 exports only some exception classes (`PasswordException`,
382
+ * `InvalidPDFException`, `ResponseException`, `AbortException`), and errors
383
+ * that cross the worker boundary are rebuilt by name, so match on `name`.
384
+ * Inputs here are always in-memory bytes, so there is no fetch to fail:
385
+ * every non-password failure means the bytes are not a usable PDF.
386
+ */
387
+ function mapLoadError(cause, context) {
388
+ const { assets, passwordSupplied = false } = context;
389
+ const name = cause?.name;
390
+ const rawMessage = cause?.message;
391
+ const message = typeof rawMessage === "string" && rawMessage !== "" ? rawMessage : "Unknown PDF.js error";
392
+ if (WORKER_FAILURE.test(message)) return new InkError("AssetLoadFailed", "The PDF.js worker could not be loaded. Check the `assets.worker` URL.", { url: assets.worker }, cause);
393
+ if (name === "PasswordException") {
394
+ const wrong = cause.code === INCORRECT_PASSWORD;
395
+ return new InkError("PasswordRequired", wrong ? "The password is incorrect" : "This document is encrypted and needs a password", {
396
+ passwordSupplied,
397
+ incorrect: wrong
398
+ }, cause);
399
+ }
400
+ return new InkError("InvalidPdf", message, {
401
+ pdfjsErrorName: typeof name === "string" ? name : void 0,
402
+ pdfjsMessage: message
403
+ }, cause);
404
+ }
405
+ //#endregion
406
+ //#region src/model/annotations/defaults.ts
407
+ const COLORS = {
408
+ highlight: "#F2C230",
409
+ underline: "#2B5A9E",
410
+ strikeout: "#C0392B",
411
+ squiggly: "#1F7A4D",
412
+ text: "#F2C230",
413
+ freetext: "#151820",
414
+ square: "#C0392B",
415
+ circle: "#C0392B",
416
+ line: "#151820",
417
+ polyline: "#151820",
418
+ polygon: "#151820",
419
+ ink: "#151820",
420
+ stamp: "#151820",
421
+ loupe: "#151820",
422
+ mask: "#000000",
423
+ redact: "#C0392B"
424
+ };
425
+ /**
426
+ * Suggested-redaction colours, strengthening with confidence: amber for low, orange for
427
+ * medium, the redaction red for high.
428
+ */
429
+ const SUGGESTION_COLORS = {
430
+ low: "#D4A017",
431
+ medium: "#E67E22",
432
+ high: "#C0392B"
433
+ };
434
+ const staticDefaults = {
435
+ color: (type) => COLORS[type],
436
+ fill: () => "#000000",
437
+ opacity: (type) => type === "highlight" ? .4 : 1,
438
+ suggestion: (bucket) => SUGGESTION_COLORS[bucket]
439
+ };
440
+ const VARIABLES = {
441
+ highlight: "--ink-highlight",
442
+ underline: "--ink-underline",
443
+ strikeout: "--ink-strikeout",
444
+ squiggly: "--ink-squiggly",
445
+ text: "--ink-note",
446
+ freetext: "--ink-free-text",
447
+ square: "--ink-shape",
448
+ circle: "--ink-shape",
449
+ line: "--ink-shape",
450
+ polyline: "--ink-shape",
451
+ polygon: "--ink-shape",
452
+ ink: "--ink-ink",
453
+ stamp: "--ink-ink",
454
+ loupe: "--ink-shape",
455
+ mask: "--ink-mask",
456
+ redact: "--ink-redact"
457
+ };
458
+ /** Resolves default colours from CSS custom properties on `el`, falling back to `staticDefaults`. */
459
+ function cssVariableDefaults(el) {
460
+ const read = (name) => {
461
+ const view = el.ownerDocument.defaultView;
462
+ if (!view) return void 0;
463
+ return normalizeColor(view.getComputedStyle(el).getPropertyValue(name));
464
+ };
465
+ return {
466
+ color: (type) => read(VARIABLES[type]) ?? staticDefaults.color(type),
467
+ fill: () => read("--ink-redact-fill") ?? staticDefaults.fill(),
468
+ opacity: (type) => staticDefaults.opacity(type),
469
+ suggestion: (bucket) => read(`--ink-suggestion-${bucket}`) ?? staticDefaults.suggestion(bucket)
470
+ };
471
+ }
472
+ /** Accepts `#rgb`, `#rrggbb`, `rgb(r, g, b)` and `rgb(r g b)`; returns `#RRGGBB` or undefined. */
473
+ function normalizeColor(value) {
474
+ const v = value.trim();
475
+ const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(v);
476
+ if (short) {
477
+ const [, r = "", g = "", b = ""] = short;
478
+ return `#${r}${r}${g}${g}${b}${b}`.toUpperCase();
479
+ }
480
+ if (/^#[0-9a-f]{6}$/i.test(v)) return v.toUpperCase();
481
+ const rgb = /^rgba?\(\s*(\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})/i.exec(v);
482
+ if (rgb) return `#${[
483
+ rgb[1],
484
+ rgb[2],
485
+ rgb[3]
486
+ ].map((n) => Math.min(255, Number(n)).toString(16).padStart(2, "0")).join("")}`.toUpperCase();
487
+ }
488
+ //#endregion
489
+ //#region src/model/pdf-date.ts
490
+ /** Parses a PDF date string (`D:YYYYMMDDHHmmSSOHH'mm'`) into ISO 8601. Returns `fallback` on anything unparseable. */
491
+ function parsePdfDate(value, fallback) {
492
+ if (!value) return fallback;
493
+ const m = /^(?:D:)?(\d{4})(\d{2})?(\d{2})?(\d{2})?(\d{2})?(\d{2})?(Z|[+-]\d{2}(?:'\d{2}')?)?/.exec(value.trim());
494
+ if (!m) return fallback;
495
+ const [, y, mo = "01", d = "01", h = "00", mi = "00", s = "00", zone] = m;
496
+ let offsetMinutes = 0;
497
+ if (zone && zone !== "Z") {
498
+ const sign = zone.startsWith("-") ? -1 : 1;
499
+ const zh = Number(zone.slice(1, 3));
500
+ const zm = Number(zone.slice(4, 6) || 0);
501
+ offsetMinutes = sign * (zh * 60 + zm);
502
+ }
503
+ const utc = Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s)) - offsetMinutes * 6e4;
504
+ if (Number.isNaN(utc)) return fallback;
505
+ return new Date(utc).toISOString();
506
+ }
507
+ //#endregion
508
+ //#region src/model/annotations/pdf-names.ts
509
+ /**
510
+ * A PDF name: a non-empty run of regular characters, so no whitespace and none of the
511
+ * delimiters `( ) < > [ ] { } / %`.
512
+ */
513
+ const PDF_NAME = /^[^\s()<>[\]{}/%]+$/;
514
+ /**
515
+ * A set of PDF names Inkbar knows that stays open: any other valid PDF name loads, is kept and
516
+ * is written back unchanged. The output type keeps autocomplete for the known values.
517
+ */
518
+ function pdfNameSet(known) {
519
+ return z.union([z.enum(known), z.string().regex(PDF_NAME, "expected a PDF name")]).describe(`One of ${known.join(", ")}. Any other PDF name is allowed and kept unchanged.`);
520
+ }
521
+ /** Line ending styles (PDF `/LE`). */
522
+ const LINE_ENDINGS = [
523
+ "None",
524
+ "Square",
525
+ "Circle",
526
+ "Diamond",
527
+ "OpenArrow",
528
+ "ClosedArrow",
529
+ "Butt",
530
+ "ROpenArrow",
531
+ "RClosedArrow",
532
+ "Slash"
533
+ ];
534
+ /** Note icons (PDF `/Name` on a text annotation). */
535
+ const NOTE_ICONS = [
536
+ "Comment",
537
+ "Note",
538
+ "Help",
539
+ "Insert",
540
+ "Key",
541
+ "NewParagraph",
542
+ "Paragraph"
543
+ ];
544
+ /** Annotation intents (PDF `/IT`). */
545
+ const INTENTS = [
546
+ "FreeText",
547
+ "FreeTextCallout",
548
+ "FreeTextTypeWriter",
549
+ "LineArrow",
550
+ "LineDimension",
551
+ "PolygonCloud",
552
+ "PolygonDimension",
553
+ "PolyLineDimension"
554
+ ];
555
+ /** True when `v` is one of the values in `list`. */
556
+ function isKnown(list, v) {
557
+ return list.includes(v);
558
+ }
559
+ //#endregion
560
+ //#region src/model/annotations/callout.ts
561
+ /**
562
+ * The insets from a free text's `rect` to its text box, in points (PDF `/RD`, XFDF `fringe`,
563
+ * both in this order).
564
+ */
565
+ const FringeSchema = z.object({
566
+ left: z.number().nonnegative(),
567
+ top: z.number().nonnegative(),
568
+ right: z.number().nonnegative(),
569
+ bottom: z.number().nonnegative()
570
+ });
571
+ /** An ending's length, and its full width, as a multiple of the stroke width. */
572
+ const ENDING_SCALE = 3;
573
+ /**
574
+ * A free text's text box: `rect` inset by `fringe`, or `rect` itself without one. Insets wider
575
+ * or taller than `rect` leave a box of width or height 0 at the inset origin.
576
+ */
577
+ function freeTextBox(a) {
578
+ const { rect, fringe } = a;
579
+ if (!fringe) return rect;
580
+ return {
581
+ x: rect.x + fringe.left,
582
+ y: rect.y + fringe.bottom,
583
+ width: Math.max(0, rect.width - fringe.left - fringe.right),
584
+ height: Math.max(0, rect.height - fringe.top - fringe.bottom)
585
+ };
586
+ }
587
+ /**
588
+ * True for a free-text callout drawn the standard way: a box with a leader line through
589
+ * `callout`. A callout with `cornerRadius` is Inkbar's speech bubble instead.
590
+ */
591
+ function isStandardCallout(a) {
592
+ return a.type === "freetext" && a.intent === "FreeTextCallout" && a.callout !== void 0 && a.callout.length >= 2 && a.cornerRadius === void 0;
593
+ }
594
+ /**
595
+ * The leader line's stroke: the border colour, else the text colour, and the border width, with
596
+ * 1 pt when the box has no border.
597
+ */
598
+ function calloutStroke(a) {
599
+ return {
600
+ color: a.borderColor ?? a.defaultStyle.color,
601
+ width: a.width > 0 ? a.width : 1
602
+ };
603
+ }
604
+ /**
605
+ * The `rect` and `fringe` that hold the text box `box` and a leader line through `callout`
606
+ * stroked `width` points wide: every point is padded by half the stroke, and by the ending's
607
+ * size as well when `head` is one Inkbar draws.
608
+ */
609
+ function withCalloutBounds(box, callout, width, head) {
610
+ const drawn = head !== void 0 && head !== "None" && isKnown(LINE_ENDINGS, head);
611
+ const pad = width / 2 + (drawn ? ENDING_SCALE * Math.max(width, 1) : 0);
612
+ const xs = [
613
+ box.x,
614
+ box.x + box.width,
615
+ ...callout.map((p) => p.x)
616
+ ];
617
+ const ys = [
618
+ box.y,
619
+ box.y + box.height,
620
+ ...callout.map((p) => p.y)
621
+ ];
622
+ const left = Math.min(...xs) - pad;
623
+ const bottom = Math.min(...ys) - pad;
624
+ const right = Math.max(...xs) + pad;
625
+ const top = Math.max(...ys) + pad;
626
+ return {
627
+ rect: {
628
+ x: left,
629
+ y: bottom,
630
+ width: right - left,
631
+ height: top - bottom
632
+ },
633
+ fringe: {
634
+ left: box.x - left,
635
+ top: top - (box.y + box.height),
636
+ right: right - (box.x + box.width),
637
+ bottom: box.y - bottom
638
+ }
639
+ };
640
+ }
641
+ //#endregion
642
+ //#region src/model/annotations/types.ts
643
+ const ANNOTATION_FORMAT = "inkbar/annotations";
644
+ const ANNOTATION_VERSION = 1;
645
+ const Hex = z.string().regex(/^#[0-9a-fA-F]{6}$/, "expected #RRGGBB");
646
+ const PointSchema = z.object({
647
+ x: z.number(),
648
+ y: z.number()
649
+ });
650
+ const RectSchema = z.object({
651
+ x: z.number(),
652
+ y: z.number(),
653
+ width: z.number().nonnegative(),
654
+ height: z.number().nonnegative()
655
+ });
656
+ const QuadSchema = z.object({
657
+ p1: PointSchema,
658
+ p2: PointSchema,
659
+ p3: PointSchema,
660
+ p4: PointSchema
661
+ });
662
+ const Base = z.object({
663
+ /** Client id, UUIDv7, assigned at creation and never reassigned. Embedded annotations use `pdf:<ref>`. */
664
+ id: z.string().min(1),
665
+ /** 0-based page index. */
666
+ page: z.number().int().nonnegative(),
667
+ /** Bounding box in PDF user space. */
668
+ rect: RectSchema,
669
+ /** Resolved #RRGGBB. Written into the PDF later, so it is always concrete. */
670
+ color: Hex,
671
+ opacity: z.number().min(0).max(1),
672
+ author: z.string().optional(),
673
+ contents: z.string().optional(),
674
+ /** Id of the parent note; replies form threads. */
675
+ inReplyTo: z.string().optional(),
676
+ /** ISO 8601 date-time. */
677
+ createdAt: z.iso.datetime({ offset: true }),
678
+ /** ISO 8601 date-time. */
679
+ modifiedAt: z.iso.datetime({ offset: true }),
680
+ /** Created in this session, or imported from the file. Viewer state, never exported. */
681
+ source: z.enum(["session", "pdf"]),
682
+ /** Embedded annotations are locked until the engine can rewrite the file. Viewer state, never exported. */
683
+ locked: z.boolean().optional(),
684
+ /** Short label for what the mark is (XFDF `subject`). */
685
+ subject: z.string().optional(),
686
+ /** What the mark is for, e.g. a callout or an arrow (XFDF `intent`, a PDF name). */
687
+ intent: pdfNameSet(INTENTS).optional(),
688
+ /** Host data. Preserved, never interpreted. */
689
+ custom: z.record(z.string(), z.unknown()).optional()
690
+ });
691
+ const TextMarkupSchema = Base.extend({
692
+ type: z.enum([
693
+ "highlight",
694
+ "underline",
695
+ "strikeout",
696
+ "squiggly"
697
+ ]),
698
+ quads: z.array(QuadSchema).min(1)
699
+ });
700
+ /** A note's icon (XFDF `icon`): a PDF name, so a name Inkbar does not know is kept. */
701
+ const NoteIconSchema = pdfNameSet(NOTE_ICONS);
702
+ const NoteSchema = Base.extend({
703
+ type: z.literal("text"),
704
+ icon: NoteIconSchema.default("Note")
705
+ });
706
+ /** A line ending (XFDF `head`/`tail`): a PDF name, so a name Inkbar does not know is kept. */
707
+ const LineEndingSchema = pdfNameSet(LINE_ENDINGS);
708
+ /** Dash pattern in points, on then off, repeating. Absent means solid. */
709
+ const DashesSchema = z.array(z.number().nonnegative()).min(1).optional();
710
+ /**
711
+ * A key a type refuses outright rather than dropping like other unknown keys: one an older
712
+ * shape used (so its value is not silently lost), or one that means nothing on the type (so a
713
+ * later version is free to give it a meaning).
714
+ */
715
+ const Refused = z.never().optional();
716
+ /**
717
+ * A free-text box's text style, keyed by the CSS property names XFDF writes in its
718
+ * `defaultstyle` string. The older `align` is refused; other unknown keys are dropped.
719
+ */
720
+ const FreeTextStyleSchema = z.object({
721
+ fontFamily: z.string().min(1).default("Helvetica"),
722
+ /** Points. */
723
+ fontSize: z.number().positive().default(12),
724
+ /** The text colour. */
725
+ color: Hex,
726
+ textAlign: z.enum([
727
+ "left",
728
+ "center",
729
+ "right",
730
+ "justify"
731
+ ]).default("left"),
732
+ fontWeight: z.literal("bold").optional(),
733
+ fontStyle: z.literal("italic").optional(),
734
+ textDecoration: z.literal("underline").optional(),
735
+ align: Refused
736
+ });
737
+ /**
738
+ * Free text, as XFDF has it: `color` is the box's fill and the text style lives in
739
+ * `defaultStyle`. A box in the older shape (top-level `fontFamily`, `fontSize`, `align`) is
740
+ * refused rather than silently losing its style; other unknown keys are dropped.
741
+ */
742
+ const FreeTextSchema = Base.extend({
743
+ type: z.literal("freetext"),
744
+ /** The text shown on the page. */
745
+ contents: z.string(),
746
+ /** The box's fill (XFDF `color`). Absent means no fill. */
747
+ color: Hex.optional(),
748
+ /** The border's colour. An extension, not XFDF. */
749
+ borderColor: Hex.optional(),
750
+ /** The border's width in points; 0 draws no border. */
751
+ width: z.number().nonnegative().default(0),
752
+ dashes: DashesSchema,
753
+ /** Points. An extension, not XFDF. */
754
+ cornerRadius: z.number().nonnegative().optional(),
755
+ defaultStyle: FreeTextStyleSchema,
756
+ /**
757
+ * The insets from `rect` to the text box, in points (XFDF `fringe`, PDF `/RD`). Absent means
758
+ * the box is `rect`.
759
+ */
760
+ fringe: FringeSchema.optional(),
761
+ /** A callout's leader line: the tip, an optional bend, and where it meets the box (PDF `/CL`). */
762
+ callout: z.array(PointSchema).min(2).max(3).optional(),
763
+ /** The line ending at a callout's tip (XFDF `head`, PDF `/LE`). Absent means `None`. */
764
+ head: LineEndingSchema.optional(),
765
+ fontFamily: Refused,
766
+ fontSize: Refused,
767
+ align: Refused
768
+ });
769
+ const ShapeFields = {
770
+ width: z.number().nonnegative().default(1),
771
+ dashes: DashesSchema,
772
+ interiorColor: Hex.optional()
773
+ };
774
+ const SquareSchema = Base.extend({
775
+ type: z.literal("square"),
776
+ ...ShapeFields,
777
+ /** The corner radius in points. An extension, not XFDF. */
778
+ cornerRadius: z.number().nonnegative().optional()
779
+ });
780
+ const CircleSchema = Base.extend({
781
+ type: z.literal("circle"),
782
+ ...ShapeFields,
783
+ cornerRadius: Refused
784
+ });
785
+ const ShapeSchema = z.discriminatedUnion("type", [SquareSchema, CircleSchema]);
786
+ const LineSchema = Base.extend({
787
+ type: z.literal("line"),
788
+ start: PointSchema,
789
+ end: PointSchema,
790
+ width: z.number().nonnegative().default(1),
791
+ dashes: DashesSchema,
792
+ head: LineEndingSchema.optional(),
793
+ tail: LineEndingSchema.optional()
794
+ });
795
+ const PolyFields = {
796
+ vertices: z.array(PointSchema).min(2),
797
+ width: z.number().nonnegative().default(1),
798
+ dashes: DashesSchema,
799
+ interiorColor: Hex.optional()
800
+ };
801
+ const PolylineSchema = Base.extend({
802
+ type: z.literal("polyline"),
803
+ ...PolyFields,
804
+ /** The ending at the first vertex. */
805
+ head: LineEndingSchema.optional(),
806
+ /** The ending at the last vertex. */
807
+ tail: LineEndingSchema.optional()
808
+ });
809
+ const PolygonSchema = Base.extend({
810
+ type: z.literal("polygon"),
811
+ ...PolyFields,
812
+ head: Refused,
813
+ tail: Refused
814
+ });
815
+ const PolySchema = z.discriminatedUnion("type", [PolylineSchema, PolygonSchema]);
816
+ const InkShape = Base.extend({
817
+ type: z.literal("ink"),
818
+ inklist: z.array(z.array(PointSchema).min(1)).min(1),
819
+ /** Pen pressure per sample, 0 to 1, shaped like `inklist`. Absent for mouse input. */
820
+ pressure: z.array(z.array(z.number().min(0).max(1))).optional(),
821
+ width: z.number().nonnegative().default(2),
822
+ /** Kept so imported dashed ink round-trips. Inkbar draws ink solid. */
823
+ dashes: DashesSchema
824
+ });
825
+ /** Pressure must have one value per point of each stroke. */
826
+ function checkPressure(a, ctx) {
827
+ if (!a.pressure) return;
828
+ if (!(a.pressure.length === a.inklist.length && a.pressure.every((p, i) => p.length === a.inklist[i]?.length))) ctx.addIssue({
829
+ code: "custom",
830
+ path: ["pressure"],
831
+ message: "pressure must have the same shape as inklist"
832
+ });
833
+ }
834
+ const InkSchema = InkShape.superRefine(checkPressure);
835
+ /** A PNG or JPEG image as a base64 `data:` URL, as XFDF carries a stamp's `<imagedata>`. */
836
+ const IMAGE_DATA_URL = /^data:image\/(png|jpeg);base64,/;
837
+ /**
838
+ * An image on the page (XFDF `stamp`), drawn to fill `rect`. Image and typed signatures are
839
+ * stamps with `subject: 'Signature'`.
840
+ */
841
+ const StampSchema = Base.extend({
842
+ type: z.literal("stamp"),
843
+ /** A PNG or JPEG `data:` URL (XFDF `imagedata`). */
844
+ imagedata: z.string().regex(IMAGE_DATA_URL, "expected a PNG or JPEG data URL"),
845
+ /**
846
+ * Quarter turns, in degrees anticlockwise, the image is turned within `rect` (XFDF
847
+ * `rotation`). Absent means upright in user space.
848
+ */
849
+ rotation: z.union([
850
+ z.literal(0),
851
+ z.literal(90),
852
+ z.literal(180),
853
+ z.literal(270)
854
+ ]).optional()
855
+ });
856
+ /**
857
+ * A loupe (an extension, not XFDF): a circle inscribed in `rect` that shows the page content
858
+ * under its own centre, magnified. `color` and `width` draw its rim.
859
+ */
860
+ const LoupeSchema = Base.extend({
861
+ type: z.literal("loupe"),
862
+ /** How many times larger the content under the centre is drawn. Above 1. */
863
+ magnification: z.number().gt(1).default(2),
864
+ /** The rim's width in points. */
865
+ width: z.number().nonnegative().default(2)
866
+ });
867
+ /**
868
+ * A mask (an extension, not XFDF): dims everything on the page outside `shape` drawn in
869
+ * `rect`, an ellipse inscribed in it or the rectangle itself. `color` is the dimming colour
870
+ * (black by default) and `dim` how strongly it covers. One per page: adding a second replaces
871
+ * the first.
872
+ */
873
+ const MaskSchema = Base.extend({
874
+ type: z.literal("mask"),
875
+ shape: z.enum(["rect", "ellipse"]),
876
+ /** Opacity of the dimming, 0 (none) to 1 (opaque). */
877
+ dim: z.number().min(0).max(1).default(.5)
878
+ });
879
+ const SuggestionSchema = z.object({
880
+ jobId: z.string().optional(),
881
+ confidence: z.number().min(0).max(1),
882
+ reason: z.string().optional(),
883
+ explanation: z.string().optional(),
884
+ recommendation: z.enum([
885
+ "redact",
886
+ "review",
887
+ "keep"
888
+ ]).optional()
889
+ });
890
+ const RedactSchema = Base.extend({
891
+ type: z.literal("redact"),
892
+ /** Present when the mark came from text; absent for an area mark. */
893
+ quads: z.array(QuadSchema).min(1).optional(),
894
+ origin: z.enum(["user", "suggested"]).default("user"),
895
+ suggestion: SuggestionSchema.optional(),
896
+ overlayText: z.string().optional(),
897
+ /** Colour the redaction will be filled with when applied. */
898
+ interiorColor: Hex
899
+ });
900
+ const AnnotationSchema = z.discriminatedUnion("type", [
901
+ TextMarkupSchema,
902
+ NoteSchema,
903
+ FreeTextSchema,
904
+ SquareSchema,
905
+ CircleSchema,
906
+ LineSchema,
907
+ PolylineSchema,
908
+ PolygonSchema,
909
+ InkSchema,
910
+ StampSchema,
911
+ LoupeSchema,
912
+ MaskSchema,
913
+ RedactSchema
914
+ ]);
915
+ /** The viewer's own state on an annotation, left out of exports. */
916
+ const VIEWER_STATE = {
917
+ source: true,
918
+ locked: true
919
+ };
920
+ /** One exported annotation: the stored annotation without its viewer state. */
921
+ const ExportedAnnotationSchema = z.discriminatedUnion("type", [
922
+ TextMarkupSchema.omit(VIEWER_STATE),
923
+ NoteSchema.omit(VIEWER_STATE),
924
+ FreeTextSchema.omit(VIEWER_STATE),
925
+ SquareSchema.omit(VIEWER_STATE),
926
+ CircleSchema.omit(VIEWER_STATE),
927
+ LineSchema.omit(VIEWER_STATE),
928
+ PolylineSchema.omit(VIEWER_STATE),
929
+ PolygonSchema.omit(VIEWER_STATE),
930
+ InkShape.omit(VIEWER_STATE).superRefine(checkPressure),
931
+ StampSchema.omit(VIEWER_STATE),
932
+ LoupeSchema.omit(VIEWER_STATE),
933
+ MaskSchema.omit(VIEWER_STATE),
934
+ RedactSchema.omit(VIEWER_STATE)
935
+ ]);
936
+ const AnnotationDocumentSchema = z.object({
937
+ format: z.literal(ANNOTATION_FORMAT),
938
+ version: z.literal(1),
939
+ documentKey: z.string().optional(),
940
+ /** Validated item by item on import so unknown types can be preserved. */
941
+ annotations: z.array(z.unknown())
942
+ });
943
+ function confidenceBucket(confidence) {
944
+ if (confidence < .5) return "low";
945
+ if (confidence < .8) return "medium";
946
+ return "high";
947
+ }
948
+ //#endregion
949
+ //#region src/model/annotations/embedded.ts
950
+ const SUPPORTED_SUBTYPES = /* @__PURE__ */ new Set([
951
+ "Highlight",
952
+ "Underline",
953
+ "StrikeOut",
954
+ "Squiggly",
955
+ "Text",
956
+ "FreeText",
957
+ "Square",
958
+ "Circle",
959
+ "Line",
960
+ "Polygon",
961
+ "PolyLine",
962
+ "Ink",
963
+ "Redact"
964
+ ]);
965
+ function pdfColorToHex(c, fallback) {
966
+ if (!c || c.length < 3) return fallback;
967
+ return `#${[
968
+ c[0],
969
+ c[1],
970
+ c[2]
971
+ ].map((n) => Math.round(n).toString(16).padStart(2, "0")).join("")}`.toUpperCase();
972
+ }
973
+ /** PDF.js hands back `rect` already in user space, but not always ordered; normalise with min/max. */
974
+ function rectFromPdf(r) {
975
+ return rectFromPoints({
976
+ x: r[0],
977
+ y: r[1]
978
+ }, {
979
+ x: r[2],
980
+ y: r[3]
981
+ });
982
+ }
983
+ /** A PDF name exactly as PDF.js gives it (names are case-sensitive), or undefined if invalid. */
984
+ function pdfName(raw) {
985
+ return raw !== void 0 && PDF_NAME.test(raw) ? raw : void 0;
986
+ }
987
+ /** `head` and `tail` from a Line's or PolyLine's `/LE`, left out when both are `None`. */
988
+ function lineEndingsOf(raw) {
989
+ const endings = raw?.map((e) => pdfName(e) ?? "None");
990
+ return endings && endings.length === 2 && endings.some((e) => e !== "None") ? {
991
+ head: endings[0],
992
+ tail: endings[1]
993
+ } : {};
994
+ }
995
+ /**
996
+ * Imported ids are `pdf:<page>:<pdfjsId>` (page is 0-based, pdfjsId is the annotation's object
997
+ * reference such as `12R`). They are stable across opens of the same file, and `inReplyTo`
998
+ * uses the same scheme so threads resolve.
999
+ */
1000
+ function importedId(page, pdfjsId) {
1001
+ return `pdf:${page}:${pdfjsId}`;
1002
+ }
1003
+ function importEmbeddedPage(page, raw, importedAt) {
1004
+ const counts = {};
1005
+ const annotations = [];
1006
+ for (const data of raw) {
1007
+ counts[data.subtype] = (counts[data.subtype] ?? 0) + 1;
1008
+ if (!SUPPORTED_SUBTYPES.has(data.subtype) || data.hidden || data.noView) continue;
1009
+ const converted = convert(page, data, importedAt);
1010
+ if (converted) annotations.push(converted);
1011
+ }
1012
+ return {
1013
+ annotations,
1014
+ counts
1015
+ };
1016
+ }
1017
+ function summarise(perPage) {
1018
+ const totals = /* @__PURE__ */ new Map();
1019
+ for (const counts of perPage) for (const [k, v] of Object.entries(counts)) totals.set(k, (totals.get(k) ?? 0) + v);
1020
+ return [...totals.entries()].map(([subtype, count]) => ({
1021
+ subtype,
1022
+ count,
1023
+ supported: SUPPORTED_SUBTYPES.has(subtype)
1024
+ })).sort((a, b) => a.subtype < b.subtype ? -1 : a.subtype > b.subtype ? 1 : 0);
1025
+ }
1026
+ function convert(page, d, importedAt) {
1027
+ const created = parsePdfDate(d.creationDate, parsePdfDate(d.modificationDate, importedAt));
1028
+ const author = d.titleObj?.str;
1029
+ const contents = d.contentsObj?.str;
1030
+ const stroke = d.borderStyle?.width ?? 1;
1031
+ const quads = d.quadPoints ? quadsFromFlat(d.quadPoints) : [];
1032
+ const optional = (v) => v !== void 0 && v !== "";
1033
+ const withColor = (type, source = d.color) => pdfColorToHex(source, staticDefaults.color(type));
1034
+ const intent = pdfName(d.it);
1035
+ const base = (type, color = withColor(type)) => ({
1036
+ id: importedId(page, d.id),
1037
+ page,
1038
+ rect: rectFromPdf(d.rect),
1039
+ color,
1040
+ opacity: d.opacity ?? 1,
1041
+ ...optional(author) ? { author } : {},
1042
+ ...optional(contents) ? { contents } : {},
1043
+ ...d.inReplyTo ? { inReplyTo: importedId(page, d.inReplyTo) } : {},
1044
+ ...intent !== void 0 ? { intent } : {},
1045
+ createdAt: created,
1046
+ modifiedAt: parsePdfDate(d.modificationDate, created),
1047
+ source: "pdf",
1048
+ locked: true
1049
+ });
1050
+ const fillOf = (c) => c && c.length >= 3 ? { interiorColor: pdfColorToHex(c, "#FFFFFF") } : {};
1051
+ let candidate;
1052
+ switch (d.subtype) {
1053
+ case "Highlight":
1054
+ case "Underline":
1055
+ case "StrikeOut":
1056
+ case "Squiggly": {
1057
+ if (quads.length === 0) return void 0;
1058
+ const type = d.subtype === "StrikeOut" ? "strikeout" : d.subtype.toLowerCase();
1059
+ candidate = {
1060
+ ...base(type),
1061
+ type,
1062
+ quads
1063
+ };
1064
+ break;
1065
+ }
1066
+ case "Text": {
1067
+ const icon = d.name === "NoIcon" ? void 0 : pdfName(d.name);
1068
+ candidate = {
1069
+ ...base("text"),
1070
+ type: "text",
1071
+ ...icon !== void 0 ? { icon } : {}
1072
+ };
1073
+ break;
1074
+ }
1075
+ case "FreeText": {
1076
+ const da = d.defaultAppearanceData;
1077
+ const { color: _stroke, ...rest } = base("freetext");
1078
+ candidate = {
1079
+ ...rest,
1080
+ ...d.color && d.color.length >= 3 ? { color: pdfColorToHex(d.color, "#FFFFFF") } : {},
1081
+ type: "freetext",
1082
+ contents: contents ?? "",
1083
+ width: d.borderStyle?.width ?? 0,
1084
+ defaultStyle: {
1085
+ color: pdfColorToHex(da?.fontColor, staticDefaults.color("freetext")),
1086
+ ...da && da.fontSize > 0 ? { fontSize: da.fontSize } : {}
1087
+ }
1088
+ };
1089
+ break;
1090
+ }
1091
+ case "Square":
1092
+ case "Circle": {
1093
+ const type = d.subtype.toLowerCase();
1094
+ candidate = {
1095
+ ...base(type),
1096
+ type,
1097
+ width: stroke,
1098
+ ...fillOf(d.interiorColor)
1099
+ };
1100
+ break;
1101
+ }
1102
+ case "Line": {
1103
+ const l = d.lineCoordinates ?? [
1104
+ d.rect[0],
1105
+ d.rect[1],
1106
+ d.rect[2],
1107
+ d.rect[3]
1108
+ ];
1109
+ candidate = {
1110
+ ...base("line"),
1111
+ type: "line",
1112
+ start: {
1113
+ x: l[0],
1114
+ y: l[1]
1115
+ },
1116
+ end: {
1117
+ x: l[2],
1118
+ y: l[3]
1119
+ },
1120
+ width: stroke,
1121
+ ...lineEndingsOf(d.lineEndings)
1122
+ };
1123
+ break;
1124
+ }
1125
+ case "Polygon":
1126
+ case "PolyLine": {
1127
+ const type = d.subtype === "Polygon" ? "polygon" : "polyline";
1128
+ const vertices = d.vertices ? pointsFromFlat(d.vertices) : [];
1129
+ if (vertices.length < 2) return void 0;
1130
+ candidate = {
1131
+ ...base(type),
1132
+ type,
1133
+ vertices,
1134
+ width: stroke,
1135
+ ...fillOf(d.interiorColor),
1136
+ ...type === "polyline" ? lineEndingsOf(d.lineEndings) : {}
1137
+ };
1138
+ break;
1139
+ }
1140
+ case "Ink": {
1141
+ const inklist = (d.inkLists ?? []).map((p) => pointsFromFlat(p)).filter((p) => p.length > 0);
1142
+ if (inklist.length === 0) return void 0;
1143
+ candidate = {
1144
+ ...base("ink"),
1145
+ type: "ink",
1146
+ inklist,
1147
+ width: stroke
1148
+ };
1149
+ break;
1150
+ }
1151
+ case "Redact":
1152
+ candidate = {
1153
+ ...base("redact"),
1154
+ type: "redact",
1155
+ origin: "user",
1156
+ interiorColor: pdfColorToHex(d.interiorColor, staticDefaults.fill()),
1157
+ ...quads.length > 0 ? { quads } : {}
1158
+ };
1159
+ break;
1160
+ default: return;
1161
+ }
1162
+ const parsed = AnnotationSchema.safeParse(candidate);
1163
+ return parsed.success ? parsed.data : void 0;
1164
+ }
1165
+ //#endregion
1166
+ //#region src/model/env.ts
1167
+ /** True only when the build or runtime says production; browsers without `process` count as dev. */
1168
+ function isProduction() {
1169
+ try {
1170
+ return process.env.NODE_ENV === "production";
1171
+ } catch {
1172
+ return false;
1173
+ }
1174
+ }
1175
+ //#endregion
1176
+ //#region src/model/annotations/history.ts
1177
+ /**
1178
+ * Snapshot-based undo and redo over an uncontrolled store.
1179
+ *
1180
+ * In controlled mode the host owns the list, so history is the host's concern (the Vue layer
1181
+ * offers `useHistory`). There `createHistory` returns an inert History: `canUndo` and `canRedo`
1182
+ * stay false, `undo` and `redo` do nothing, and nothing is recorded.
1183
+ */
1184
+ function createHistory(store, opts = {}) {
1185
+ const canUndo = writable(false);
1186
+ const canRedo = writable(false);
1187
+ if (store.mode === "controlled") return {
1188
+ canUndo: readonly(canUndo),
1189
+ canRedo: readonly(canRedo),
1190
+ undo() {},
1191
+ redo() {},
1192
+ clear() {},
1193
+ batch(fn) {
1194
+ fn();
1195
+ },
1196
+ destroy() {}
1197
+ };
1198
+ const limit = opts.limit ?? 200;
1199
+ const undoStack = [];
1200
+ const redoStack = [];
1201
+ let previous = store.list.get();
1202
+ let replaying = false;
1203
+ /** Open batch depth; while above zero, changes update `previous` but push no entry. */
1204
+ let depth = 0;
1205
+ /** The list when the outermost batch opened (or was restarted by a replace). */
1206
+ let batchStart = null;
1207
+ const sync = () => {
1208
+ canUndo.set(undoStack.length > 0);
1209
+ canRedo.set(redoStack.length > 0);
1210
+ };
1211
+ let destroyed = false;
1212
+ const unsubscribe = store.on("change", (change) => {
1213
+ const current = store.list.get();
1214
+ if (replaying || change.kind === "replace" && change.reason === "history") {
1215
+ previous = current;
1216
+ return;
1217
+ }
1218
+ if (change.kind === "replace") {
1219
+ undoStack.length = 0;
1220
+ redoStack.length = 0;
1221
+ previous = current;
1222
+ if (depth > 0) batchStart = current;
1223
+ sync();
1224
+ return;
1225
+ }
1226
+ if (depth > 0) {
1227
+ previous = current;
1228
+ return;
1229
+ }
1230
+ undoStack.push({
1231
+ before: previous,
1232
+ after: current
1233
+ });
1234
+ if (undoStack.length > limit) undoStack.shift();
1235
+ redoStack.length = 0;
1236
+ previous = current;
1237
+ sync();
1238
+ });
1239
+ const apply = (list) => {
1240
+ replaying = true;
1241
+ try {
1242
+ store.replaceAll([...list], "history");
1243
+ } finally {
1244
+ replaying = false;
1245
+ }
1246
+ };
1247
+ return {
1248
+ canUndo: readonly(canUndo),
1249
+ canRedo: readonly(canRedo),
1250
+ undo() {
1251
+ const entry = undoStack.pop();
1252
+ if (destroyed || !entry) return;
1253
+ redoStack.push(entry);
1254
+ apply(entry.before);
1255
+ sync();
1256
+ },
1257
+ redo() {
1258
+ const entry = redoStack.pop();
1259
+ if (destroyed || !entry) return;
1260
+ undoStack.push(entry);
1261
+ apply(entry.after);
1262
+ sync();
1263
+ },
1264
+ batch(fn) {
1265
+ if (destroyed) {
1266
+ fn();
1267
+ return;
1268
+ }
1269
+ if (depth++ === 0) batchStart = store.list.get();
1270
+ try {
1271
+ const result = fn();
1272
+ if (result !== null && typeof result === "object" && typeof result.then === "function" && !isProduction()) console.warn("[inkbar] history.batch(fn): fn returned a promise. Changes after its first await are not part of the batch.");
1273
+ } finally {
1274
+ if (--depth === 0 && !destroyed) {
1275
+ const before = batchStart;
1276
+ batchStart = null;
1277
+ const after = store.list.get();
1278
+ if (before && !sameAnnotations(before, after)) {
1279
+ undoStack.push({
1280
+ before,
1281
+ after
1282
+ });
1283
+ if (undoStack.length > limit) undoStack.shift();
1284
+ redoStack.length = 0;
1285
+ sync();
1286
+ }
1287
+ }
1288
+ }
1289
+ },
1290
+ destroy() {
1291
+ destroyed = true;
1292
+ batchStart = null;
1293
+ unsubscribe();
1294
+ undoStack.length = 0;
1295
+ redoStack.length = 0;
1296
+ sync();
1297
+ },
1298
+ clear() {
1299
+ undoStack.length = 0;
1300
+ redoStack.length = 0;
1301
+ previous = store.list.get();
1302
+ sync();
1303
+ }
1304
+ };
1305
+ }
1306
+ /** The same annotation objects in the same order. */
1307
+ function sameAnnotations(a, b) {
1308
+ return a === b || a.length === b.length && a.every((x, i) => x === b[i]);
1309
+ }
1310
+ //#endregion
1311
+ //#region src/model/annotations/json.ts
1312
+ const KNOWN_TYPES = new Set(ExportedAnnotationSchema.options.flatMap((o) => [...o.shape.type._zod.values]));
1313
+ /**
1314
+ * Session annotations plus any preserved foreign items. Embedded (`source: 'pdf'`) ones stay in
1315
+ * the file. `source` and `locked` are viewer state and are left out.
1316
+ *
1317
+ * The result is a JSON copy (`JSON.parse(JSON.stringify(...))`), the same data a serialised
1318
+ * export would carry: editing it never touches the store, and values JSON cannot hold, such as
1319
+ * functions or `undefined` inside `custom`, are left out exactly as `JSON.stringify` would.
1320
+ *
1321
+ * Without foreign items the result validates against this version's `schema.json`. With them it
1322
+ * validates only against the newer schema that produced them, since this version's schema
1323
+ * describes only the types it knows.
1324
+ */
1325
+ function exportAnnotations(store, preserved = [], documentKey) {
1326
+ const session = store.list.get().filter((a) => a.source === "session").map(({ source: _source, locked: _locked, ...rest }) => rest);
1327
+ return {
1328
+ format: ANNOTATION_FORMAT,
1329
+ version: 1,
1330
+ ...documentKey === void 0 ? {} : { documentKey },
1331
+ annotations: JSON.parse(JSON.stringify([...session, ...preserved]))
1332
+ };
1333
+ }
1334
+ /**
1335
+ * Validates the envelope (throws a TypeError when it is not an inkbar/annotations v1 document),
1336
+ * then each item on its own. Embedded annotations are never touched; imported items become
1337
+ * session annotations.
1338
+ */
1339
+ function importAnnotations(store, data, opts) {
1340
+ const plan = planImport(store, data, opts);
1341
+ plan.apply();
1342
+ return plan.result;
1343
+ }
1344
+ /**
1345
+ * @internal Validation half of `importAnnotations`, so the document can record foreign items
1346
+ * before the store publishes the change.
1347
+ *
1348
+ * Ids are unique across the payload: the first item with an id claims it, and later ones (known
1349
+ * or foreign) are reported in `errors`, even when the first was itself rejected. An id that
1350
+ * matches an embedded annotation is rejected for known and foreign items alike. In `merge` mode an incoming item replaces whatever session
1351
+ * annotation has its id, whether the incoming item is known or foreign.
1352
+ */
1353
+ function planImport(store, data, opts) {
1354
+ const raw = typeof data === "string" ? JSON.parse(data) : data;
1355
+ const envelope = AnnotationDocumentSchema.safeParse(raw);
1356
+ if (!envelope.success) throw new TypeError(`Expected an ${ANNOTATION_FORMAT} v1 document: ${envelope.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")}`);
1357
+ const embeddedIds = new Set(store.list.get().filter((a) => a.source === "pdf").map((a) => a.id));
1358
+ const result = {
1359
+ imported: 0,
1360
+ unknown: [],
1361
+ errors: []
1362
+ };
1363
+ const incoming = [];
1364
+ /** id -> index of the first item that used it, whether that item was accepted or not. */
1365
+ const seen = /* @__PURE__ */ new Map();
1366
+ /** Ids the import actually brings in. */
1367
+ const accepted = /* @__PURE__ */ new Set();
1368
+ /**
1369
+ * Reserves `id` for the item at `index`. Later items with the same id are duplicates even
1370
+ * when this one is rejected for reusing an embedded id.
1371
+ */
1372
+ const claim = (id, index) => {
1373
+ const first = seen.get(id);
1374
+ if (first !== void 0) {
1375
+ result.errors.push({
1376
+ index,
1377
+ issues: [`id: duplicate id "${id}", already used by item ${first}`]
1378
+ });
1379
+ return false;
1380
+ }
1381
+ seen.set(id, index);
1382
+ if (embeddedIds.has(id)) {
1383
+ result.errors.push({
1384
+ index,
1385
+ issues: ["id: matches an annotation embedded in the PDF, which import never replaces"]
1386
+ });
1387
+ return false;
1388
+ }
1389
+ accepted.add(id);
1390
+ return true;
1391
+ };
1392
+ envelope.data.annotations.forEach((item, index) => {
1393
+ const type = item?.type;
1394
+ if (typeof type === "string" && !KNOWN_TYPES.has(type)) {
1395
+ if (!isForeign(item)) result.errors.push({
1396
+ index,
1397
+ issues: [`type: unknown type "${type}" needs a string id and a numeric page to be preserved`]
1398
+ });
1399
+ else if (claim(item.id, index)) result.unknown.push(item);
1400
+ return;
1401
+ }
1402
+ const parsed = ExportedAnnotationSchema.safeParse(item);
1403
+ if (!parsed.success) {
1404
+ result.errors.push({
1405
+ index,
1406
+ issues: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`)
1407
+ });
1408
+ return;
1409
+ }
1410
+ if (!claim(parsed.data.id, index)) return;
1411
+ incoming.push({
1412
+ ...parsed.data,
1413
+ source: "session"
1414
+ });
1415
+ result.imported++;
1416
+ });
1417
+ if (result.unknown.length > 0 && !isProduction()) {
1418
+ const types = [...new Set(result.unknown.map((u) => u.type))];
1419
+ console.warn(`[inkbar] importAnnotations kept ${result.unknown.length} annotation(s) of unknown type (${types.join(", ")}). They are not shown, and exportAnnotations writes them back out.`);
1420
+ }
1421
+ const ids = accepted;
1422
+ return {
1423
+ result,
1424
+ ids,
1425
+ apply() {
1426
+ const current = store.list.get();
1427
+ const embedded = current.filter((a) => a.source === "pdf");
1428
+ if (opts.mode === "replace") {
1429
+ store.replaceAll([...embedded, ...incoming], "import");
1430
+ return;
1431
+ }
1432
+ const byId = new Map(current.filter((a) => a.source === "session" && !ids.has(a.id)).map((a) => [a.id, a]));
1433
+ for (const a of incoming) byId.set(a.id, a);
1434
+ store.replaceAll([...embedded, ...byId.values()], "import");
1435
+ }
1436
+ };
1437
+ }
1438
+ function isForeign(item) {
1439
+ if (typeof item !== "object" || item === null || Array.isArray(item)) return false;
1440
+ const { type, id, page } = item;
1441
+ return typeof type === "string" && typeof id === "string" && typeof page === "number";
1442
+ }
1443
+ //#endregion
1444
+ //#region src/model/annotations/store.ts
1445
+ /** Keys a locked annotation refuses to change. */
1446
+ const LOCKED_KEYS = /* @__PURE__ */ new Set([
1447
+ "page",
1448
+ "rect",
1449
+ "quads",
1450
+ "inklist",
1451
+ "start",
1452
+ "end",
1453
+ "vertices",
1454
+ "callout",
1455
+ "contents",
1456
+ "imagedata",
1457
+ "rotation"
1458
+ ]);
1459
+ function keepKey(target, from, key) {
1460
+ if (Object.prototype.hasOwnProperty.call(from, key)) target[key] = from[key];
1461
+ else delete target[key];
1462
+ }
1463
+ /** `proposed` as a replacement for embedded `current`, with what the file owns kept from `current`. */
1464
+ function guardEmbedded(current, proposed) {
1465
+ if (proposed === current) return current;
1466
+ if (proposed.type !== current.type) return current;
1467
+ const candidate = {
1468
+ ...proposed,
1469
+ id: current.id,
1470
+ createdAt: current.createdAt,
1471
+ source: "pdf"
1472
+ };
1473
+ keepKey(candidate, current, "locked");
1474
+ if (current.locked) for (const key of LOCKED_KEYS) keepKey(candidate, current, key);
1475
+ const parsed = AnnotationSchema.safeParse(candidate);
1476
+ return parsed.success ? parsed.data : current;
1477
+ }
1478
+ function deriveRect(input) {
1479
+ switch (input.type) {
1480
+ case "highlight":
1481
+ case "underline":
1482
+ case "strikeout":
1483
+ case "squiggly": return unionRects(input.quads.map(rectFromQuad));
1484
+ case "redact":
1485
+ if (input.quads) return unionRects(input.quads.map(rectFromQuad));
1486
+ break;
1487
+ case "ink": {
1488
+ const pad = (input.width ?? 2) / 2;
1489
+ const r = bounds(input.inklist.flat());
1490
+ return {
1491
+ x: r.x - pad,
1492
+ y: r.y - pad,
1493
+ width: r.width + pad * 2,
1494
+ height: r.height + pad * 2
1495
+ };
1496
+ }
1497
+ case "line": return bounds([input.start, input.end]);
1498
+ case "polyline":
1499
+ case "polygon": return bounds(input.vertices);
1500
+ }
1501
+ if (input.rect) return input.rect;
1502
+ throw new TypeError(`rect is required for ${input.type}`);
1503
+ }
1504
+ function bounds(pts) {
1505
+ const xs = pts.map((p) => p.x);
1506
+ const ys = pts.map((p) => p.y);
1507
+ const x = Math.min(...xs);
1508
+ const y = Math.min(...ys);
1509
+ return {
1510
+ x,
1511
+ y,
1512
+ width: Math.max(...xs) - x,
1513
+ height: Math.max(...ys) - y
1514
+ };
1515
+ }
1516
+ /** `o` without its `undefined` values. */
1517
+ function withoutUndefined(o) {
1518
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
1519
+ }
1520
+ /**
1521
+ * A `defaultStyle` patch merges one level deep into the current one, so changing the weight
1522
+ * keeps the font and size. An `undefined` value removes its key.
1523
+ */
1524
+ function mergedStyle(before, patch) {
1525
+ const next = patch.defaultStyle;
1526
+ if (before.type !== "freetext" || next === void 0 || next === null) return {};
1527
+ return { defaultStyle: withoutUndefined({
1528
+ ...before.defaultStyle,
1529
+ ...next
1530
+ }) };
1531
+ }
1532
+ /** Pending-map key; only annotation changes are tracked, and the prefix keeps ids apart from any other slot. */
1533
+ function changeKey(change) {
1534
+ return `annotation:${change.kind === "update" ? change.id : change.annotation.id}`;
1535
+ }
1536
+ /** Structural equality for plain JSON values, ignoring `modifiedAt` at the top level. */
1537
+ function sameIgnoringModifiedAt(a, b) {
1538
+ const { modifiedAt: _a, ...restA } = a;
1539
+ const { modifiedAt: _b, ...restB } = b;
1540
+ return deepEqual(restA, restB);
1541
+ }
1542
+ function deepEqual(a, b) {
1543
+ if (Object.is(a, b)) return true;
1544
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
1545
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
1546
+ const ka = Object.keys(a);
1547
+ const kb = Object.keys(b);
1548
+ if (ka.length !== kb.length) return false;
1549
+ return ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
1550
+ }
1551
+ function isApplied(change, current) {
1552
+ switch (change.kind) {
1553
+ case "add": return current.some((a) => a.id === change.annotation.id);
1554
+ case "remove": return !current.some((a) => a.id === change.annotation.id);
1555
+ case "update": {
1556
+ const mine = current.find((a) => a.id === change.id);
1557
+ if (!mine) return false;
1558
+ return mine === change.after || sameIgnoringModifiedAt(mine, change.after);
1559
+ }
1560
+ case "replace": return true;
1561
+ }
1562
+ }
1563
+ function createAnnotationStore(opts) {
1564
+ const now = opts.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
1565
+ const nextId = opts.id ?? (() => v7());
1566
+ const list = writable([...opts.mode.initial ?? []]);
1567
+ const selection = writable([]);
1568
+ const emitter = new Emitter();
1569
+ const controlled = opts.mode.mode === "controlled" ? opts.mode : void 0;
1570
+ const pending = /* @__PURE__ */ new Map();
1571
+ /**
1572
+ * Controlled mode: the list as the store last proposed it, embedded items included. Later
1573
+ * proposals build on it, so several mutations in a row (one highlight per page, a bulk
1574
+ * remove, add then select) all reach the host. It resets to the applied list when the host
1575
+ * pushes a value or a pending change's check fires without one.
1576
+ */
1577
+ let proposed;
1578
+ let destroyed = false;
1579
+ /** What mutations build on: the pending proposal in controlled mode, else the list. */
1580
+ const basis = () => proposed ?? list.get();
1581
+ const findIn = (items, id) => items.find((a) => a.id === id);
1582
+ function completeInput(input) {
1583
+ const ts = now();
1584
+ const candidate = {
1585
+ ...input,
1586
+ id: input.id ?? nextId(),
1587
+ rect: input.rect ?? deriveRect(input),
1588
+ color: input.color ?? opts.defaults.color(input.type),
1589
+ opacity: input.opacity ?? opts.defaults.opacity(input.type),
1590
+ createdAt: ts,
1591
+ modifiedAt: ts,
1592
+ source: "session"
1593
+ };
1594
+ if (input.type === "freetext") {
1595
+ if (input.color === void 0) delete candidate.color;
1596
+ candidate.defaultStyle = {
1597
+ color: opts.defaults.color("freetext"),
1598
+ ...withoutUndefined(input.defaultStyle ?? {})
1599
+ };
1600
+ }
1601
+ if (input.type === "redact") {
1602
+ if (input.interiorColor === void 0) candidate.interiorColor = opts.defaults.fill();
1603
+ if (input.origin === "suggested" && input.suggestion && input.color === void 0) candidate.color = opts.defaults.suggestion(confidenceBucket(input.suggestion.confidence));
1604
+ }
1605
+ return AnnotationSchema.parse(candidate);
1606
+ }
1607
+ function clearPending(key) {
1608
+ const entry = pending.get(key);
1609
+ if (!entry) return;
1610
+ clearTimeout(entry.timer);
1611
+ pending.delete(key);
1612
+ }
1613
+ function warnIfIgnored(key) {
1614
+ const entry = pending.get(key);
1615
+ if (!entry) return;
1616
+ pending.delete(key);
1617
+ if (pending.size === 0) proposed = void 0;
1618
+ if (isApplied(entry.change, list.get()) || isProduction()) return;
1619
+ console.warn(`[inkbar] ControlledMutationIgnored: the host did not apply a ${entry.change.kind} for annotation ${entry.id}. In controlled mode, pass the list from onChange back into the store.`);
1620
+ }
1621
+ function commit(next, change) {
1622
+ if (controlled) {
1623
+ if (change.kind !== "replace") {
1624
+ const key = changeKey(change);
1625
+ clearPending(key);
1626
+ const entry = {
1627
+ id: change.kind === "update" ? change.id : change.annotation.id,
1628
+ change,
1629
+ timer: setTimeout(() => {
1630
+ entry.timer = setTimeout(() => {
1631
+ warnIfIgnored(key);
1632
+ }, 0);
1633
+ }, 0)
1634
+ };
1635
+ pending.set(key, entry);
1636
+ }
1637
+ proposed = change.kind === "replace" ? [...list.get().filter((a) => a.source === "pdf"), ...next.filter((a) => a.source !== "pdf")] : next;
1638
+ controlled.onChange(next.filter((a) => a.source !== "pdf"), change);
1639
+ return;
1640
+ }
1641
+ list.set(next);
1642
+ emitter.emit("change", change);
1643
+ }
1644
+ /**
1645
+ * Uncontrolled `replaceAll` cannot drop or forge embedded annotations: every current embedded
1646
+ * item stays (taking the list's version of it, guarded like `update`, when the list has one),
1647
+ * and items claiming `source: 'pdf'` that the store does not hold are dropped. History
1648
+ * snapshots contain the embedded items, so undo and redo of their edits still work.
1649
+ */
1650
+ function withEmbedded(proposed) {
1651
+ const current = new Map(list.get().filter((a) => a.source === "pdf").map((a) => [a.id, a]));
1652
+ const seen = /* @__PURE__ */ new Set();
1653
+ const out = [];
1654
+ for (const a of proposed) {
1655
+ const mine = current.get(a.id);
1656
+ if (mine) {
1657
+ if (!seen.has(a.id)) out.push(guardEmbedded(mine, a));
1658
+ seen.add(a.id);
1659
+ } else if (a.source !== "pdf") out.push(a);
1660
+ }
1661
+ return [...[...current.values()].filter((a) => !seen.has(a.id)), ...out];
1662
+ }
1663
+ function pruneSelection(next) {
1664
+ const known = new Set(next.map((a) => a.id));
1665
+ const current = selection.get();
1666
+ if (current.every((id) => known.has(id))) return;
1667
+ selection.set(current.filter((id) => known.has(id)));
1668
+ }
1669
+ return {
1670
+ mode: opts.mode.mode,
1671
+ list: readonly(list),
1672
+ selection: readonly(selection),
1673
+ defaults: opts.defaults,
1674
+ get: (id) => list.get().find((a) => a.id === id),
1675
+ _getProposed: (id) => findIn(basis(), id),
1676
+ byPage: (page) => list.get().filter((a) => a.page === page),
1677
+ completeInput,
1678
+ add(input) {
1679
+ const a = completeInput(input);
1680
+ if (findIn(basis(), a.id)) throw new Error(`An annotation with id ${a.id} already exists`);
1681
+ if (destroyed) return a;
1682
+ const replaced = a.type === "mask" ? basis().filter((x) => x.type === "mask" && x.page === a.page && x.source !== "pdf") : [];
1683
+ const gone = new Set(replaced.map((x) => x.id));
1684
+ for (const x of replaced) clearPending(changeKey({
1685
+ kind: "add",
1686
+ annotation: x
1687
+ }));
1688
+ commit([...basis().filter((x) => !gone.has(x.id)), a], {
1689
+ kind: "add",
1690
+ annotation: a
1691
+ });
1692
+ if (!controlled && gone.size > 0) pruneSelection(list.get());
1693
+ return a;
1694
+ },
1695
+ update(id, patch) {
1696
+ const before = findIn(basis(), id);
1697
+ if (destroyed || !before) return void 0;
1698
+ if (before.locked && Object.keys(patch).some((k) => LOCKED_KEYS.has(k))) return void 0;
1699
+ const candidate = {
1700
+ ...before,
1701
+ ...patch,
1702
+ ...mergedStyle(before, patch),
1703
+ id: before.id,
1704
+ type: before.type,
1705
+ createdAt: before.createdAt,
1706
+ source: before.source,
1707
+ modifiedAt: now()
1708
+ };
1709
+ if (before.source === "pdf") keepKey(candidate, before, "locked");
1710
+ const after = AnnotationSchema.parse(candidate);
1711
+ const swap = (items) => items.map((a) => a.id === id ? after : a);
1712
+ const next = swap(basis());
1713
+ const change = {
1714
+ kind: "update",
1715
+ id,
1716
+ before,
1717
+ after
1718
+ };
1719
+ if (controlled && before.source === "pdf") {
1720
+ list.set(swap(list.get()));
1721
+ if (proposed) proposed = next;
1722
+ emitter.emit("change", change);
1723
+ } else commit(next, change);
1724
+ return after;
1725
+ },
1726
+ remove(id) {
1727
+ const items = basis();
1728
+ const target = findIn(items, id);
1729
+ if (destroyed || !target || target.locked) return false;
1730
+ const doomed = /* @__PURE__ */ new Set([id]);
1731
+ let grew = true;
1732
+ while (grew) {
1733
+ grew = false;
1734
+ for (const a of items) if (a.inReplyTo !== void 0 && doomed.has(a.inReplyTo) && !doomed.has(a.id)) {
1735
+ doomed.add(a.id);
1736
+ grew = true;
1737
+ }
1738
+ }
1739
+ const next = items.filter((a) => !doomed.has(a.id));
1740
+ commit(next, {
1741
+ kind: "remove",
1742
+ annotation: target,
1743
+ removed: [target, ...items.filter((a) => a.id !== id && doomed.has(a.id))]
1744
+ });
1745
+ if (!controlled) pruneSelection(next);
1746
+ return true;
1747
+ },
1748
+ select(ids) {
1749
+ const known = new Set(basis().map((a) => a.id));
1750
+ selection.set(ids.filter((id) => known.has(id)));
1751
+ },
1752
+ replaceAll(list, reason) {
1753
+ if (destroyed) return;
1754
+ const next = controlled ? [...list] : withEmbedded(list);
1755
+ commit(next, {
1756
+ kind: "replace",
1757
+ reason
1758
+ });
1759
+ if (!controlled) pruneSelection(next);
1760
+ },
1761
+ setControlledValue(value) {
1762
+ if (!controlled) throw new TypeError("setControlledValue is only valid in controlled mode");
1763
+ if (destroyed) return;
1764
+ const embedded = list.get().filter((a) => a.source === "pdf");
1765
+ const embeddedIds = new Set(embedded.map((a) => a.id));
1766
+ const next = [...embedded, ...value.filter((a) => !embeddedIds.has(a.id))];
1767
+ list.set(next);
1768
+ proposed = void 0;
1769
+ for (const [key, entry] of [...pending]) if (isApplied(entry.change, next)) clearPending(key);
1770
+ pruneSelection(next);
1771
+ emitter.emit("change", {
1772
+ kind: "replace",
1773
+ reason: "sync"
1774
+ });
1775
+ },
1776
+ _setEmbedded(items) {
1777
+ if (destroyed) return;
1778
+ const ids = new Set(items.map((a) => a.id));
1779
+ const next = [...items, ...list.get().filter((a) => a.source !== "pdf" && !ids.has(a.id))];
1780
+ proposed = void 0;
1781
+ list.set(next);
1782
+ pruneSelection(next);
1783
+ emitter.emit("change", {
1784
+ kind: "replace",
1785
+ reason: "import"
1786
+ });
1787
+ },
1788
+ on: (event, fn) => emitter.on(event, fn),
1789
+ destroy() {
1790
+ destroyed = true;
1791
+ proposed = void 0;
1792
+ for (const key of [...pending.keys()]) clearPending(key);
1793
+ emitter.clear();
1794
+ }
1795
+ };
1796
+ }
1797
+ //#endregion
1798
+ //#region src/model/page-cache.ts
1799
+ function createPageCache(fetch) {
1800
+ const cache = /* @__PURE__ */ new Map();
1801
+ return {
1802
+ get(index) {
1803
+ const cached = cache.get(index);
1804
+ if (cached) return cached;
1805
+ const fetched = fetch(index);
1806
+ cache.set(index, fetched);
1807
+ fetched.catch(() => {
1808
+ if (cache.get(index) === fetched) cache.delete(index);
1809
+ });
1810
+ return fetched;
1811
+ },
1812
+ clear: () => cache.clear()
1813
+ };
1814
+ }
1815
+ //#endregion
1816
+ //#region src/model/pages.ts
1817
+ function pageInfoFromProxy(page, index) {
1818
+ const [x1, y1, x2, y2] = page.view;
1819
+ const box = {
1820
+ x: Math.min(x1, x2),
1821
+ y: Math.min(y1, y2),
1822
+ width: Math.abs(x2 - x1),
1823
+ height: Math.abs(y2 - y1)
1824
+ };
1825
+ return {
1826
+ index,
1827
+ box,
1828
+ rotate: normaliseRotation(page.rotate),
1829
+ userUnit: page.userUnit > 0 ? page.userUnit : 1,
1830
+ width: box.width,
1831
+ height: box.height
1832
+ };
1833
+ }
1834
+ /** PDF.js already rejects /Rotate values that are not multiples of 90; this also folds negatives. */
1835
+ function normaliseRotation(rotate) {
1836
+ return (Math.round(rotate / 90) * 90 % 360 + 360) % 360;
1837
+ }
1838
+ //#endregion
1839
+ //#region src/model/source.ts
1840
+ function resolveSource(src, fetchImpl = globalThis.fetch) {
1841
+ if (typeof src === "string") return {
1842
+ key: src,
1843
+ bytes: () => fetchBytes(src, fetchImpl)
1844
+ };
1845
+ if (src instanceof ArrayBuffer || src instanceof Uint8Array) {
1846
+ const data = toBytes(src);
1847
+ return {
1848
+ key: `bytes:${v7()}`,
1849
+ bytes: () => Promise.resolve(data.slice())
1850
+ };
1851
+ }
1852
+ if ("url" in src) {
1853
+ const { url } = src;
1854
+ return {
1855
+ key: src.key,
1856
+ bytes: () => fetchBytes(url, fetchImpl)
1857
+ };
1858
+ }
1859
+ if ("data" in src) {
1860
+ const data = toBytes(src.data);
1861
+ return {
1862
+ key: src.key,
1863
+ bytes: () => Promise.resolve(data.slice())
1864
+ };
1865
+ }
1866
+ const blob = src;
1867
+ return {
1868
+ key: `bytes:${v7()}`,
1869
+ bytes: async () => new Uint8Array(await blob.arrayBuffer())
1870
+ };
1871
+ }
1872
+ /**
1873
+ * A view over the host's bytes. `bytes()` hands PDF.js a copy each time: PDF.js transfers the
1874
+ * buffer it is given to its worker, which would empty the host's array and break a reopen
1875
+ * (a password retry, for one).
1876
+ */
1877
+ function toBytes(data) {
1878
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
1879
+ }
1880
+ async function fetchBytes(url, fetchImpl) {
1881
+ if (typeof fetchImpl !== "function") throw new InkError("SourceFetchFailed", "No fetch implementation available for URL sources", { url });
1882
+ let res;
1883
+ try {
1884
+ res = await fetchImpl(url, { credentials: "same-origin" });
1885
+ } catch (cause) {
1886
+ throw new InkError("SourceFetchFailed", `Could not fetch ${url}`, { url }, cause);
1887
+ }
1888
+ if (!res.ok) throw new InkError("SourceFetchFailed", `Fetching ${url} returned HTTP ${res.status}`, {
1889
+ url,
1890
+ status: res.status
1891
+ });
1892
+ try {
1893
+ return new Uint8Array(await res.arrayBuffer());
1894
+ } catch (cause) {
1895
+ throw new InkError("SourceFetchFailed", `Reading the body of ${url} failed`, { url }, cause);
1896
+ }
1897
+ }
1898
+ //#endregion
1899
+ //#region src/model/text.ts
1900
+ /** Fractions of the font size used when PDF.js has no usable metrics for the font. */
1901
+ const FALLBACK_ASCENT = .75;
1902
+ const FALLBACK_DESCENT = .25;
1903
+ /**
1904
+ * Converts `getTextContent()` output to user-space boxes.
1905
+ *
1906
+ * For an item with transform [a, b, c, d, e, f] (already in user space):
1907
+ * - (e, f) is the start of the run on the baseline;
1908
+ * - u = (a, b) / |(a, b)| is the baseline direction, along which the run advances `width`;
1909
+ * - v = (c, d) / |(c, d)| is the glyph-up direction, and `fontSize` = |(c, d)|;
1910
+ * - the box spans from `descent * fontSize` below the baseline to `ascent * fontSize` above it,
1911
+ * using the font's ascent/descent from `styles` when PDF.js provides them, else 0.75 / 0.25.
1912
+ *
1913
+ * So p3 = (e, f) - v * descent * fontSize, p4 = p3 + u * width, p1 = p3 + v * (ascent + descent) * fontSize,
1914
+ * p2 = p4 + (p1 - p3). `rect` is the axis-aligned bounding box of the quad.
1915
+ */
1916
+ function textContentFromPdfjs(page, tc) {
1917
+ const items = [];
1918
+ for (const raw of tc.items) {
1919
+ if (!("str" in raw)) continue;
1920
+ const item = raw;
1921
+ const [a, b, c, d, e, f] = item.transform;
1922
+ const baseLen = Math.hypot(a, b);
1923
+ const fontSize = Math.hypot(c, d);
1924
+ const u = baseLen === 0 ? {
1925
+ x: 1,
1926
+ y: 0
1927
+ } : {
1928
+ x: a / baseLen,
1929
+ y: b / baseLen
1930
+ };
1931
+ const v = fontSize === 0 ? {
1932
+ x: -u.y,
1933
+ y: u.x
1934
+ } : {
1935
+ x: c / fontSize,
1936
+ y: d / fontSize
1937
+ };
1938
+ const { ascent, descent } = metrics(tc.styles[item.fontName]);
1939
+ const below = descent * fontSize;
1940
+ const total = (ascent + descent) * fontSize;
1941
+ const w = item.width;
1942
+ const p3 = {
1943
+ x: e - v.x * below,
1944
+ y: f - v.y * below
1945
+ };
1946
+ const p4 = {
1947
+ x: p3.x + u.x * w,
1948
+ y: p3.y + u.y * w
1949
+ };
1950
+ const quad = {
1951
+ p1: {
1952
+ x: p3.x + v.x * total,
1953
+ y: p3.y + v.y * total
1954
+ },
1955
+ p2: {
1956
+ x: p4.x + v.x * total,
1957
+ y: p4.y + v.y * total
1958
+ },
1959
+ p3,
1960
+ p4
1961
+ };
1962
+ items.push({
1963
+ str: item.str,
1964
+ dir: isDir(item.dir) ? item.dir : "ltr",
1965
+ fontName: item.fontName,
1966
+ fontSize,
1967
+ hasEOL: item.hasEOL,
1968
+ quad,
1969
+ rect: rectFromQuad(quad)
1970
+ });
1971
+ }
1972
+ return {
1973
+ page,
1974
+ items
1975
+ };
1976
+ }
1977
+ function metrics(style) {
1978
+ if (!style || style.vertical) return {
1979
+ ascent: FALLBACK_ASCENT,
1980
+ descent: FALLBACK_DESCENT
1981
+ };
1982
+ const ascent = style.ascent;
1983
+ const descent = Math.abs(style.descent);
1984
+ if (!(ascent > 0) || !Number.isFinite(descent) || ascent + descent <= 0) return {
1985
+ ascent: FALLBACK_ASCENT,
1986
+ descent: FALLBACK_DESCENT
1987
+ };
1988
+ return {
1989
+ ascent,
1990
+ descent
1991
+ };
1992
+ }
1993
+ function isDir(dir) {
1994
+ return dir === "ltr" || dir === "rtl" || dir === "ttb";
1995
+ }
1996
+ //#endregion
1997
+ //#region src/model/document.ts
1998
+ /**
1999
+ * Opens a document. Resolves once loading has finished, whether it succeeded or not:
2000
+ * check `status` or await `ready`, which rejects with the InkError. Only a missing
2001
+ * `assets` option (a programmer error) makes this promise itself reject.
2002
+ */
2003
+ async function openDocument(source, options) {
2004
+ assertAssets(options?.assets);
2005
+ const resolved = resolveSource(source, options.fetch);
2006
+ const status = writable({ state: "loading" });
2007
+ const pages = [];
2008
+ const info = {
2009
+ pageCount: 0,
2010
+ isEncrypted: false
2011
+ };
2012
+ let pageCache;
2013
+ let destroyed = false;
2014
+ let handles;
2015
+ let destroyTask;
2016
+ const store = createAnnotationStore({
2017
+ mode: options.annotations ?? { mode: "uncontrolled" },
2018
+ defaults: options.defaults ?? staticDefaults
2019
+ });
2020
+ const embedded = [];
2021
+ let preserved = [];
2022
+ const destroyedError = () => new InkError("DocumentDestroyed", "The document has been destroyed");
2023
+ const ready = (async () => {
2024
+ const pdfjs = await loadPdfjs(options.assets);
2025
+ const { task, proxy } = await openProxy(pdfjs, await resolved.bytes(), {
2026
+ assets: options.assets,
2027
+ password: options.password,
2028
+ verbosity: options.verbosity
2029
+ });
2030
+ destroyTask = () => task.destroy();
2031
+ const cache = createPageCache((index) => proxy.getPage(index + 1));
2032
+ pageCache = cache;
2033
+ const getPage = (index) => {
2034
+ if (destroyed) return Promise.reject(destroyedError());
2035
+ if (!Number.isInteger(index) || index < 0 || index >= proxy.numPages) return Promise.reject(new InkError("PageOutOfRange", `Page ${index} does not exist`, {
2036
+ index,
2037
+ pageCount: proxy.numPages
2038
+ }));
2039
+ return cache.get(index);
2040
+ };
2041
+ handles = {
2042
+ module: pdfjs,
2043
+ proxy,
2044
+ getPage
2045
+ };
2046
+ const docInfo = (await proxy.getMetadata().catch(() => {}))?.info ?? {};
2047
+ const title = nonEmptyString(docInfo.Title);
2048
+ const author = nonEmptyString(docInfo.Author);
2049
+ if (title !== void 0) info.title = title;
2050
+ if (author !== void 0) info.author = author;
2051
+ info.pageCount = proxy.numPages;
2052
+ info.isEncrypted = docInfo.EncryptFilterName !== null && docInfo.EncryptFilterName !== void 0;
2053
+ for (let i = 0; i < proxy.numPages; i++) pages.push(pageInfoFromProxy(await getPage(i), i));
2054
+ const importedAt = (/* @__PURE__ */ new Date()).toISOString();
2055
+ const perPage = await mapInOrder(proxy.numPages, EMBEDDED_CONCURRENCY, async (i) => {
2056
+ return importEmbeddedPage(i, await (await getPage(i)).getAnnotations().catch(() => {
2057
+ return [];
2058
+ }), importedAt);
2059
+ });
2060
+ embedded.push(...summarise(perPage.map((r) => r.counts)));
2061
+ const fromFile = perPage.flatMap((r) => r.annotations);
2062
+ if (fromFile.length > 0) store._setEmbedded(fromFile);
2063
+ })().then(() => {
2064
+ status.set({ state: "ready" });
2065
+ }, (cause) => {
2066
+ const error = isInkError(cause) ? cause : new InkError("InvalidPdf", errorMessage(cause), {}, cause);
2067
+ if (error.code === "PasswordRequired") info.isEncrypted = true;
2068
+ status.set({
2069
+ state: "error",
2070
+ error
2071
+ });
2072
+ throw error;
2073
+ });
2074
+ await ready.catch(() => void 0);
2075
+ const historyOption = options.history ?? true;
2076
+ const historyLimit = historyOption === false ? 0 : historyOption === true ? void 0 : historyOption.limit;
2077
+ const history = createHistory(store, historyLimit === void 0 ? {} : { limit: historyLimit });
2078
+ return {
2079
+ key: resolved.key,
2080
+ status: readonly(status),
2081
+ ready,
2082
+ pages,
2083
+ info,
2084
+ async text(page) {
2085
+ if (destroyed) throw destroyedError();
2086
+ if (!handles) throw statusError(status.get());
2087
+ return textContentFromPdfjs(page, await (await handles.getPage(page)).getTextContent());
2088
+ },
2089
+ annotations: store,
2090
+ embedded,
2091
+ history,
2092
+ exportAnnotations(format) {
2093
+ if (format !== "json") throw new TypeError(`Unsupported export format ${String(format)}`);
2094
+ return exportAnnotations(store, preserved, resolved.key);
2095
+ },
2096
+ importAnnotations(data, opts = { mode: "replace" }) {
2097
+ const plan = planImport(store, data, opts);
2098
+ preserved = opts.mode === "replace" ? plan.result.unknown : [...preserved.filter((u) => !plan.ids.has(u.id)), ...plan.result.unknown];
2099
+ plan.apply();
2100
+ return plan.result;
2101
+ },
2102
+ save() {
2103
+ return Promise.reject(new InkError("EngineUnavailable", "Saving needs @inkbar/engine, which is not registered. Use exportAnnotations(\"json\") to keep annotations without writing the PDF."));
2104
+ },
2105
+ destroy() {
2106
+ if (destroyed) return;
2107
+ destroyed = true;
2108
+ history.destroy();
2109
+ store.destroy();
2110
+ pageCache?.clear();
2111
+ if (destroyTask) teardown(destroyTask);
2112
+ },
2113
+ get _pdfjs() {
2114
+ if (!handles) throw statusError(status.get());
2115
+ return handles;
2116
+ }
2117
+ };
2118
+ }
2119
+ const EMBEDDED_CONCURRENCY = 8;
2120
+ /** Runs `task(0..count-1)` with at most `limit` in flight; results come back in index order. */
2121
+ async function mapInOrder(count, limit, task) {
2122
+ const results = new Array(count);
2123
+ let next = 0;
2124
+ const worker = async () => {
2125
+ while (next < count) {
2126
+ const i = next++;
2127
+ results[i] = await task(i);
2128
+ }
2129
+ };
2130
+ await Promise.all(Array.from({ length: Math.min(limit, count) }, worker));
2131
+ return results;
2132
+ }
2133
+ function teardown(destroyTask) {
2134
+ destroyTask().catch(() => {});
2135
+ }
2136
+ function statusError(s) {
2137
+ return s.state === "error" ? s.error : new InkError("InvalidPdf", "The document has not finished loading");
2138
+ }
2139
+ function nonEmptyString(value) {
2140
+ return typeof value === "string" && value !== "" ? value : void 0;
2141
+ }
2142
+ function errorMessage(cause) {
2143
+ if (cause instanceof Error) return cause.message;
2144
+ return String(cause);
2145
+ }
2146
+ const shift = (p, dx, dy) => ({
2147
+ x: p.x + dx,
2148
+ y: p.y + dy
2149
+ });
2150
+ /** The geometry patch that translates `a` by (dx, dy) in user space. */
2151
+ function translated(a, dx, dy) {
2152
+ const patch = { rect: translateRect(a.rect, dx, dy) };
2153
+ if ("quads" in a && a.quads) patch.quads = a.quads.map((q) => translateQuad(q, dx, dy));
2154
+ if ("callout" in a && a.callout) patch.callout = a.callout.map((p) => shift(p, dx, dy));
2155
+ switch (a.type) {
2156
+ case "line":
2157
+ patch.start = shift(a.start, dx, dy);
2158
+ patch.end = shift(a.end, dx, dy);
2159
+ break;
2160
+ case "polyline":
2161
+ case "polygon":
2162
+ patch.vertices = a.vertices.map((p) => shift(p, dx, dy));
2163
+ break;
2164
+ case "ink": patch.inklist = a.inklist.map((path) => path.map((p) => shift(p, dx, dy)));
2165
+ }
2166
+ return patch;
2167
+ }
2168
+ /**
2169
+ * True when `rect` is the annotation's whole shape, so resizing means changing `rect`: area
2170
+ * redactions, free text, squares, circles, stamps, loupes and masks. Text-derived marks (quads), note icons and
2171
+ * point-based shapes are not.
2172
+ */
2173
+ function hasRectGeometry(a) {
2174
+ switch (a.type) {
2175
+ case "redact": return a.quads === void 0 || a.quads.length === 0;
2176
+ case "freetext":
2177
+ case "square":
2178
+ case "circle":
2179
+ case "stamp":
2180
+ case "loupe":
2181
+ case "mask": return true;
2182
+ default: return false;
2183
+ }
2184
+ }
2185
+ /**
2186
+ * Grows (positive) or shrinks (negative) a rect by `dw` and `dh` points, keeping its top-left
2187
+ * corner (user space: left edge and top edge, `y + height`) where it is. Neither side goes
2188
+ * below `MIN_SIZE`. With `keepAspect`, the side that changes leads and the other follows it in
2189
+ * proportion (the width when both change).
2190
+ */
2191
+ function resizedRect(r, dw, dh, keepAspect = false) {
2192
+ let width = Math.max(1, r.width + dw);
2193
+ let height = Math.max(1, r.height + dh);
2194
+ if (keepAspect && r.width > 0 && r.height > 0) {
2195
+ const aspect = r.width / r.height;
2196
+ if (dw !== 0) height = width / aspect;
2197
+ else width = height * aspect;
2198
+ const grow = Math.max(1 / width, 1 / height, 1);
2199
+ width *= grow;
2200
+ height *= grow;
2201
+ }
2202
+ const top = r.y + r.height;
2203
+ return {
2204
+ x: r.x,
2205
+ y: top - height,
2206
+ width,
2207
+ height
2208
+ };
2209
+ }
2210
+ /**
2211
+ * True for highlight, underline, strikeout and squiggly: marks on text, which a drag passes
2212
+ * through to text selection and a click selects.
2213
+ */
2214
+ function isTextMarkup(a) {
2215
+ return a.type === "highlight" || a.type === "underline" || a.type === "strikeout" || a.type === "squiggly";
2216
+ }
2217
+ /**
2218
+ * True for the point-based shapes a corner handle resizes by scaling their points: polylines,
2219
+ * polygons and ink. With `hasRectGeometry`, the annotations that get corner handles.
2220
+ */
2221
+ function scalesPoints(a) {
2222
+ return a.type === "polyline" || a.type === "polygon" || a.type === "ink";
2223
+ }
2224
+ /** True when a corner handle resizes `a`: rect-shaped types and point-based shapes. */
2225
+ function hasCornerHandles(a) {
2226
+ return hasRectGeometry(a) || scalesPoints(a);
2227
+ }
2228
+ /**
2229
+ * The geometry patch that maps `a` from the box `from` onto the box `to`, both in user space:
2230
+ * `rect`, every point field (quads, ink paths, vertices, line ends, callout) and a free text's
2231
+ * `fringe` scale with the boxes. Stroke widths and font sizes stay as they are.
2232
+ */
2233
+ function scaled(a, from, to) {
2234
+ const sx = from.width === 0 ? 1 : to.width / from.width;
2235
+ const sy = from.height === 0 ? 1 : to.height / from.height;
2236
+ const map = (p) => ({
2237
+ x: to.x + (p.x - from.x) * sx,
2238
+ y: to.y + (p.y - from.y) * sy
2239
+ });
2240
+ const sameBox = (r) => r.x === from.x && r.y === from.y && r.width === from.width && r.height === from.height;
2241
+ const patch = { rect: sameBox(a.rect) ? { ...to } : {
2242
+ ...map(a.rect),
2243
+ width: a.rect.width * sx,
2244
+ height: a.rect.height * sy
2245
+ } };
2246
+ if ("quads" in a && a.quads) patch.quads = a.quads.map((q) => ({
2247
+ p1: map(q.p1),
2248
+ p2: map(q.p2),
2249
+ p3: map(q.p3),
2250
+ p4: map(q.p4)
2251
+ }));
2252
+ if ("callout" in a && a.callout) patch.callout = a.callout.map(map);
2253
+ if (a.type === "freetext" && a.fringe) patch.fringe = {
2254
+ left: a.fringe.left * sx,
2255
+ top: a.fringe.top * sy,
2256
+ right: a.fringe.right * sx,
2257
+ bottom: a.fringe.bottom * sy
2258
+ };
2259
+ switch (a.type) {
2260
+ case "line":
2261
+ patch.start = map(a.start);
2262
+ patch.end = map(a.end);
2263
+ break;
2264
+ case "polyline":
2265
+ case "polygon":
2266
+ patch.vertices = a.vertices.map(map);
2267
+ break;
2268
+ case "ink": patch.inklist = a.inklist.map((path) => path.map(map));
2269
+ }
2270
+ return patch;
2271
+ }
2272
+ /**
2273
+ * The patch that moves one end of a line to `to` and refits `rect` to the new ends, padded by
2274
+ * half the stroke width on every side.
2275
+ */
2276
+ function movedEndpoint(a, which, to) {
2277
+ const start = which === "start" ? to : a.start;
2278
+ const end = which === "end" ? to : a.end;
2279
+ const pad = a.width / 2;
2280
+ const x = Math.min(start.x, end.x);
2281
+ const y = Math.min(start.y, end.y);
2282
+ return {
2283
+ [which]: { ...to },
2284
+ rect: {
2285
+ x: x - pad,
2286
+ y: y - pad,
2287
+ width: Math.abs(end.x - start.x) + pad * 2,
2288
+ height: Math.abs(end.y - start.y) + pad * 2
2289
+ }
2290
+ };
2291
+ }
2292
+ /**
2293
+ * True for annotations whose resize keeps their aspect ratio without `Shift`: stamps, loupes,
2294
+ * masks and signatures (ink with subject `Signature`).
2295
+ */
2296
+ function keepsAspect(a) {
2297
+ if (a.type === "stamp" || a.type === "loupe" || a.type === "mask") return true;
2298
+ return a.type === "ink" && a.subject === "Signature";
2299
+ }
2300
+ /**
2301
+ * True for a speech bubble: a standard free-text callout (`intent: 'FreeTextCallout'`, `rect`,
2302
+ * `fringe`, `callout`) with Inkbar's `cornerRadius`. Inkbar draws it as one rounded outline with
2303
+ * a wedge from where `callout`'s last point meets the box to the tip, `callout[0]`.
2304
+ */
2305
+ function isBubble(a) {
2306
+ return a.type === "freetext" && a.intent === "FreeTextCallout" && a.cornerRadius !== void 0 && a.callout !== void 0 && a.callout.length >= 2;
2307
+ }
2308
+ /** True for a free text with a callout to edit: a speech bubble or a standard callout. */
2309
+ function hasCallout(a) {
2310
+ return isBubble(a) || isStandardCallout(a);
2311
+ }
2312
+ /**
2313
+ * The patch that puts a free text's text box at `box`, refitting `rect` and `fringe` around
2314
+ * it. A callout's points become `callout` (its own by default) and `rect` holds them too; any
2315
+ * other box keeps its fringe, or has `rect` equal to the box without one.
2316
+ */
2317
+ function withBox(a, box, callout = a.callout) {
2318
+ if (hasCallout(a) && callout) return {
2319
+ ...withCalloutBounds(box, callout, calloutStroke(a).width, a.head),
2320
+ callout: callout.map((p) => ({ ...p }))
2321
+ };
2322
+ const f = a.fringe;
2323
+ if (!f) return { rect: { ...box } };
2324
+ return { rect: {
2325
+ x: box.x - f.left,
2326
+ y: box.y - f.bottom,
2327
+ width: box.width + f.left + f.right,
2328
+ height: box.height + f.bottom + f.top
2329
+ } };
2330
+ }
2331
+ const EDGES = [
2332
+ "left",
2333
+ "right",
2334
+ "bottom",
2335
+ "top"
2336
+ ];
2337
+ /**
2338
+ * The edge of `box` nearest `p`. `bubblePath` (dom/overlay-render.ts) picks the wedge's edge by
2339
+ * the same rule in CSS px; change both together.
2340
+ */
2341
+ function nearestEdge(p, box) {
2342
+ const gaps = {
2343
+ left: Math.abs(p.x - box.x),
2344
+ right: Math.abs(p.x - (box.x + box.width)),
2345
+ bottom: Math.abs(p.y - box.y),
2346
+ top: Math.abs(p.y - (box.y + box.height))
2347
+ };
2348
+ return EDGES.reduce((best, e) => gaps[e] < gaps[best] ? e : best);
2349
+ }
2350
+ /** The side of `box` that `p` lies furthest beyond. */
2351
+ function edgeBeyond(p, box) {
2352
+ const beyond = {
2353
+ left: box.x - p.x,
2354
+ right: p.x - (box.x + box.width),
2355
+ bottom: box.y - p.y,
2356
+ top: p.y - (box.y + box.height)
2357
+ };
2358
+ return EDGES.reduce((best, e) => beyond[e] > beyond[best] ? e : best);
2359
+ }
2360
+ /**
2361
+ * `p` carried from the box `from` onto the box `to`: it keeps its fraction along the box edge
2362
+ * nearest it and its distance off that edge.
2363
+ */
2364
+ function onMovedEdge(p, from, to) {
2365
+ const edge = nearestEdge(p, from);
2366
+ const along = (v, start, size, next, nextSize) => next + (size === 0 ? nextSize / 2 : (v - start) / size * nextSize);
2367
+ if (edge === "left" || edge === "right") {
2368
+ const x = edge === "left" ? from.x : from.x + from.width;
2369
+ return {
2370
+ x: (edge === "left" ? to.x : to.x + to.width) + p.x - x,
2371
+ y: along(p.y, from.y, from.height, to.y, to.height)
2372
+ };
2373
+ }
2374
+ const y = edge === "bottom" ? from.y : from.y + from.height;
2375
+ const ny = edge === "bottom" ? to.y : to.y + to.height;
2376
+ return {
2377
+ x: along(p.x, from.x, from.width, to.x, to.width),
2378
+ y: ny + p.y - y
2379
+ };
2380
+ }
2381
+ /**
2382
+ * `p` placed on `box`'s `edge` at its own position along it, kept `margin` points clear of the
2383
+ * corners (at most half the edge).
2384
+ */
2385
+ function ontoEdge(p, box, edge, margin) {
2386
+ const clamp = (v, start, size) => {
2387
+ const m = Math.min(margin, size / 2);
2388
+ return Math.min(Math.max(v, start + m), start + size - m);
2389
+ };
2390
+ if (edge === "left" || edge === "right") return {
2391
+ x: edge === "left" ? box.x : box.x + box.width,
2392
+ y: clamp(p.y, box.y, box.height)
2393
+ };
2394
+ return {
2395
+ x: clamp(p.x, box.x, box.width),
2396
+ y: edge === "bottom" ? box.y : box.y + box.height
2397
+ };
2398
+ }
2399
+ /**
2400
+ * The patch that resizes a free text's text box to `to`. A callout's tip and bend stay where
2401
+ * they are and its last point moves with the box edge it sits on (`onMovedEdge`).
2402
+ */
2403
+ function resizedBox(a, to) {
2404
+ if (!hasCallout(a)) return withBox(a, to);
2405
+ const from = freeTextBox(a);
2406
+ const last = a.callout.length - 1;
2407
+ return withBox(a, to, a.callout.map((p, i) => i === last ? onMovedEdge(p, from, to) : p));
2408
+ }
2409
+ /**
2410
+ * The patch that moves a callout's tip to `to`, leaving its text box where it is. A callout
2411
+ * without a bend (every bubble) moves its edge point to the side the tip now lies furthest
2412
+ * beyond, at its own position along that side and clear of the corners, so the line or wedge
2413
+ * never crosses the box; on the same side it stays put. A bend and its edge point stay.
2414
+ */
2415
+ function movedTip(a, to) {
2416
+ const box = freeTextBox(a);
2417
+ if (a.callout.length !== 2) return withBox(a, box, [to, ...a.callout.slice(1)]);
2418
+ const edge = a.callout[1];
2419
+ const side = edgeBeyond(to, box);
2420
+ const margin = (a.cornerRadius ?? 0) + 8;
2421
+ return withBox(a, box, [to, nearestEdge(edge, box) === side ? edge : ontoEdge(edge, box, side, margin)]);
2422
+ }
2423
+ //#endregion
2424
+ //#region src/model/annotations/style-map.ts
2425
+ /** For each type, the control-level props it supports and the field each writes. */
2426
+ const FIELDS = {
2427
+ square: {
2428
+ border: "color",
2429
+ fill: "interiorColor",
2430
+ opacity: "opacity",
2431
+ width: "width",
2432
+ dashes: "dashes"
2433
+ },
2434
+ circle: {
2435
+ border: "color",
2436
+ fill: "interiorColor",
2437
+ opacity: "opacity",
2438
+ width: "width",
2439
+ dashes: "dashes"
2440
+ },
2441
+ polygon: {
2442
+ border: "color",
2443
+ fill: "interiorColor",
2444
+ opacity: "opacity",
2445
+ width: "width",
2446
+ dashes: "dashes"
2447
+ },
2448
+ polyline: {
2449
+ border: "color",
2450
+ opacity: "opacity",
2451
+ width: "width",
2452
+ dashes: "dashes",
2453
+ head: "head",
2454
+ tail: "tail"
2455
+ },
2456
+ line: {
2457
+ border: "color",
2458
+ opacity: "opacity",
2459
+ width: "width",
2460
+ dashes: "dashes",
2461
+ head: "head",
2462
+ tail: "tail"
2463
+ },
2464
+ ink: {
2465
+ border: "color",
2466
+ opacity: "opacity",
2467
+ width: "width"
2468
+ },
2469
+ highlight: {
2470
+ border: "color",
2471
+ opacity: "opacity"
2472
+ },
2473
+ underline: {
2474
+ border: "color",
2475
+ opacity: "opacity"
2476
+ },
2477
+ strikeout: {
2478
+ border: "color",
2479
+ opacity: "opacity"
2480
+ },
2481
+ squiggly: {
2482
+ border: "color",
2483
+ opacity: "opacity"
2484
+ },
2485
+ redact: {
2486
+ border: "color",
2487
+ opacity: "opacity"
2488
+ },
2489
+ freetext: {
2490
+ border: "borderColor",
2491
+ fill: "color",
2492
+ textColor: "defaultStyle.color",
2493
+ opacity: "opacity",
2494
+ width: "width",
2495
+ dashes: "dashes",
2496
+ fontFamily: "defaultStyle.fontFamily",
2497
+ fontSize: "defaultStyle.fontSize",
2498
+ fontWeight: "defaultStyle.fontWeight",
2499
+ fontStyle: "defaultStyle.fontStyle",
2500
+ textDecoration: "defaultStyle.textDecoration",
2501
+ textAlign: "defaultStyle.textAlign"
2502
+ },
2503
+ loupe: {
2504
+ border: "color",
2505
+ opacity: "opacity",
2506
+ width: "width"
2507
+ },
2508
+ mask: {},
2509
+ text: {},
2510
+ stamp: {}
2511
+ };
2512
+ const GROUPS = {
2513
+ square: "shape",
2514
+ circle: "shape",
2515
+ line: "shape",
2516
+ polyline: "shape",
2517
+ polygon: "shape",
2518
+ loupe: "shape",
2519
+ ink: "ink",
2520
+ freetext: "text",
2521
+ highlight: "markup",
2522
+ underline: "markup",
2523
+ strikeout: "markup",
2524
+ squiggly: "markup",
2525
+ redact: "redact",
2526
+ text: void 0,
2527
+ stamp: void 0,
2528
+ mask: void 0
2529
+ };
2530
+ const SUPPORTED = new Map(Object.keys(FIELDS).map((type) => [type, new Set(Object.keys(FIELDS[type]))]));
2531
+ /**
2532
+ * The props a speech bubble (`intent: 'FreeTextCallout'`) takes from the `shape` group: its
2533
+ * outline, fill and opacity, as the shape tool creates it. Its text props stay in `text`.
2534
+ */
2535
+ const BUBBLE_SHAPE_PROPS = /* @__PURE__ */ new Set([
2536
+ "border",
2537
+ "fill",
2538
+ "opacity",
2539
+ "width",
2540
+ "dashes"
2541
+ ]);
2542
+ /**
2543
+ * The style group an annotation's type belongs to; notes belong to none. With `key`, the group
2544
+ * that owns that prop on `a`: a speech bubble's outline and fill are `shape`'s, its text `text`'s.
2545
+ */
2546
+ function styleGroupOf(a, key) {
2547
+ if (key !== void 0 && a.type === "freetext" && a.intent === "FreeTextCallout" && BUBBLE_SHAPE_PROPS.has(key)) return "shape";
2548
+ return GROUPS[a.type];
2549
+ }
2550
+ /** Every group that owns some prop on `a`: two for a speech bubble, else at most one. */
2551
+ function styleGroupsOf(a) {
2552
+ const out = /* @__PURE__ */ new Set();
2553
+ const own = GROUPS[a.type];
2554
+ if (own) out.add(own);
2555
+ for (const key of supportedProps(a.type)) {
2556
+ const g = styleGroupOf(a, key);
2557
+ if (g) out.add(g);
2558
+ }
2559
+ return [...out];
2560
+ }
2561
+ /** The types in `group`, from the same table `styleGroupOf` reads. */
2562
+ function typesInGroup(group) {
2563
+ return Object.keys(GROUPS).filter((t) => GROUPS[t] === group);
2564
+ }
2565
+ /** The style group a type belongs to. */
2566
+ function styleGroupOfType(type) {
2567
+ return GROUPS[type];
2568
+ }
2569
+ /** The control-level props `type` supports. */
2570
+ function supportedProps(type) {
2571
+ return SUPPORTED.get(type) ?? /* @__PURE__ */ new Set();
2572
+ }
2573
+ /**
2574
+ * The control values a field leaves out: `normal` weight and style, no decoration. The field
2575
+ * is absent rather than holding them, as XFDF writes only what differs.
2576
+ */
2577
+ const UNSET = {
2578
+ fontWeight: "normal",
2579
+ fontStyle: "normal",
2580
+ textDecoration: "none"
2581
+ };
2582
+ /** The prefix of a field nested in `defaultStyle` (free text). */
2583
+ const STYLE = "defaultStyle.";
2584
+ /**
2585
+ * The field patch `patch` means on `type`. Props the type lacks are dropped. A `null` fill
2586
+ * becomes `interiorColor: undefined` (`color` on free text), which removes the fill when the
2587
+ * store applies it; so does `normal` weight or style and no decoration. Free-text text props go
2588
+ * into a partial `defaultStyle`, which the store merges into the current one.
2589
+ */
2590
+ function toFields(type, patch) {
2591
+ const fields = FIELDS[type];
2592
+ const out = {};
2593
+ for (const key of Object.keys(patch)) {
2594
+ const field = fields[key];
2595
+ if (field === void 0) continue;
2596
+ const raw = patch[key];
2597
+ const value = raw === null || raw === UNSET[key] ? void 0 : raw;
2598
+ if (field.startsWith(STYLE)) {
2599
+ const style = out.defaultStyle ??= {};
2600
+ style[field.slice(13)] = value;
2601
+ } else out[field] = value;
2602
+ }
2603
+ return out;
2604
+ }
2605
+ /** The control-level props an annotation shows, for the props its type supports. */
2606
+ function fromAnnotation(a) {
2607
+ const fields = FIELDS[a.type];
2608
+ const record = a;
2609
+ const style = record.defaultStyle ?? {};
2610
+ const out = {};
2611
+ for (const key of Object.keys(fields)) {
2612
+ const field = fields[key];
2613
+ const value = field.startsWith(STYLE) ? style[field.slice(13)] : record[field];
2614
+ if (value !== void 0) out[key] = value;
2615
+ else if (key === "fill" || key === "dashes") out[key] = null;
2616
+ else if (key === "head" || key === "tail") out[key] = "None";
2617
+ else if (UNSET[key] !== void 0) out[key] = UNSET[key];
2618
+ }
2619
+ return out;
2620
+ }
2621
+ //#endregion
2622
+ //#region src/model/annotations/tool-style.ts
2623
+ const STYLE_GROUPS = [
2624
+ "shape",
2625
+ "ink",
2626
+ "text",
2627
+ "markup",
2628
+ "redact"
2629
+ ];
2630
+ /** Every prop some type in `group` supports. */
2631
+ function groupProps(group) {
2632
+ const out = /* @__PURE__ */ new Set();
2633
+ for (const type of typesInGroup(group)) for (const key of supportedProps(type)) out.add(key);
2634
+ return out;
2635
+ }
2636
+ function sameValue(a, b) {
2637
+ if (Object.is(a, b)) return true;
2638
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((v, i) => Object.is(v, b[i]));
2639
+ return false;
2640
+ }
2641
+ function sameRecord(a, b) {
2642
+ const ka = Object.keys(a);
2643
+ if (ka.length !== Object.keys(b).length) return false;
2644
+ return ka.every((k) => k in b && sameValue(a[k], b[k]));
2645
+ }
2646
+ function sameSet(a, b) {
2647
+ return a.size === b.size && [...a].every((v) => b.has(v));
2648
+ }
2649
+ /**
2650
+ * A readable recomputed from `fn` whenever any source fires, subscribed to its sources only
2651
+ * while it has subscribers. Equal results (by `eq`) are not re-emitted and keep their identity.
2652
+ */
2653
+ function computed(sources, fn, eq) {
2654
+ const subs = /* @__PURE__ */ new Set();
2655
+ let cached;
2656
+ let stops;
2657
+ /** Recomputes, keeping the previous value's identity when equal. True when it changed. */
2658
+ const recompute = () => {
2659
+ const next = fn();
2660
+ if (cached && eq(next, cached.value)) return false;
2661
+ cached = { value: next };
2662
+ return true;
2663
+ };
2664
+ const refresh = () => {
2665
+ if (!recompute() || !cached) return;
2666
+ const value = cached.value;
2667
+ for (const sub of [...subs]) sub(value);
2668
+ };
2669
+ return {
2670
+ get: () => {
2671
+ if (!stops) recompute();
2672
+ return cached.value;
2673
+ },
2674
+ subscribe(sub) {
2675
+ if (!stops) {
2676
+ recompute();
2677
+ stops = sources.map((s) => s.subscribe(refresh));
2678
+ }
2679
+ subs.add(sub);
2680
+ return () => {
2681
+ if (!subs.delete(sub) || subs.size > 0) return;
2682
+ for (const stop of stops ?? []) stop();
2683
+ stops = void 0;
2684
+ };
2685
+ }
2686
+ };
2687
+ }
2688
+ function createToolStyle(deps) {
2689
+ const { store, history, activeGroup } = deps;
2690
+ const groups = new Map(STYLE_GROUPS.map((g) => [g, writable({})]));
2691
+ const groupStore = (g) => {
2692
+ const w = groups.get(g);
2693
+ if (!w) throw new RangeError(`Unknown style group ${String(g)}`);
2694
+ return w;
2695
+ };
2696
+ /** The selected annotations, including changes proposed to a controlled host. */
2697
+ const selected = () => store.selection.get().map((id) => store._getProposed(id) ?? store.get(id)).filter((a) => a !== void 0);
2698
+ const sources = [
2699
+ store.list,
2700
+ store.selection,
2701
+ ...groups.values(),
2702
+ ...deps.active ? [deps.active] : []
2703
+ ];
2704
+ /** One value per prop over `items`, `'mixed'` where they differ. */
2705
+ const styleOf = (items) => {
2706
+ const out = {};
2707
+ for (const a of items) {
2708
+ const props = fromAnnotation(a);
2709
+ for (const [key, value] of Object.entries(props)) if (!(key in out)) out[key] = value;
2710
+ else if (out[key] !== "mixed" && !sameValue(out[key], value)) out[key] = "mixed";
2711
+ }
2712
+ return out;
2713
+ };
2714
+ const propsOf = (items) => {
2715
+ const out = /* @__PURE__ */ new Set();
2716
+ for (const a of items) for (const key of supportedProps(a.type)) out.add(key);
2717
+ return out;
2718
+ };
2719
+ /** The selection, when it is non-empty and wholly in `group`. */
2720
+ const selectedIn = (group) => {
2721
+ const items = selected();
2722
+ return items.length > 0 && items.every((a) => styleGroupsOf(a).includes(group)) ? items : null;
2723
+ };
2724
+ const current = computed(sources, () => {
2725
+ const g = activeGroup();
2726
+ if (!g) return styleOf(selected());
2727
+ const items = selectedIn(g);
2728
+ return items ? styleOf(items) : { ...groupStore(g).get() };
2729
+ }, (a, b) => sameRecord(a, b));
2730
+ const supported = computed(sources, () => {
2731
+ const g = activeGroup();
2732
+ if (!g) return propsOf(selected());
2733
+ const items = selectedIn(g);
2734
+ return items ? /* @__PURE__ */ new Set([...groupProps(g), ...propsOf(items)]) : groupProps(g);
2735
+ }, sameSet);
2736
+ const scopes = /* @__PURE__ */ new Map();
2737
+ function scoped(group) {
2738
+ const known = scopes.get(group);
2739
+ if (known) return known;
2740
+ groupStore(group);
2741
+ const scope = {
2742
+ group,
2743
+ current: computed(sources, () => {
2744
+ const items = selectedIn(group);
2745
+ return items ? styleOf(items) : { ...groupStore(group).get() };
2746
+ }, (a, b) => sameRecord(a, b)),
2747
+ supported: computed(sources, () => {
2748
+ const items = selectedIn(group);
2749
+ return items ? propsOf(items) : groupProps(group);
2750
+ }, sameSet),
2751
+ set: (patch) => set(patch, {
2752
+ group,
2753
+ apply: selectedIn(group) !== null
2754
+ })
2755
+ };
2756
+ scopes.set(group, scope);
2757
+ return scope;
2758
+ }
2759
+ function set(patch, opts = {}) {
2760
+ const items = selected();
2761
+ const active = opts.group ?? activeGroup();
2762
+ const keys = Object.keys(patch).filter((k) => patch[k] !== void 0);
2763
+ const targets = /* @__PURE__ */ new Map();
2764
+ if (active) targets.set(active, new Set(keys));
2765
+ else for (const a of items) for (const key of keys) {
2766
+ if (!supportedProps(a.type).has(key)) continue;
2767
+ const g = styleGroupOf(a, key);
2768
+ if (!g) continue;
2769
+ const own = targets.get(g) ?? /* @__PURE__ */ new Set();
2770
+ own.add(key);
2771
+ targets.set(g, own);
2772
+ }
2773
+ for (const [g, own] of targets) {
2774
+ const allowed = groupProps(g);
2775
+ const next = { ...groupStore(g).get() };
2776
+ let changed = false;
2777
+ for (const key of own) {
2778
+ if (!allowed.has(key)) continue;
2779
+ next[key] = patch[key];
2780
+ changed = true;
2781
+ }
2782
+ if (changed) groupStore(g).set(next);
2783
+ }
2784
+ if (!(opts.apply ?? (active === void 0 || selectedIn(active) !== null))) return;
2785
+ const edits = items.filter((a) => !a.locked).map((a) => ({
2786
+ id: a.id,
2787
+ fields: refit(a, toFields(a.type, patch))
2788
+ })).filter((e) => Object.keys(e.fields).length > 0);
2789
+ if (edits.length === 0) return;
2790
+ history.batch(() => {
2791
+ for (const e of edits) store.update(e.id, e.fields);
2792
+ });
2793
+ }
2794
+ /**
2795
+ * `fields` with a callout's `rect` and `fringe` refit when they change its border width, so
2796
+ * the bounds keep covering the leader, its ending and the outline.
2797
+ */
2798
+ function refit(a, fields) {
2799
+ if (!("width" in fields) || !hasCallout(a)) return fields;
2800
+ const next = {
2801
+ ...a,
2802
+ ...fields
2803
+ };
2804
+ return {
2805
+ ...fields,
2806
+ ...withBox(next, freeTextBox(a))
2807
+ };
2808
+ }
2809
+ /** `value`'s keys that hold something. */
2810
+ const defined = (value) => Object.fromEntries(Object.entries(value ?? {}).filter(([, v]) => v !== void 0));
2811
+ function resolve(group, input) {
2812
+ const fields = toFields(input.type, groupStore(group).get());
2813
+ const out = { ...input };
2814
+ for (const [key, value] of Object.entries(fields)) if (key === "defaultStyle") out[key] = {
2815
+ ...defined(value),
2816
+ ...defined(out[key])
2817
+ };
2818
+ else if (value !== void 0 && out[key] === void 0) out[key] = value;
2819
+ return out;
2820
+ }
2821
+ return {
2822
+ get: (g) => groupStore(g).get(),
2823
+ readable: (g) => {
2824
+ const w = groupStore(g);
2825
+ return {
2826
+ get: () => w.get(),
2827
+ subscribe: (fn) => w.subscribe(fn)
2828
+ };
2829
+ },
2830
+ current,
2831
+ supported,
2832
+ set,
2833
+ resolve,
2834
+ scoped
2835
+ };
2836
+ }
2837
+ //#endregion
2838
+ //#region src/model/annotations/suggestions.ts
2839
+ /**
2840
+ * Keeps a suggested redaction as the user's own: `origin` becomes `'user'` and the colour
2841
+ * goes from the confidence colour to the store's default redaction colour, so an accepted
2842
+ * mark looks like any other. The suggestion details stay on it. Returns the updated
2843
+ * annotation, or undefined (changing nothing) when `id` is not a suggested redaction or is
2844
+ * locked.
2845
+ */
2846
+ function acceptSuggestion(store, id) {
2847
+ const a = store._getProposed(id);
2848
+ if (a?.type !== "redact" || a.origin !== "suggested" || a.locked) return void 0;
2849
+ return store.update(id, {
2850
+ origin: "user",
2851
+ color: store.defaults.color("redact")
2852
+ });
2853
+ }
2854
+ //#endregion
2855
+ //#region src/model/annotations/threads.ts
2856
+ function isThreadRoot(a) {
2857
+ return a.type === "text" || isTextMarkup(a);
2858
+ }
2859
+ /**
2860
+ * True for a reply: an annotation whose `inReplyTo` names a thread root (a note or text markup)
2861
+ * in `list`. Replies show in the thread popover only, never on the page.
2862
+ */
2863
+ function isReply(a, list) {
2864
+ if (a.inReplyTo === void 0) return false;
2865
+ const parent = list.find((x) => x.id === a.inReplyTo);
2866
+ return parent !== void 0 && isThreadRoot(parent);
2867
+ }
2868
+ /** `list` less its replies (see `isReply`), in the same order. */
2869
+ function withoutReplies(list) {
2870
+ const roots = new Set(list.filter(isThreadRoot).map((a) => a.id));
2871
+ return list.filter((a) => a.inReplyTo === void 0 || !roots.has(a.inReplyTo));
2872
+ }
2873
+ /** Direct replies to `id`, in creation order. */
2874
+ function repliesTo(list, id) {
2875
+ return list.filter((a) => a.inReplyTo === id).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
2876
+ }
2877
+ /**
2878
+ * The top of a thread: follows `inReplyTo` up through notes, stopping at text markup (which
2879
+ * roots a thread of its own), a missing parent, a parent that cannot root a thread, or a
2880
+ * cycle. Null when `start` is neither a note nor text markup.
2881
+ */
2882
+ function threadRoot(list, start) {
2883
+ if (!isThreadRoot(start)) return null;
2884
+ const seen = /* @__PURE__ */ new Set([start.id]);
2885
+ let current = start;
2886
+ while (current.type === "text" && current.inReplyTo) {
2887
+ const id = current.inReplyTo;
2888
+ const parent = list.find((a) => a.id === id);
2889
+ if (!parent || !isThreadRoot(parent) || seen.has(parent.id)) break;
2890
+ seen.add(parent.id);
2891
+ current = parent;
2892
+ }
2893
+ return current;
2894
+ }
2895
+ /** The root, then every reply below it, depth first, each level in creation order. */
2896
+ function threadOf(list, root) {
2897
+ const out = [root];
2898
+ const seen = /* @__PURE__ */ new Set([root.id]);
2899
+ const visit = (id) => {
2900
+ for (const r of repliesTo(list, id)) {
2901
+ if (seen.has(r.id)) continue;
2902
+ seen.add(r.id);
2903
+ out.push(r);
2904
+ visit(r.id);
2905
+ }
2906
+ };
2907
+ visit(root.id);
2908
+ return out;
2909
+ }
2910
+ /**
2911
+ * An unlocked root note with no text and no replies: nothing a reader would miss. Always
2912
+ * false for text markup, which is worth keeping without a comment.
2913
+ */
2914
+ function isAbandonedNote(a, list) {
2915
+ if (a.type !== "text" || a.locked || a.inReplyTo || a.contents?.trim()) return false;
2916
+ return repliesTo(list, a.id).length === 0;
2917
+ }
2918
+ //#endregion
2919
+ //#region src/model/annotations/shape-geometry.ts
2920
+ /** The kinds the shape menu offers today, in menu order. Later kinds extend this. */
2921
+ const SHAPE_KINDS = [
2922
+ "line",
2923
+ "arrow",
2924
+ "rectangle",
2925
+ "roundedRectangle",
2926
+ "ellipse",
2927
+ "bubble",
2928
+ "star",
2929
+ "polygon",
2930
+ "loupe",
2931
+ "mask",
2932
+ "ovalMask"
2933
+ ];
2934
+ const DEFAULT_SHAPE_OPTIONS = {
2935
+ kind: "rectangle",
2936
+ points: 5,
2937
+ sides: 6
2938
+ };
2939
+ const POINTER_ONLY = /* @__PURE__ */ new Set([
2940
+ "loupe",
2941
+ "mask",
2942
+ "ovalMask"
2943
+ ]);
2944
+ /**
2945
+ * True for kinds only a pointer creates: the loupe and the mask. `Enter` with the shape tool
2946
+ * does not place them.
2947
+ */
2948
+ function isPointerOnlyKind(kind) {
2949
+ return POINTER_ONLY.has(kind);
2950
+ }
2951
+ /** How strongly a new mask dims the page. */
2952
+ const DEFAULT_MASK_DIM = .5;
2953
+ /** Side of the shape a click or Enter places, in points. */
2954
+ const DEFAULT_SHAPE_SIZE = 72;
2955
+ /** Corner radius of a new rounded rectangle, in points. */
2956
+ const DEFAULT_CORNER_RADIUS = 8;
2957
+ /** How far below and left of its anchor a new speech bubble's tail tip sits, in points. */
2958
+ const BUBBLE_TAIL = 24;
2959
+ /** A new speech bubble's outline width, in points, before the style group's applies. */
2960
+ const BUBBLE_WIDTH = 1;
2961
+ const clean = (n) => n + 0;
2962
+ /** The box between two corners. */
2963
+ function rectOf(a, b) {
2964
+ return {
2965
+ x: Math.min(a.x, b.x),
2966
+ y: Math.min(a.y, b.y),
2967
+ width: Math.abs(b.x - a.x),
2968
+ height: Math.abs(b.y - a.y)
2969
+ };
2970
+ }
2971
+ /** Vertices round the ellipse inscribed in `rect`, the first at the top centre, clockwise on the page. */
2972
+ function ring(rect, count, radius) {
2973
+ const cx = rect.x + rect.width / 2;
2974
+ const cy = rect.y + rect.height / 2;
2975
+ return Array.from({ length: count }, (_, i) => {
2976
+ const angle = i * 2 * Math.PI / count;
2977
+ const r = radius(i);
2978
+ return {
2979
+ x: clean(cx + rect.width / 2 * r * Math.sin(angle)),
2980
+ y: clean(cy + rect.height / 2 * r * Math.cos(angle))
2981
+ };
2982
+ });
2983
+ }
2984
+ /** A star's `2 * points` vertices, outer and inner alternating, the first at the top centre. */
2985
+ function starVertices(rect, points, innerRatio = .5) {
2986
+ return ring(rect, Math.max(2, Math.round(points)) * 2, (i) => i % 2 === 0 ? 1 : innerRatio);
2987
+ }
2988
+ /** A regular polygon's vertices on the inscribed ellipse, the first at the top centre. */
2989
+ function polygonVertices(rect, sides) {
2990
+ return ring(rect, Math.max(3, Math.round(sides)), () => 1);
2991
+ }
2992
+ const LINE_KINDS = /* @__PURE__ */ new Set(["line", "arrow"]);
2993
+ /** True for kinds drawn between two endpoints rather than inside a box. */
2994
+ function isLineKind(kind) {
2995
+ return LINE_KINDS.has(kind);
2996
+ }
2997
+ const H = Math.SQRT1_2;
2998
+ /** Unit steps every 45 degrees, counter-clockwise from +x (y up). */
2999
+ const EIGHT_WAYS = [
3000
+ {
3001
+ x: 1,
3002
+ y: 0
3003
+ },
3004
+ {
3005
+ x: H,
3006
+ y: H
3007
+ },
3008
+ {
3009
+ x: 0,
3010
+ y: 1
3011
+ },
3012
+ {
3013
+ x: -H,
3014
+ y: H
3015
+ },
3016
+ {
3017
+ x: -1,
3018
+ y: 0
3019
+ },
3020
+ {
3021
+ x: -H,
3022
+ y: -H
3023
+ },
3024
+ {
3025
+ x: 0,
3026
+ y: -1
3027
+ },
3028
+ {
3029
+ x: H,
3030
+ y: -H
3031
+ }
3032
+ ];
3033
+ /**
3034
+ * Where the drag ends with Shift held: a square or circle for box kinds, the nearest 45 degree
3035
+ * angle for lines.
3036
+ */
3037
+ function constrain(kind, start, end) {
3038
+ const dx = end.x - start.x;
3039
+ const dy = end.y - start.y;
3040
+ if (isLineKind(kind)) {
3041
+ const step = Math.round(Math.atan2(dy, dx) / (Math.PI / 4));
3042
+ const u = EIGHT_WAYS[(step % 8 + 8) % 8];
3043
+ const length = dx * u.x + dy * u.y;
3044
+ return {
3045
+ x: clean(start.x + length * u.x),
3046
+ y: clean(start.y + length * u.y)
3047
+ };
3048
+ }
3049
+ const size = Math.max(Math.abs(dx), Math.abs(dy));
3050
+ return {
3051
+ x: clean(start.x + (dx < 0 ? -size : size)),
3052
+ y: clean(start.y + (dy < 0 ? -size : size))
3053
+ };
3054
+ }
3055
+ /**
3056
+ * The two drag corners of the default-size shape centred on `at`. A line or arrow runs left to
3057
+ * right on the page as the file displays it: along user space turned anticlockwise by the
3058
+ * page's /Rotate `rotation`, which undoes the page's clockwise turn, as a signature is placed.
3059
+ */
3060
+ function defaultEnds(kind, at, rotation = 0) {
3061
+ const half = 36;
3062
+ if (!isLineKind(kind)) return [{
3063
+ x: at.x - half,
3064
+ y: at.y - half
3065
+ }, {
3066
+ x: at.x + half,
3067
+ y: at.y + half
3068
+ }];
3069
+ const rad = rotation * Math.PI / 180;
3070
+ const dx = Math.round(Math.cos(rad)) * half;
3071
+ const dy = Math.round(Math.sin(rad)) * half;
3072
+ return [{
3073
+ x: clean(at.x - dx),
3074
+ y: clean(at.y - dy)
3075
+ }, {
3076
+ x: clean(at.x + dx),
3077
+ y: clean(at.y + dy)
3078
+ }];
3079
+ }
3080
+ /** The annotation a shape kind creates between two points, or `undefined` for a kind without a creator yet. */
3081
+ function shapeInput(kind, page, start, end, opts) {
3082
+ const rect = rectOf(start, end);
3083
+ switch (kind) {
3084
+ case "line": return {
3085
+ type: "line",
3086
+ page,
3087
+ start,
3088
+ end,
3089
+ head: "None",
3090
+ tail: "None"
3091
+ };
3092
+ case "arrow": return {
3093
+ type: "line",
3094
+ page,
3095
+ start,
3096
+ end,
3097
+ tail: "OpenArrow",
3098
+ intent: "LineArrow"
3099
+ };
3100
+ case "rectangle": return {
3101
+ type: "square",
3102
+ page,
3103
+ rect
3104
+ };
3105
+ case "roundedRectangle": return {
3106
+ type: "square",
3107
+ page,
3108
+ rect,
3109
+ cornerRadius: 8
3110
+ };
3111
+ case "ellipse": return {
3112
+ type: "circle",
3113
+ page,
3114
+ rect
3115
+ };
3116
+ case "bubble": {
3117
+ const edge = {
3118
+ x: clean(rect.x + rect.width / 4),
3119
+ y: clean(rect.y)
3120
+ };
3121
+ const callout = [{
3122
+ x: clean(edge.x - BUBBLE_TAIL),
3123
+ y: clean(edge.y - BUBBLE_TAIL)
3124
+ }, edge];
3125
+ return {
3126
+ type: "freetext",
3127
+ page,
3128
+ contents: "",
3129
+ intent: "FreeTextCallout",
3130
+ cornerRadius: 8,
3131
+ width: BUBBLE_WIDTH,
3132
+ ...withCalloutBounds(rect, callout, BUBBLE_WIDTH, void 0),
3133
+ callout
3134
+ };
3135
+ }
3136
+ case "star": return {
3137
+ type: "polygon",
3138
+ page,
3139
+ vertices: starVertices(rect, opts.points)
3140
+ };
3141
+ case "polygon": return {
3142
+ type: "polygon",
3143
+ page,
3144
+ vertices: polygonVertices(rect, opts.sides)
3145
+ };
3146
+ case "loupe": return {
3147
+ type: "loupe",
3148
+ page,
3149
+ rect: rectOf(start, constrain(kind, start, end)),
3150
+ magnification: 2
3151
+ };
3152
+ case "mask":
3153
+ case "ovalMask": return {
3154
+ type: "mask",
3155
+ page,
3156
+ rect,
3157
+ shape: kind === "mask" ? "rect" : "ellipse",
3158
+ dim: DEFAULT_MASK_DIM
3159
+ };
3160
+ default: return;
3161
+ }
3162
+ }
3163
+ //#endregion
3164
+ //#region src/model/recognise.ts
3165
+ /** The score a fit needs before a stroke is tidied into its shape. */
3166
+ const RECOGNISE_THRESHOLD = .8;
3167
+ /** Samples either side of a point that its turn is measured over. */
3168
+ const W = 3;
3169
+ /** Turns, over `2 * W` samples, that make a corner: outward, and back against the loop. */
3170
+ const CONVEX_TURN = 40 * Math.PI / 180;
3171
+ const CONCAVE_TURN = 15 * Math.PI / 180;
3172
+ /** Resampled points along the box diagonal. */
3173
+ const DENSITY = 50;
3174
+ /** A run of path is straight when its chord is at least this share of its length. */
3175
+ const STRAIGHT = .95;
3176
+ /** Corners whose neighbours this straight run through them (a turn under about 23 degrees) go. */
3177
+ const MERGE_STRAIGHT = .98;
3178
+ /** The ends of a closed stroke are within this share of the box diagonal. */
3179
+ const CLOSE_GAP = .25;
3180
+ /** Weights of a line's largest and mean straying from its chord, over its length. */
3181
+ const LINE_MAX = 2;
3182
+ const LINE_MEAN = 2;
3183
+ /** Weight of a polygon side's mean straying from its chord, over its length. */
3184
+ const SIDE_MEAN = 3;
3185
+ const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
3186
+ const clamp01 = (n) => Math.min(Math.max(n, 0), 1);
3187
+ const round = (n) => Math.round(n * 100) / 100 + 0;
3188
+ const pt = (p) => ({
3189
+ x: round(p.x),
3190
+ y: round(p.y)
3191
+ });
3192
+ function boxOf(points) {
3193
+ let minX = Infinity;
3194
+ let minY = Infinity;
3195
+ let maxX = -Infinity;
3196
+ let maxY = -Infinity;
3197
+ for (const p of points) {
3198
+ minX = Math.min(minX, p.x);
3199
+ minY = Math.min(minY, p.y);
3200
+ maxX = Math.max(maxX, p.x);
3201
+ maxY = Math.max(maxY, p.y);
3202
+ }
3203
+ return {
3204
+ x: minX,
3205
+ y: minY,
3206
+ width: maxX - minX,
3207
+ height: maxY - minY
3208
+ };
3209
+ }
3210
+ const diagonal = (r) => Math.hypot(r.width, r.height);
3211
+ function lengthOf(points) {
3212
+ let total = 0;
3213
+ for (let i = 1; i < points.length; i++) total += dist(points[i - 1], points[i]);
3214
+ return total;
3215
+ }
3216
+ /** Points every `spacing` along the path, the first and last included. */
3217
+ function resample(points, spacing) {
3218
+ const out = [points[0]];
3219
+ let carried = 0;
3220
+ let prev = points[0];
3221
+ for (let i = 1; i < points.length; i++) {
3222
+ const next = points[i];
3223
+ let d = dist(prev, next);
3224
+ while (carried + d >= spacing) {
3225
+ const t = (spacing - carried) / d;
3226
+ const q = {
3227
+ x: prev.x + t * (next.x - prev.x),
3228
+ y: prev.y + t * (next.y - prev.y)
3229
+ };
3230
+ out.push(q);
3231
+ prev = q;
3232
+ d = dist(prev, next);
3233
+ carried = 0;
3234
+ }
3235
+ carried += d;
3236
+ prev = next;
3237
+ }
3238
+ const last = points[points.length - 1];
3239
+ if (dist(out[out.length - 1], last) > spacing / 2) out.push(last);
3240
+ else out[out.length - 1] = last;
3241
+ return out;
3242
+ }
3243
+ /** Distance from `p` to the segment `a`–`b`. */
3244
+ function toSegment(p, a, b) {
3245
+ const dx = b.x - a.x;
3246
+ const dy = b.y - a.y;
3247
+ const len2 = dx * dx + dy * dy;
3248
+ const t = len2 === 0 ? 0 : clamp01(((p.x - a.x) * dx + (p.y - a.y) * dy) / len2);
3249
+ return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
3250
+ }
3251
+ /** Path lengths from the first point: `cum[i]` is the length up to point `i`. */
3252
+ function cumulative(points) {
3253
+ const cum = [0];
3254
+ for (let i = 1; i < points.length; i++) cum.push(cum[i - 1] + dist(points[i - 1], points[i]));
3255
+ return cum;
3256
+ }
3257
+ /**
3258
+ * Corner indices of the loop `r` (its last point joins its first), in order round it. A corner
3259
+ * is where the path turns sharply over a few samples: outward by more than `CONVEX_TURN`, or
3260
+ * back against the loop's own direction (a star's inner corner) by more than `CONCAVE_TURN`.
3261
+ */
3262
+ function cornersOf(r) {
3263
+ const n = r.length;
3264
+ if (n < 8) return [];
3265
+ const at = (i) => r[(i % n + n) % n];
3266
+ const direction = Math.sign(winding(r, centroid(r))) || 1;
3267
+ const turns = r.map((p, i) => {
3268
+ const a = at(i - W);
3269
+ const b = at(i + W);
3270
+ const turn = Math.atan2(b.y - p.y, b.x - p.x) - Math.atan2(p.y - a.y, p.x - a.x);
3271
+ return direction * (turn > Math.PI ? turn - 2 * Math.PI : turn < -Math.PI ? turn + 2 * Math.PI : turn);
3272
+ });
3273
+ /** 1 for an outward corner, -1 for an inward one, 0 for none. */
3274
+ const kind = (i) => turns[i] > CONVEX_TURN ? 1 : turns[i] < -CONCAVE_TURN ? -1 : 0;
3275
+ const start = turns.findIndex((_, i) => kind(i) === 0);
3276
+ if (start < 0) return [];
3277
+ const corners = [];
3278
+ let best;
3279
+ for (let k = 0; k <= n; k++) {
3280
+ const i = (start + k) % n;
3281
+ const c = k < n ? kind(i) : 0;
3282
+ if (best !== void 0 && c !== kind(best)) {
3283
+ corners.push(best);
3284
+ best = void 0;
3285
+ }
3286
+ if (c !== 0 && (best === void 0 || Math.abs(turns[i]) > Math.abs(turns[best]))) best = i;
3287
+ }
3288
+ corners.sort((a, b) => a - b);
3289
+ for (let k = 0; corners.length > 1 && k < corners.length;) {
3290
+ const next = (k + 1) % corners.length;
3291
+ if ((corners[next] - corners[k] + n) % n > 6) k++;
3292
+ else corners.splice(Math.abs(turns[corners[k]]) < Math.abs(turns[corners[next]]) ? k : next, 1);
3293
+ }
3294
+ return mergeStraight(r, corners);
3295
+ }
3296
+ /** Drops corners whose neighbours run straight through them, the straightest first. */
3297
+ function mergeStraight(r, corners) {
3298
+ const cum = cumulative(r);
3299
+ const total = cum[cum.length - 1] + dist(r[r.length - 1], r[0]);
3300
+ const arc = (a, b) => b > a ? cum[b] - cum[a] : total - cum[a] + cum[b];
3301
+ const out = [...corners];
3302
+ while (out.length > 3) {
3303
+ let drop = -1;
3304
+ let straightest = MERGE_STRAIGHT;
3305
+ for (let k = 0; k < out.length; k++) {
3306
+ const p = out[(k - 1 + out.length) % out.length];
3307
+ const q = out[(k + 1) % out.length];
3308
+ const a = arc(p, q);
3309
+ const ratio = a === 0 ? 1 : dist(r[p], r[q]) / a;
3310
+ if (ratio > straightest) {
3311
+ straightest = ratio;
3312
+ drop = k;
3313
+ }
3314
+ }
3315
+ if (drop < 0) break;
3316
+ out.splice(drop, 1);
3317
+ }
3318
+ return out;
3319
+ }
3320
+ /** Times the path winds round `c`, signed. */
3321
+ function winding(points, c) {
3322
+ let total = 0;
3323
+ for (let i = 0; i < points.length; i++) {
3324
+ const a = points[i];
3325
+ const b = points[(i + 1) % points.length];
3326
+ let d = Math.atan2(b.y - c.y, b.x - c.x) - Math.atan2(a.y - c.y, a.x - c.x);
3327
+ if (d > Math.PI) d -= 2 * Math.PI;
3328
+ if (d < -Math.PI) d += 2 * Math.PI;
3329
+ total += d;
3330
+ }
3331
+ return total / (2 * Math.PI);
3332
+ }
3333
+ /** Largest and mean distance of `points` from the line through `a` and `b`, over `|ab|`. */
3334
+ function deviation(points, a, b) {
3335
+ const len = dist(a, b);
3336
+ if (len === 0 || points.length === 0) return {
3337
+ max: Infinity,
3338
+ mean: Infinity
3339
+ };
3340
+ let max = 0;
3341
+ let sum = 0;
3342
+ for (const p of points) {
3343
+ const d = Math.abs((b.x - a.x) * (a.y - p.y) - (a.x - p.x) * (b.y - a.y)) / len;
3344
+ max = Math.max(max, d);
3345
+ sum += d;
3346
+ }
3347
+ return {
3348
+ max: max / len,
3349
+ mean: sum / points.length / len
3350
+ };
3351
+ }
3352
+ /** How straight a run from `a` to `b` is: 1 on the chord, falling as the path strays from it. */
3353
+ function straightness(points, a, b) {
3354
+ const dev = deviation(points, a, b);
3355
+ const bend = 1 - dist(a, b) / lengthOf(points);
3356
+ return clamp01(1 - LINE_MAX * dev.max - LINE_MEAN * dev.mean - 2 * bend);
3357
+ }
3358
+ function fitLine(r) {
3359
+ const a = r[0];
3360
+ const b = r[r.length - 1];
3361
+ if (dist(a, b) / lengthOf(r) < .8) return void 0;
3362
+ return {
3363
+ shape: {
3364
+ kind: "line",
3365
+ start: pt(a),
3366
+ end: pt(b)
3367
+ },
3368
+ score: straightness(r, a, b)
3369
+ };
3370
+ }
3371
+ /** An arrow whose head is drawn at the end of `r`: a straight shaft, then a short fold back. */
3372
+ function fitArrow(r) {
3373
+ const from = r.map((p) => dist(p, r[0]));
3374
+ const far = Math.max(...from);
3375
+ let tipAt = from.findIndex((d) => d >= .97 * far);
3376
+ while (tipAt + 1 < r.length && from[tipAt + 1] > from[tipAt]) tipAt++;
3377
+ const shaft = r.slice(0, tipAt + 1);
3378
+ const head = r.slice(tipAt + 1);
3379
+ const tail = r[0];
3380
+ const tip = r[tipAt];
3381
+ const shaftLength = lengthOf(shaft);
3382
+ const headLength = lengthOf([tip, ...head]);
3383
+ if (shaftLength < .6 * (shaftLength + headLength) || headLength < .06 * shaftLength) return void 0;
3384
+ const along = {
3385
+ x: (tip.x - tail.x) / shaftLength,
3386
+ y: (tip.y - tail.y) / shaftLength
3387
+ };
3388
+ const chord = dist(tail, tip);
3389
+ if (chord / shaftLength < STRAIGHT) return void 0;
3390
+ let off = 0;
3391
+ for (const p of head) {
3392
+ if (dist(p, tip) > .4 * chord) return void 0;
3393
+ if ((p.x - tip.x) * along.x + (p.y - tip.y) * along.y > .08 * chord) return void 0;
3394
+ off = Math.max(off, Math.abs((p.x - tip.x) * along.y - (p.y - tip.y) * along.x));
3395
+ }
3396
+ if (off < .04 * chord) return void 0;
3397
+ return {
3398
+ shape: {
3399
+ kind: "arrow",
3400
+ start: pt(tail),
3401
+ end: pt(tip)
3402
+ },
3403
+ score: straightness(shaft, tail, tip)
3404
+ };
3405
+ }
3406
+ /**
3407
+ * The stroke as a loop, evenly spaced all the way round (the gap between its ends bridged), an
3408
+ * overshoot past its start trimmed; undefined when the stroke is open.
3409
+ */
3410
+ function loopOf(r, size, spacing) {
3411
+ const n = r.length;
3412
+ if (n < 8) return void 0;
3413
+ let end = n - 1;
3414
+ for (let i = Math.floor(n / 2); i < n; i++) if (dist(r[i], r[0]) < dist(r[end], r[0])) end = i;
3415
+ if (dist(r[end], r[0]) > CLOSE_GAP * size || n - 1 - end > .25 * n) return void 0;
3416
+ const loop = resample([...r.slice(0, end + 1), r[0]], spacing);
3417
+ loop.pop();
3418
+ return loop;
3419
+ }
3420
+ function fitEllipse(loop, box) {
3421
+ const rx = box.width / 2;
3422
+ const ry = box.height / 2;
3423
+ if (rx === 0 || ry === 0) return void 0;
3424
+ const cx = box.x + rx;
3425
+ const cy = box.y + ry;
3426
+ let sum = 0;
3427
+ for (const p of loop) sum += Math.abs(Math.hypot((p.x - cx) / rx, (p.y - cy) / ry) - 1);
3428
+ const mean = sum / loop.length;
3429
+ return {
3430
+ shape: {
3431
+ kind: "ellipse",
3432
+ rect: {
3433
+ x: round(box.x),
3434
+ y: round(box.y),
3435
+ width: round(box.width),
3436
+ height: round(box.height)
3437
+ }
3438
+ },
3439
+ score: clamp01(1 - 3 * mean)
3440
+ };
3441
+ }
3442
+ /** How closely the loop follows the polygon through `vertices`: 1 on it, falling with distance. */
3443
+ function polygonFit(loop, vertices, size) {
3444
+ let sum = 0;
3445
+ for (const p of loop) {
3446
+ let best = Infinity;
3447
+ for (let i = 0; i < vertices.length; i++) best = Math.min(best, toSegment(p, vertices[i], vertices[(i + 1) % vertices.length]));
3448
+ sum += best;
3449
+ }
3450
+ return clamp01(1 - 12 * sum / loop.length / size);
3451
+ }
3452
+ /** Within `tolerance` radians of horizontal (0) or vertical (1); else -1. */
3453
+ function axisOf(a, b, tolerance) {
3454
+ const angle = Math.abs(Math.atan2(b.y - a.y, b.x - a.x)) % Math.PI;
3455
+ const fromH = Math.min(angle, Math.PI - angle);
3456
+ const fromV = Math.abs(angle - Math.PI / 2);
3457
+ if (fromH <= tolerance) return {
3458
+ axis: 0,
3459
+ off: fromH
3460
+ };
3461
+ if (fromV <= tolerance) return {
3462
+ axis: 1,
3463
+ off: fromV
3464
+ };
3465
+ return {
3466
+ axis: -1,
3467
+ off: Math.PI / 4
3468
+ };
3469
+ }
3470
+ function fitRectangle(vertices, fit) {
3471
+ if (vertices.length !== 4) return void 0;
3472
+ const tolerance = 20 * Math.PI / 180;
3473
+ let worst = 0;
3474
+ for (let i = 0; i < 4; i++) {
3475
+ const side = axisOf(vertices[i], vertices[(i + 1) % 4], tolerance);
3476
+ if (side.axis < 0 || side.axis !== (axisOf(vertices[0], vertices[1], tolerance).axis + i) % 2) return void 0;
3477
+ worst = Math.max(worst, side.off);
3478
+ }
3479
+ const xs = vertices.map((v) => v.x).sort((a, b) => a - b);
3480
+ const ys = vertices.map((v) => v.y).sort((a, b) => a - b);
3481
+ const left = (xs[0] + xs[1]) / 2;
3482
+ const right = (xs[2] + xs[3]) / 2;
3483
+ const bottom = (ys[0] + ys[1]) / 2;
3484
+ const top = (ys[2] + ys[3]) / 2;
3485
+ return {
3486
+ shape: {
3487
+ kind: "rectangle",
3488
+ rect: {
3489
+ x: round(left),
3490
+ y: round(bottom),
3491
+ width: round(right - left),
3492
+ height: round(top - bottom)
3493
+ }
3494
+ },
3495
+ score: clamp01(fit - worst / tolerance / 10)
3496
+ };
3497
+ }
3498
+ /** The shape tool's star of `points` tips round `c`, tips at `radius`, the first at the top. */
3499
+ function regularStar(c, points, radius) {
3500
+ return starVertices({
3501
+ x: c.x - radius,
3502
+ y: c.y - radius,
3503
+ width: 2 * radius,
3504
+ height: 2 * radius
3505
+ }, points).map(pt);
3506
+ }
3507
+ const centroid = (points) => ({
3508
+ x: points.reduce((s, p) => s + p.x, 0) / points.length,
3509
+ y: points.reduce((s, p) => s + p.y, 0) / points.length
3510
+ });
3511
+ /** An outline star: an even number of corners alternating far from and near the centre. */
3512
+ function fitStar(vertices, fit) {
3513
+ const k = vertices.length;
3514
+ if (k % 2 !== 0 || k < 8 || k > 16) return void 0;
3515
+ const c = centroid(vertices);
3516
+ const radii = vertices.map((v) => dist(v, c));
3517
+ const even = radii.filter((_, i) => i % 2 === 0);
3518
+ const odd = radii.filter((_, i) => i % 2 === 1);
3519
+ const [outer, inner] = Math.min(...even) > Math.max(...odd) ? [even, odd] : [odd, even];
3520
+ if (Math.min(...outer) <= Math.max(...inner)) return void 0;
3521
+ const mean = (xs) => xs.reduce((s, x) => s + x, 0) / xs.length;
3522
+ if (mean(inner) / mean(outer) > .75) return void 0;
3523
+ const spread = (Math.max(...outer) - Math.min(...outer)) / mean(outer);
3524
+ return {
3525
+ shape: {
3526
+ kind: "star",
3527
+ vertices: regularStar(c, k / 2, mean(outer))
3528
+ },
3529
+ score: clamp01(fit - Math.max(0, spread - .2))
3530
+ };
3531
+ }
3532
+ /** A pentagram: five straight strokes that wind twice round the centre. */
3533
+ function fitPentagram(vertices, loop, size) {
3534
+ if (vertices.length !== 5) return void 0;
3535
+ const c = centroid(vertices);
3536
+ const turns = Math.abs(winding(loop, c));
3537
+ if (turns < 1.6 || turns > 2.4) return void 0;
3538
+ const radii = vertices.map((v) => dist(v, c));
3539
+ const mean = radii.reduce((s, x) => s + x, 0) / radii.length;
3540
+ const spread = (Math.max(...radii) - Math.min(...radii)) / mean;
3541
+ return {
3542
+ shape: {
3543
+ kind: "star",
3544
+ vertices: regularStar(c, 5, mean)
3545
+ },
3546
+ score: clamp01(polygonFit(loop, vertices, size) - Math.max(0, spread - .2))
3547
+ };
3548
+ }
3549
+ /** True when two sides of the polygon through `v` cross. */
3550
+ function crosses(v) {
3551
+ const k = v.length;
3552
+ const side = (a, b, c) => Math.sign((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x));
3553
+ for (let i = 0; i < k; i++) for (let j = i + 2; j < k; j++) {
3554
+ if (i === 0 && j === k - 1) continue;
3555
+ const [a, b, c, d] = [
3556
+ v[i],
3557
+ v[(i + 1) % k],
3558
+ v[j],
3559
+ v[(j + 1) % k]
3560
+ ];
3561
+ if (side(a, b, c) * side(a, b, d) < 0 && side(c, d, a) * side(c, d, b) < 0) return true;
3562
+ }
3563
+ return false;
3564
+ }
3565
+ /** How straight the loop runs between consecutive corners: the worst side's score. */
3566
+ function sidesFit(loop, corners) {
3567
+ let worst = 1;
3568
+ for (let k = 0; k < corners.length; k++) {
3569
+ const from = corners[k];
3570
+ const to = corners[(k + 1) % corners.length];
3571
+ const side = to > from ? loop.slice(from, to + 1) : [...loop.slice(from), ...loop.slice(0, to + 1)];
3572
+ const a = side[0];
3573
+ const b = side[side.length - 1];
3574
+ const bend = 1 - dist(a, b) / lengthOf(side);
3575
+ worst = Math.min(worst, clamp01(1 - SIDE_MEAN * deviation(side, a, b).mean - 2 * bend));
3576
+ }
3577
+ return worst;
3578
+ }
3579
+ function fitClosed(loop, size) {
3580
+ const box = boxOf(loop);
3581
+ const fits = [];
3582
+ const corners = cornersOf(loop);
3583
+ const vertices = corners.map((i) => loop[i]);
3584
+ const pentagram = fitPentagram(vertices, loop, size);
3585
+ if (pentagram) fits.push(pentagram);
3586
+ const turns = Math.abs(winding(loop, {
3587
+ x: box.x + box.width / 2,
3588
+ y: box.y + box.height / 2
3589
+ }));
3590
+ if (turns < .8 || turns > 1.25) return fits;
3591
+ const ellipse = fitEllipse(loop, box);
3592
+ if (ellipse) fits.push(ellipse);
3593
+ if (vertices.length < 3 || crosses(vertices)) return fits;
3594
+ const fit = polygonFit(loop, vertices, size);
3595
+ const rectangle = fitRectangle(vertices, fit);
3596
+ if (rectangle) fits.push(rectangle);
3597
+ else if (vertices.length <= 8) fits.push({
3598
+ shape: {
3599
+ kind: "polygon",
3600
+ vertices: vertices.map(pt)
3601
+ },
3602
+ score: Math.min(fit, sidesFit(loop, corners))
3603
+ });
3604
+ const star = fitStar(vertices, fit);
3605
+ if (star) fits.push(star);
3606
+ return fits;
3607
+ }
3608
+ /**
3609
+ * The standard shape a single freehand stroke (user space points, in drawing order) is closest
3610
+ * to, and how well it fits, from 0 to 1. Tidy the stroke only when the score reaches
3611
+ * `RECOGNISE_THRESHOLD`. Undefined when no shape fits at all.
3612
+ */
3613
+ function recogniseStroke(points) {
3614
+ const clean = points.filter((p, i) => Number.isFinite(p.x) && Number.isFinite(p.y) && (i === 0 || p.x !== points[i - 1].x || p.y !== points[i - 1].y));
3615
+ if (clean.length < 2) return void 0;
3616
+ const size = diagonal(boxOf(clean));
3617
+ if (size === 0) return void 0;
3618
+ const spacing = Math.max(size / DENSITY, lengthOf(clean) / 1e3);
3619
+ const r = resample(clean, spacing);
3620
+ if (r.length < 2) return void 0;
3621
+ const fits = [];
3622
+ const line = fitLine(r);
3623
+ if (line) fits.push(line);
3624
+ const loop = loopOf(r, size, spacing);
3625
+ if (loop) fits.push(...fitClosed(loop, size));
3626
+ else for (const f of [fitArrow(r), fitArrow([...r].reverse())]) if (f) fits.push(f);
3627
+ let best;
3628
+ for (const f of fits) if (!best || f.score > best.score) best = f;
3629
+ return best && {
3630
+ shape: best.shape,
3631
+ score: round(best.score)
3632
+ };
3633
+ }
3634
+ //#endregion
3635
+ //#region src/model/signatures.ts
3636
+ /** How wide a placed signature is, in points. */
3637
+ const DEFAULT_SIGNATURE_WIDTH = 150;
3638
+ /** A placed ink signature's stroke width, in points. */
3639
+ const SIGNATURE_INK_WIDTH = 2;
3640
+ const Aspect = z.number().positive().finite();
3641
+ const TemplateSchema = z.discriminatedUnion("kind", [z.object({
3642
+ id: z.string().min(1),
3643
+ kind: z.literal("ink"),
3644
+ inklist: z.array(z.array(PointSchema).min(1)).min(1),
3645
+ pressure: z.array(z.array(z.number().min(0).max(1))).optional(),
3646
+ aspect: Aspect
3647
+ }), z.object({
3648
+ id: z.string().min(1),
3649
+ kind: z.literal("image"),
3650
+ imagedata: z.string().regex(IMAGE_DATA_URL),
3651
+ aspect: Aspect
3652
+ })]).refine((t) => t.kind !== "ink" || !t.pressure || t.pressure.length === t.inklist.length && t.pressure.every((p, i) => p.length === t.inklist[i]?.length), {
3653
+ message: "pressure must have the same shape as inklist",
3654
+ path: ["pressure"]
3655
+ });
3656
+ /** The items that are valid templates; the rest are skipped. */
3657
+ function validTemplates(items) {
3658
+ return items.flatMap((item) => {
3659
+ const t = TemplateSchema.safeParse(item);
3660
+ return t.success ? [t.data] : [];
3661
+ });
3662
+ }
3663
+ const copy = (t) => JSON.parse(JSON.stringify(t));
3664
+ function upsert(list, t) {
3665
+ const i = list.findIndex((x) => x.id === t.id);
3666
+ return i < 0 ? [...list, copy(t)] : list.map((x, j) => j === i ? copy(t) : x);
3667
+ }
3668
+ /** Templates in memory, gone on reload. The default when a host passes no store. */
3669
+ function createMemorySignatureStore(initial = []) {
3670
+ let items = initial.map(copy);
3671
+ return {
3672
+ list: () => Promise.resolve(items.map(copy)),
3673
+ save(t) {
3674
+ items = upsert(items, t);
3675
+ return Promise.resolve();
3676
+ },
3677
+ remove(id) {
3678
+ items = items.filter((x) => x.id !== id);
3679
+ return Promise.resolve();
3680
+ }
3681
+ };
3682
+ }
3683
+ /**
3684
+ * Templates in `localStorage` under `key`, as a JSON array. Where storage is blocked (it refuses
3685
+ * even a tiny test write, as in some private windows) the templates stay in memory for the
3686
+ * page's life, so signing still works. Where storage works, or is full but holds a saved list,
3687
+ * and has no room for a change, the change is undone and `save` or `remove` rejects, so the host can say so. Stored entries it
3688
+ * cannot read, such as a later version's templates, are left out of `list` and kept on write.
3689
+ */
3690
+ function createLocalSignatureStore(key) {
3691
+ /** Usable storage, or undefined when it is missing or blocked. */
3692
+ const storage = (() => {
3693
+ try {
3694
+ const s = globalThis.localStorage ?? void 0;
3695
+ if (!s) return void 0;
3696
+ const probe = `${key}:probe`;
3697
+ try {
3698
+ s.setItem(probe, "1");
3699
+ s.removeItem(probe);
3700
+ } catch {
3701
+ return s.getItem(key) === null ? void 0 : s;
3702
+ }
3703
+ return s;
3704
+ } catch {
3705
+ return;
3706
+ }
3707
+ })();
3708
+ /** The stored list; undefined when storage cannot be read. */
3709
+ const read = () => {
3710
+ if (!storage) return void 0;
3711
+ try {
3712
+ const raw = storage.getItem(key);
3713
+ if (raw === null) return {
3714
+ items: [],
3715
+ unread: []
3716
+ };
3717
+ const parsed = JSON.parse(raw);
3718
+ if (!Array.isArray(parsed)) return {
3719
+ items: [],
3720
+ unread: []
3721
+ };
3722
+ return {
3723
+ items: validTemplates(parsed),
3724
+ unread: parsed.filter((x) => validTemplates([x]).length === 0)
3725
+ };
3726
+ } catch (e) {
3727
+ return e instanceof SyntaxError ? {
3728
+ items: [],
3729
+ unread: []
3730
+ } : void 0;
3731
+ }
3732
+ };
3733
+ let { items, unread } = read() ?? {
3734
+ items: [],
3735
+ unread: []
3736
+ };
3737
+ /** Picks up what another tab wrote. */
3738
+ const sync = () => {
3739
+ const stored = read();
3740
+ if (stored) ({items, unread} = stored);
3741
+ };
3742
+ /** The id of an entry that may not be a template, if it has one. */
3743
+ const idOf = (x) => typeof x === "object" && x !== null ? x.id : void 0;
3744
+ /**
3745
+ * Writes `next`, then adopts it; leaves everything as it was when storage refuses. Entries
3746
+ * it cannot read go back after the templates, less any whose id a template now has.
3747
+ */
3748
+ const commit = (next) => {
3749
+ const ids = new Set(next.map((t) => t.id));
3750
+ const kept = unread.filter((x) => idOf(x) === void 0 || !ids.has(idOf(x)));
3751
+ if (storage) try {
3752
+ storage.setItem(key, JSON.stringify([...next, ...kept]));
3753
+ } catch (cause) {
3754
+ return Promise.reject(new Error("The signature could not be saved: browser storage is full", { cause }));
3755
+ }
3756
+ items = next;
3757
+ unread = kept;
3758
+ return Promise.resolve();
3759
+ };
3760
+ return {
3761
+ list() {
3762
+ sync();
3763
+ return Promise.resolve(items.map(copy));
3764
+ },
3765
+ save(t) {
3766
+ sync();
3767
+ return commit(upsert(items, t));
3768
+ },
3769
+ remove(id) {
3770
+ sync();
3771
+ return commit(items.filter((x) => x.id !== id));
3772
+ }
3773
+ };
3774
+ }
3775
+ /**
3776
+ * Fits strokes into a unit box, for an ink template. Points come in any y-up space; they go
3777
+ * out between 0 and 1 on both axes, and `aspect` is the box's width over its height. A flat
3778
+ * side is given 1% of the long side (a dot, a square), so the aspect stays finite, and the
3779
+ * strokes are centred across it.
3780
+ */
3781
+ function normaliseInk(inklist) {
3782
+ const all = inklist.flat();
3783
+ const xs = all.map((p) => p.x);
3784
+ const ys = all.map((p) => p.y);
3785
+ const minX = Math.min(...xs);
3786
+ const minY = Math.min(...ys);
3787
+ const w = Math.max(...xs) - minX;
3788
+ const h = Math.max(...ys) - minY;
3789
+ const long = Math.max(w, h);
3790
+ const boxW = long === 0 ? 1 : Math.max(w, long * .01);
3791
+ const boxH = long === 0 ? 1 : Math.max(h, long * .01);
3792
+ const map = (p) => ({
3793
+ x: (p.x - minX + (boxW - w) / 2) / boxW,
3794
+ y: (p.y - minY + (boxH - h) / 2) / boxH
3795
+ });
3796
+ return {
3797
+ inklist: inklist.map((path) => path.map(map)),
3798
+ aspect: boxW / boxH
3799
+ };
3800
+ }
3801
+ /**
3802
+ * An ink template from strokes in any y-up space, with a new id. Throws a RangeError for no
3803
+ * strokes, an empty stroke, or pressure that does not have one value per point.
3804
+ */
3805
+ function createInkTemplate(inklist, pressure) {
3806
+ if (inklist.length === 0 || inklist.some((path) => path.length === 0)) throw new RangeError("A signature needs at least one stroke, and no empty strokes");
3807
+ if (pressure && (pressure.length !== inklist.length || pressure.some((p, i) => p.length !== inklist[i].length))) throw new RangeError("pressure must have the same shape as inklist");
3808
+ const fitted = normaliseInk(inklist);
3809
+ return {
3810
+ id: v7(),
3811
+ kind: "ink",
3812
+ inklist: fitted.inklist,
3813
+ ...pressure ? { pressure: pressure.map((p) => [...p]) } : {},
3814
+ aspect: fitted.aspect
3815
+ };
3816
+ }
3817
+ /** An image template, with a new id. Throws a TypeError unless `imagedata` is a PNG or JPEG data URL. */
3818
+ function createImageTemplate(imagedata, aspect) {
3819
+ if (!IMAGE_DATA_URL.test(imagedata)) throw new TypeError("A signature image must be a PNG or JPEG data URL");
3820
+ if (!(aspect > 0 && Number.isFinite(aspect))) throw new RangeError(`aspect must be positive, got ${aspect}`);
3821
+ return {
3822
+ id: v7(),
3823
+ kind: "image",
3824
+ imagedata,
3825
+ aspect
3826
+ };
3827
+ }
3828
+ /**
3829
+ * The annotation that places `t` on `page`, `width` points wide on screen and centred on
3830
+ * `centre` (user space). `rotation` is the page's /Rotate (clockwise): the signature is turned
3831
+ * back by as much, so it reads upright on the page as the file displays it. A viewer's view
3832
+ * rotation is left out; it turns the signature with the page like any annotation. Ink becomes `ink` with `subject: 'Signature'`, its strokes inset by half their
3833
+ * width; an image becomes a `stamp` with `subject: 'Signature'`.
3834
+ */
3835
+ function placeSignature(t, page, centre, width = 150, rotation = 0) {
3836
+ const height = width / t.aspect;
3837
+ const sideways = rotation === 90 || rotation === 270;
3838
+ const rw = sideways ? height : width;
3839
+ const rh = sideways ? width : height;
3840
+ const rect = {
3841
+ x: centre.x - rw / 2,
3842
+ y: centre.y - rh / 2,
3843
+ width: rw,
3844
+ height: rh
3845
+ };
3846
+ if (t.kind === "image") return {
3847
+ type: "stamp",
3848
+ page,
3849
+ subject: "Signature",
3850
+ imagedata: t.imagedata,
3851
+ rect,
3852
+ ...rotation === 0 ? {} : { rotation }
3853
+ };
3854
+ const innerW = Math.max(width - 2, 0);
3855
+ const innerH = Math.max(height - 2, 0);
3856
+ const rad = rotation * Math.PI / 180;
3857
+ const cos = Math.round(Math.cos(rad));
3858
+ const sin = Math.round(Math.sin(rad));
3859
+ const place = (p) => {
3860
+ const u = (p.x - .5) * innerW;
3861
+ const v = (p.y - .5) * innerH;
3862
+ return {
3863
+ x: centre.x + u * cos - v * sin,
3864
+ y: centre.y + u * sin + v * cos
3865
+ };
3866
+ };
3867
+ return {
3868
+ type: "ink",
3869
+ page,
3870
+ subject: "Signature",
3871
+ inklist: t.inklist.map((path) => path.map(place)),
3872
+ ...t.pressure ? { pressure: t.pressure.map((p) => [...p]) } : {},
3873
+ width: 2,
3874
+ rect
3875
+ };
3876
+ }
3877
+ function createSignatureLibrary(store) {
3878
+ const templates = writable([]);
3879
+ const removeError = writable(void 0);
3880
+ /**
3881
+ * The newest load that succeeded writes, so a slow one cannot undo a later save, and a later
3882
+ * one that fails does not throw away a slow success.
3883
+ */
3884
+ let loads = 0;
3885
+ let applied = 0;
3886
+ const refresh = async () => {
3887
+ const n = ++loads;
3888
+ try {
3889
+ const list = validTemplates(await store.list());
3890
+ if (n > applied) {
3891
+ applied = n;
3892
+ templates.set(list);
3893
+ }
3894
+ } catch {}
3895
+ };
3896
+ return {
3897
+ store,
3898
+ templates: readonly(templates),
3899
+ get: (id) => templates.get().find((t) => t.id === id),
3900
+ refresh,
3901
+ async save(t) {
3902
+ await store.save(t);
3903
+ await refresh();
3904
+ },
3905
+ async remove(id) {
3906
+ removeError.set(void 0);
3907
+ try {
3908
+ await store.remove(id);
3909
+ } catch (e) {
3910
+ removeError.set("The signature could not be removed. Try again.");
3911
+ throw e;
3912
+ }
3913
+ await refresh();
3914
+ },
3915
+ removeError: readonly(removeError),
3916
+ clearRemoveError: () => removeError.set(void 0)
3917
+ };
3918
+ }
3919
+ //#endregion
3920
+ export { exportAnnotations as $, derived as $t, fromAnnotation as A, RedactSchema as At, isBubble as B, isStandardCallout as Bt, repliesTo as C, NoteSchema as Ct, acceptSuggestion as D, PolylineSchema as Dt, withoutReplies as E, PolygonSchema as Et, toFields as F, TextMarkupSchema as Ft, resizedBox as G, PDF_NAME as Gt, keepsAspect as H, INTENTS as Ht, typesInGroup as I, confidenceBucket as It, translated as J, parsePdfDate as Jt, resizedRect as K, isKnown as Kt, hasCallout as L, FringeSchema as Lt, styleGroupOfType as M, SquareSchema as Mt, styleGroupsOf as N, StampSchema as Nt, STYLE_GROUPS as O, QuadSchema as Ot, supportedProps as P, SuggestionSchema as Pt, deriveRect as Q, mergeLineRects as Qt, hasCornerHandles as R, calloutStroke as Rt, isThreadRoot as S, NoteIconSchema as St, threadRoot as T, PolySchema as Tt, movedEndpoint as U, LINE_ENDINGS as Ut, isTextMarkup as V, withCalloutBounds as Vt, movedTip as W, NOTE_ICONS as Wt, openDocument as X, normalizeColor as Xt, withBox as Y, cssVariableDefaults as Yt, createAnnotationStore as Z, staticDefaults as Zt, defaultEnds as _, InkError as _n, InkSchema as _t, createLocalSignatureStore as a, multiplyMatrix as an, importedId as at, isAbandonedNote as b, LoupeSchema as bt, normaliseInk as c, quadsFromFlat as cn, ANNOTATION_FORMAT as ct, recogniseStroke as d, rectFromQuad as dn, AnnotationSchema as dt, readonly as en, importAnnotations as et, DEFAULT_CORNER_RADIUS as f, rectsIntersect as fn, CircleSchema as ft, constrain as g, Emitter as gn, IMAGE_DATA_URL as gt, SHAPE_KINDS as h, unionRects as hn, FreeTextStyleSchema as ht, createInkTemplate as i, invertMatrix as in, importEmbeddedPage as it, styleGroupOf as j, ShapeSchema as jt, createToolStyle as k, RectSchema as kt, placeSignature as l, rectContainsPoint as ln, ANNOTATION_VERSION as lt, DEFAULT_SHAPE_SIZE as m, translateRect as mn, FreeTextSchema as mt, SIGNATURE_INK_WIDTH as n, applyMatrix as nn, isProduction as nt, createMemorySignatureStore as o, pointsFromFlat as on, pdfColorToHex as ot, DEFAULT_SHAPE_OPTIONS as p, translateQuad as pn, ExportedAnnotationSchema as pt, scaled as q, pdfNameSet as qt, createImageTemplate as r, approxEqual as rn, SUPPORTED_SUBTYPES as rt, createSignatureLibrary as s, quadFromRect as sn, summarise as st, DEFAULT_SIGNATURE_WIDTH as t, writable as tn, createHistory as tt, RECOGNISE_THRESHOLD as u, rectFromPoints as un, AnnotationDocumentSchema as ut, isPointerOnlyKind as v, isInkError as vn, LineEndingSchema as vt, threadOf as w, PointSchema as wt, isReply as x, MaskSchema as xt, shapeInput as y, LineSchema as yt, hasRectGeometry as z, freeTextBox as zt };
3921
+
3922
+ //# sourceMappingURL=signatures-DF2VmNVa.mjs.map