@embedpdf/plugin-annotation 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/contract/host.cjs +2 -2
  2. package/dist/contract/host.d.cts +3 -3
  3. package/dist/contract/host.d.ts +3 -3
  4. package/dist/contract/host.js +2 -2
  5. package/dist/{contract-OwgW3JE8.js → contract-BrvLUGi2.js} +73 -80
  6. package/dist/contract-BrvLUGi2.js.map +1 -0
  7. package/dist/{contract-BK2g1Rem.d.ts → contract-CQfRsCVj.d.ts} +89 -17
  8. package/dist/{contract-CBYEqnev.d.cts → contract-DkxvCGXL.d.cts} +89 -17
  9. package/dist/{contract-BtAl3Yo2.cjs → contract-X3gZNpwu.cjs} +78 -79
  10. package/dist/contract-X3gZNpwu.cjs.map +1 -0
  11. package/dist/contract.cjs +1 -1
  12. package/dist/contract.d.cts +2 -2
  13. package/dist/contract.d.ts +2 -2
  14. package/dist/contract.js +1 -1
  15. package/dist/{host-contract-COF2Prd-.d.ts → host-contract-BSH_muud.d.cts} +35 -6
  16. package/dist/{host-contract-BzM2upsA.cjs → host-contract-C7vx6wTQ.cjs} +2 -2
  17. package/dist/host-contract-C7vx6wTQ.cjs.map +1 -0
  18. package/dist/{host-contract-CSKiuu3g.js → host-contract-CDp5skzD.js} +2 -2
  19. package/dist/host-contract-CDp5skzD.js.map +1 -0
  20. package/dist/{host-contract-CxOrR_pp.d.cts → host-contract-DU3CxFE1.d.ts} +35 -6
  21. package/dist/index.cjs +486 -80
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +3 -3
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +488 -82
  26. package/dist/index.js.map +1 -1
  27. package/package.json +12 -12
  28. package/dist/contract-BtAl3Yo2.cjs.map +0 -1
  29. package/dist/contract-OwgW3JE8.js.map +0 -1
  30. package/dist/host-contract-BzM2upsA.cjs.map +0 -1
  31. package/dist/host-contract-CSKiuu3g.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { a as buildToolRegistry, c as AnnotationToken, i as DEFAULT_TOOLS, n as AnnotationTransfer, o as toolTouchOf, r as ARMED_STAMP_TOOL_ID, s as annotationState, t as ANNOTATION_DEFAULTS } from "./contract-OwgW3JE8.js";
2
- import { n as previewBucket, t as AnnotationToken$1 } from "./host-contract-CSKiuu3g.js";
1
+ import { a as applyTool, c as annotationState, i as DEFAULT_TOOLS, l as AnnotationToken, n as AnnotationTransfer, o as buildToolRegistry, r as ARMED_STAMP_TOOL_ID, s as toolTouchOf, t as ANNOTATION_DEFAULTS } from "./contract-BrvLUGi2.js";
2
+ import { n as previewBucket, t as AnnotationToken$1 } from "./host-contract-CDp5skzD.js";
3
3
  import { widgetAppearanceOf } from "./authoring.js";
4
4
  import { PluginError, annotationKey, composeApi, definePlugin, memo, pageRefsEqual, reload, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
5
5
  import { ActionsToken, createHoverPump } from "@embedpdf/plugin-actions/contract";
@@ -7,8 +7,8 @@ import { FontsToken } from "@embedpdf/plugin-fonts/contract";
7
7
  import { InteractionToken } from "@embedpdf/plugin-interaction/contract/host";
8
8
  import { RenderToken } from "@embedpdf/plugin-render/contract";
9
9
  import { SelectionToken } from "@embedpdf/plugin-selection/contract/host";
10
- import { ANNOTATION_FIELD_NAMES, STANDARD_FACES, anchorOf, annotationKey as annotationKey$1, annotationPatchBetween, buildCommentThreads, colorOf, compareIsoDateTime, deletedWith, faceForFontName, familyKey, fontNameForFace, imageSourceOfBytes, isDimension, isLocalEngine, isReadout, measurementReadout, pageBoxOf, reorderPart, reorderedList, resolveAnnotationPatch, resolveBinarySource, serializeError, sniffBinaryMetadata, standardFontForFace, toPageRef, viewportForPoint } from "@embedpdf/engine-core/runtime";
11
- import { MIN_DRAG, anchorModeOf, anchoredGeometry, annotContentsEditable, annotDeletable, annotTransformable, annotationAfter, annotationAnchor, annotationOfNew, applyStyleToRange, canMove, chrome, creationDraftAnchor, cursorAt, defaultsFor, drawnAfter, drawsLive, expandGroups, faceForFont, fitStampBox, fromDTO, gesturePlacement, gesturePlacement as gesturePlacement$1, groupKeyOf, groupOf, hitTest, initialSession, initialTextStyle, isContentsEditableByHand, isDrag, isEditableByHand, isOnTextBox, isSelectable, isSubstrateOnly, isTransformableByHand, kindNamed, kindNamed as kindNamed$1, kindOf, linkChildRects, linkChildrenOf, linkOf, locateOffset, newRecordsAtMost, pageItems, placedShape, propertiesOf, propertiesOf as propertiesOf$1, readOfDefaults, refOf, resolveClickPlacement, resolveClickPlacement as resolveClickPlacement$1, richDocOf, richTextLength, rotationAnchor, sameSession, selectionAnchor, selectionInBox, selectionProperties, shapeOf, sourceOfConfirmed, sourceOfNew, styleAt, styleOf, textBoxOf, textBoxes, textOf, textPlateInset, toolAnnotation, typeWithStyle, unanchoredGeometry, unmadeItem, update, uprightRotation, viewable, writableTarget } from "@embedpdf/core-annotation";
10
+ import { ANNOTATION_FIELD_NAMES, STANDARD_FACES, anchorOf, annotationKey as annotationKey$1, annotationPatchBetween, buildCommentThreads, colorOf, compareIsoDateTime, deletedWith, faceForFontName, familyKey, fontNameForFace, imageSourceOfBytes, isDimension, isLocalEngine, isReadout, measurementReadout, pageBoxOf, planAnnotationCopies, reorderPart, reorderedList, resolveAnnotationPatch, resolveBinarySource, serializeError, sniffBinaryMetadata, standardFontForFace, toPageRef, viewportForPoint } from "@embedpdf/engine-core/runtime";
11
+ import { MIN_DRAG, anchorModeOf, anchoredGeometry, annotContentsEditable, annotDeletable, annotTransformable, annotationAfter, annotationAnchor, annotationOfNew, applyStyleToRange, canMove, chrome, creationDraftAnchor, cursorAt, defaultsFor, drawnAfter, drawsLive, expandGroups, faceForFont, fitStampBox, fromDTO, gesturePlacement, gesturePlacement as gesturePlacement$1, groupKeyOf, groupOf, hitTest, initialSession, initialTextStyle, isContentsEditableByHand, isDrag, isEditableByHand, isMovable, isOnTextBox, isSelectable, isSubstrateOnly, isTransformableByHand, kindNamed, kindNamed as kindNamed$1, kindOf, linkChildRects, linkChildrenOf, linkOf, locateOffset, newRecordsAtMost, pageItems, placedShape, propertiesOf, propertiesOf as propertiesOf$1, readOfDefaults, refOf, resolveClickPlacement, resolveClickPlacement as resolveClickPlacement$1, richDocOf, richTextLength, rotationAnchor, sameSession, selectionAnchor, selectionInBox, selectionProperties, shapeOf, sourceOfConfirmed, sourceOfNew, styleAt, styleOf, textBoxOf, textBoxes, textOf, textPlateInset, toolAnnotation, typeWithStyle, unanchoredGeometry, unmadeItem, update, uprightRotation, viewable, writableTarget } from "@embedpdf/core-annotation";
12
12
  import { ActionsToken as ActionsToken$1 } from "@embedpdf/plugin-actions/contract/host";
13
13
  import { RenderToken as RenderToken$1 } from "@embedpdf/plugin-render/contract/host";
14
14
  import { standardFontCss, standardFontOf, standardFontOfProgramFamily } from "@embedpdf/core-fonts";
@@ -894,6 +894,11 @@ function createAnnotationReads(ctx, { store, records, lending }) {
894
894
  const record = model.byId[annotationKey$1(ref)];
895
895
  return !!record && isEditableByHand(model, record.annotation);
896
896
  };
897
+ /** Whether it is an annotation people move: its kind moves, and it doesn't sit on text. */
898
+ const isMovable$1 = (ref) => {
899
+ const record = store.model().byId[annotationKey$1(ref)];
900
+ return !!record && isMovable(record);
901
+ };
897
902
  return {
898
903
  get,
899
904
  listAnnots,
@@ -907,7 +912,8 @@ function createAnnotationReads(ctx, { store, records, lending }) {
907
912
  list,
908
913
  isPending,
909
914
  getHovered,
910
- isEditable
915
+ isEditable,
916
+ isMovable: isMovable$1
911
917
  }
912
918
  };
913
919
  }
@@ -1527,10 +1533,10 @@ function programsOf(id, doc, body, bodyPrograms, text) {
1527
1533
  * areas, and the baked-appearance seam (epoch and pictures). The engine's
1528
1534
  * pictures come through the render plugin, which shares and keeps them. A
1529
1535
  * stamp this session placed shows the preview it was placed with until the
1530
- * engine's picture of it exists, and an annotation an undo brings back the
1531
- * picture it had.
1536
+ * engine's picture of it exists, an annotation an undo brings back the
1537
+ * picture it had, and a copy of a stamp its original's.
1532
1538
  */
1533
- function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLookup, textFonts }, ghost, stamps) {
1539
+ function createRenderReads(ctx, { view: { pageModel }, lending, records, copySources, fonts: fontLookup, textFonts }, ghost, stamps) {
1534
1540
  const itemsCache = /* @__PURE__ */ new Map();
1535
1541
  const fonts = () => ctx.tryGet(FontsToken);
1536
1542
  /**
@@ -1675,8 +1681,9 @@ function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLooku
1675
1681
  * annotations the engine draws on it, each at its picture version
1676
1682
  * (`pictureVersion`, which advances when the engine confirms a re-bake).
1677
1683
  * `placed`: the stamps this session placed that the engine hasn't written
1678
- * yet, which show the preview they were placed with, and the records an
1679
- * undo brought back, which show the pictures kept of them. Position,
1684
+ * yet, which show the preview they were placed with (`previewOf`), and
1685
+ * the records an undo brought back or a copy made, which show the pictures
1686
+ * kept of them or of their original (`keptOf`). Position,
1680
1687
  * rotation and the state shown are absent: the blit translates (`apBox`)
1681
1688
  * and turns (`apRot`) the same pixels, and every state is held, so a move,
1682
1689
  * a spin or a switch costs no new picture. `lent`: the lender's epoch for
@@ -1693,8 +1700,8 @@ function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLooku
1693
1700
  if (!record || record.annotation.page.objectNumber !== pageObjectNumber || record.source !== "baked") continue;
1694
1701
  if (isSubstrateOnly(record)) continue;
1695
1702
  if (record.unconfirmed) {
1696
- if (stamps.lookOf(record)) placed.push(`${id}@placed`);
1697
- else if (keptOf(id, record.annotation.ref).length) placed.push(`${id}@kept`);
1703
+ if (previewOf(record)) placed.push(`${id}@placed`);
1704
+ else if (keptOf(record).length) placed.push(`${id}@kept`);
1698
1705
  continue;
1699
1706
  }
1700
1707
  if (lending.owns(id)) {
@@ -1734,8 +1741,64 @@ function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLooku
1734
1741
  };
1735
1742
  /** The family whose pictures a record's are: the lender's widgets, or annotations. */
1736
1743
  const familyOf = (id) => lending.owns(id) ? "widgets" : "annotations";
1737
- /** The engine's last pictures of a record, kept a while after it left its page. */
1738
- const keptOf = (id, ref) => ctx.tryGet(RenderToken$1)?.getKeptAppearances(familyOf(id), ref) ?? [];
1744
+ /**
1745
+ * The annotations a copy the engine hasn't written stands in for, nearest
1746
+ * first: the one it copies, then, while that one is such a copy too, the
1747
+ * one behind it, and last the source noted when the copy was staged
1748
+ * (services/copy-sources.ts), which still holds once the engine wrote a
1749
+ * copy in between. A copy of a copy finds its look this way.
1750
+ */
1751
+ const originalsOf = (id) => {
1752
+ const { byKey } = records.view();
1753
+ const originals = [];
1754
+ const seen = /* @__PURE__ */ new Set([id]);
1755
+ let next = byKey[id]?.copyOf;
1756
+ while (next && !seen.has(annotationKey$1(next))) {
1757
+ seen.add(annotationKey$1(next));
1758
+ originals.push(next);
1759
+ next = byKey[annotationKey$1(next)]?.copyOf;
1760
+ }
1761
+ const noted = copySources.of(id);
1762
+ if (noted && !seen.has(annotationKey$1(noted))) originals.push(noted);
1763
+ return originals;
1764
+ };
1765
+ /**
1766
+ * The preview a record the engine hasn't written shows: the one it was
1767
+ * placed with (a stamp this session placed), or, for a copy of a stamp
1768
+ * that is still being placed, that stamp's.
1769
+ */
1770
+ const previewOf = (record) => {
1771
+ const own = stamps.lookOf(record);
1772
+ if (own || !record.unconfirmed) return own;
1773
+ for (const original of originalsOf(record.id)) {
1774
+ const placed = pageModel(original.page.objectNumber).byId[annotationKey$1(original)];
1775
+ const look = placed ? stamps.lookOf(placed) : null;
1776
+ if (look) return look;
1777
+ }
1778
+ return null;
1779
+ };
1780
+ /**
1781
+ * The pictures a record the engine hasn't written shows when it has no
1782
+ * live drawing: the engine's last pictures of it, kept a while after it
1783
+ * left its page (an undo brings it back), or, for a copy, the ones of the
1784
+ * annotation it copies, where the copy is.
1785
+ */
1786
+ const keptOf = (record) => {
1787
+ const render = ctx.tryGet(RenderToken$1);
1788
+ if (!render) return [];
1789
+ const { ref } = record.annotation;
1790
+ const own = render.getKeptAppearances(familyOf(record.id), ref);
1791
+ if (own.length) return own;
1792
+ for (const original of originalsOf(record.id)) {
1793
+ const kept = render.getKeptAppearances("annotations", original);
1794
+ if (kept.length) return kept.map((each) => ({
1795
+ ...each,
1796
+ ref,
1797
+ rect: record.apBox ?? each.rect
1798
+ }));
1799
+ }
1800
+ return [];
1801
+ };
1739
1802
  /**
1740
1803
  * The pictures of what shows on `page` that the engine hasn't written yet:
1741
1804
  * a stamp this session placed shows its preview, at the size the page shows
@@ -1748,8 +1811,8 @@ function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLooku
1748
1811
  const record = model.byId[id];
1749
1812
  if (!record.unconfirmed) return [];
1750
1813
  const version = record.pictureVersion ?? 0;
1751
- const look = stamps.lookOf(record);
1752
- if (!look) return keptOf(id, record.annotation.ref).map((kept) => ({
1814
+ const look = previewOf(record);
1815
+ if (!look) return keptOf(record).map((kept) => ({
1753
1816
  ...kept,
1754
1817
  version
1755
1818
  }));
@@ -1813,11 +1876,29 @@ function createAuthority(ctx, store) {
1813
1876
  }).map((member) => member.ref);
1814
1877
  };
1815
1878
  const canDelete = (ref) => blockersOf(ref).length === 0;
1879
+ /**
1880
+ * Whether a person may copy these annotations: the right to create, each
1881
+ * one here and copied whole by the engine's own rule
1882
+ * (`planAnnotationCopies`), and none locked. A copy of a locked annotation
1883
+ * is locked too, so a person could neither move nor delete it.
1884
+ */
1885
+ const canDuplicate = (refs) => {
1886
+ if (!refs.length || !canCreate()) return false;
1887
+ const model = store.model();
1888
+ const sources = [];
1889
+ for (const ref of refs) {
1890
+ const annotation = model.byId[annotationKey$1(ref)]?.annotation;
1891
+ if (!annotation || annotation.locked) return false;
1892
+ sources.push(annotation);
1893
+ }
1894
+ return planAnnotationCopies(sources, {}).dropped.length === 0;
1895
+ };
1816
1896
  return {
1817
1897
  canRead,
1818
1898
  canCreate,
1819
1899
  canUpdate,
1820
1900
  canDelete,
1901
+ canDuplicate,
1821
1902
  blockersOf,
1822
1903
  allowsMutation
1823
1904
  };
@@ -2087,6 +2168,19 @@ const NO_RECORDS$1 = [];
2087
2168
  const sameItems = (left, right) => left.length === right.length && left.every((item, index) => Object.is(item, right[index]));
2088
2169
  const samePageParts = (left, right) => sameItems(left.records, right.records) && sameItems(left.selected, right.selected) && left.hovered === right.hovered && left.editing === right.editing && left.draft === right.draft && left.preview === right.preview && sameItems(left.settings, right.settings);
2089
2170
  //#endregion
2171
+ //#region src/services/copy-sources.ts
2172
+ function createCopySources(records) {
2173
+ const sources = /* @__PURE__ */ new Map();
2174
+ return {
2175
+ note(copies) {
2176
+ const { byKey } = records.view();
2177
+ for (const key of sources.keys()) if (!(key in byKey)) sources.delete(key);
2178
+ for (const { ref, of } of copies) sources.set(annotationKey$1(ref), sources.get(annotationKey$1(of)) ?? of);
2179
+ },
2180
+ of: (id) => sources.get(id) ?? null
2181
+ };
2182
+ }
2183
+ //#endregion
2090
2184
  //#region src/services/events.ts
2091
2185
  /**
2092
2186
  * The plugin's events. Record events (created, updated, deleted, reordered,
@@ -2471,6 +2565,54 @@ function annotationOfCreate(draft, ref) {
2471
2565
  };
2472
2566
  }
2473
2567
  /**
2568
+ * The copies a copy makes, each with the annotation it copies: the engine's
2569
+ * own rule (`planAnnotationCopies`) over the records, and each copy read as
2570
+ * a create of the same data is (`annotationOfCreate`). None for a copy the
2571
+ * engine numbers itself, which has no keys to show its copies by, and none
2572
+ * when the engine would refuse it (an annotation it names is gone).
2573
+ */
2574
+ function copiesOf(records, op) {
2575
+ const { objectNumbers } = op;
2576
+ if (!objectNumbers || objectNumbers.length !== op.refs.length) return [];
2577
+ const sources = [];
2578
+ for (const ref of op.refs) {
2579
+ const stored = records.byKey[annotationKey$1(ref)];
2580
+ if (!stored) return [];
2581
+ sources.push(stored.dto);
2582
+ }
2583
+ const { copies } = planAnnotationCopies(sources, {
2584
+ ...op.page ? { page: op.page } : {},
2585
+ ...op.offset ? { offset: op.offset } : {}
2586
+ });
2587
+ const refs = copies.map((copy) => ({
2588
+ kind: "objectNumber",
2589
+ page: copy.page,
2590
+ objectNumber: objectNumbers[copy.source]
2591
+ }));
2592
+ return copies.map((copy, at) => {
2593
+ const draft = {
2594
+ ...copy.data,
2595
+ ...copy.replyTo ? { reply: {
2596
+ to: refs[copy.replyTo.copy],
2597
+ type: copy.replyTo.type
2598
+ } } : {},
2599
+ ...copy.parent !== void 0 ? { parent: refs[copy.parent] } : {}
2600
+ };
2601
+ let read;
2602
+ try {
2603
+ read = annotationOfCreate(draft, refs[at]);
2604
+ } catch {
2605
+ read = null;
2606
+ }
2607
+ return {
2608
+ ref: refs[at],
2609
+ copy: read,
2610
+ of: sources[copy.source].ref,
2611
+ source: copy.source
2612
+ };
2613
+ });
2614
+ }
2615
+ /**
2474
2616
  * The record keys of one page in a new drawing order: `keys` moved to
2475
2617
  * `position` among the page's others, in the order given, as the engine
2476
2618
  * reorders. Other pages keep their places. Unchanged when the engine would
@@ -2531,6 +2673,23 @@ function predictRecords(records, op) {
2531
2673
  order
2532
2674
  };
2533
2675
  }
2676
+ case "annotations.copy": {
2677
+ const made = copiesOf(records, op).flatMap(({ copy, of }) => copy && !(annotationKey$1(copy.ref) in records.byKey) ? [{
2678
+ copy,
2679
+ of
2680
+ }] : []);
2681
+ if (!made.length) return records;
2682
+ const byKey = { ...records.byKey };
2683
+ for (const { copy, of } of made) byKey[annotationKey$1(copy.ref)] = {
2684
+ dto: copy,
2685
+ pictureVersion: 0,
2686
+ copyOf: of
2687
+ };
2688
+ return {
2689
+ byKey,
2690
+ order: [...records.order, ...made.map(({ copy }) => annotationKey$1(copy.ref))]
2691
+ };
2692
+ }
2534
2693
  case "annotations.restore": {
2535
2694
  const key = annotationKey$1(op.annotation.ref);
2536
2695
  if (key in records.byKey) return records;
@@ -2594,6 +2753,10 @@ function undoOfOp(records, op) {
2594
2753
  index
2595
2754
  }] : []);
2596
2755
  }
2756
+ case "annotations.copy": return copiesOf(records, op).map(({ ref }) => ({
2757
+ type: "annotations.delete",
2758
+ ref
2759
+ }));
2597
2760
  case "annotations.reorder": return [{
2598
2761
  type: "annotations.reorder",
2599
2762
  page: op.page,
@@ -2654,6 +2817,8 @@ function createRecordsMirror(ctx, events) {
2654
2817
  * update; the deletes another delete covers; the records it names and what it
2655
2818
  * is called. Pure functions.
2656
2819
  */
2820
+ /** The annotations a stated copy copies: the ones it names, then what comes along. */
2821
+ const copiedBy = (change) => change.along?.length ? [...change.refs, ...change.along] : change.refs;
2657
2822
  /**
2658
2823
  * A stated change as its op, as given: what an op builder adds for changes
2659
2824
  * worked out in the engine's terms (a link's children).
@@ -2682,12 +2847,19 @@ const opOfStated = (change) => {
2682
2847
  refs: change.refs,
2683
2848
  position: change.position
2684
2849
  };
2850
+ case "copy": return {
2851
+ type: "annotations.copy",
2852
+ refs: copiedBy(change),
2853
+ ...change.page ? { page: change.page } : {},
2854
+ ...change.offset ? { offset: change.offset } : {}
2855
+ };
2685
2856
  }
2686
2857
  };
2687
2858
  /** The record keys an op names. */
2688
2859
  const keysOf = (op) => {
2689
2860
  switch (op.type) {
2690
2861
  case "annotations.create": return op.objectNumber === void 0 ? [] : [`obj:${op.objectNumber}`];
2862
+ case "annotations.copy": return (op.objectNumbers ?? []).map((objectNumber) => `obj:${objectNumber}`);
2691
2863
  case "annotations.update":
2692
2864
  case "annotations.delete": return [annotationKey$1(op.ref)];
2693
2865
  case "annotations.reorder": return op.refs.map(annotationKey$1);
@@ -2700,8 +2872,15 @@ const keysOf = (op) => {
2700
2872
  /** The records a change names, each once. */
2701
2873
  const idsOf = (ops) => [...new Set(ops.flatMap(keysOf))];
2702
2874
  /**
2703
- * What a change is called, from what it does: one kind of op (`annotation.move`,
2704
- * or a lent record's own, `form.updateWidget`), or several (`annotation.change`).
2875
+ * The verb of this plugin that makes an op, where the engine names the op
2876
+ * differently: `duplicate()` makes copies, and the page plugin calls its own
2877
+ * `pages.duplicate`.
2878
+ */
2879
+ const LABEL_VERBS = { "annotations.copy": "duplicate" };
2880
+ /**
2881
+ * What a change is called, from what it does: one kind of op, by the verb
2882
+ * that makes it (`annotation.update`, `annotation.duplicate`, or a lent
2883
+ * record's own, `form.updateWidget`), or several (`annotation.change`).
2705
2884
  * History and refusals show it.
2706
2885
  */
2707
2886
  const labelOf = (ops) => {
@@ -2709,7 +2888,7 @@ const labelOf = (ops) => {
2709
2888
  const [only] = kinds;
2710
2889
  const [plane, verb] = kinds.size === 1 && only ? only.split(".") : ["annotations", "change"];
2711
2890
  return {
2712
- key: `${plane === "annotations" ? "annotation" : plane === "forms" ? "form" : plane}.${verb}`,
2891
+ key: `${plane === "annotations" ? "annotation" : plane === "forms" ? "form" : plane}.${(kinds.size === 1 && only ? LABEL_VERBS[only] : void 0) ?? verb}`,
2713
2892
  count: idsOf(ops).length
2714
2893
  };
2715
2894
  };
@@ -2770,6 +2949,35 @@ function modelAfter(before, result) {
2770
2949
  };
2771
2950
  }
2772
2951
  const notFound = (ref) => new PluginError("not-found", "annotation", `no annotation ${annotationKey$1(ref)}`);
2952
+ /** How many object numbers stated changes take: one per create, and one per annotation a copy copies. */
2953
+ const numbersFor = (changes) => changes.reduce((count, change) => count + (change.type === "create" ? 1 : change.type === "copy" ? copiedBy(change).length : 0), 0);
2954
+ /**
2955
+ * A stated copy as its op, with an object number for each annotation it
2956
+ * copies, so the copies show at once under them. `ids`: the copies of the
2957
+ * annotations it names, in their order (one the engine leaves out has none),
2958
+ * each by the object number it gets, whether it shows before the engine
2959
+ * answers or not; `live`: the copies that draw live from now on; `copies`:
2960
+ * every copy it makes, each with the annotation it copies. Throws for an
2961
+ * annotation the view doesn't have.
2962
+ */
2963
+ function checkedCopyOf(change, current, taken) {
2964
+ const refs = copiedBy(change);
2965
+ for (const ref of refs) if (!(annotationKey$1(ref) in current.byKey)) throw notFound(ref);
2966
+ const op = {
2967
+ type: "annotations.copy",
2968
+ refs,
2969
+ ...change.page ? { page: change.page } : {},
2970
+ ...change.offset ? { offset: change.offset } : {},
2971
+ objectNumbers: taken.splice(0, refs.length)
2972
+ };
2973
+ const copies = copiesOf(current, op);
2974
+ return {
2975
+ ids: copies.filter(({ source }) => source < change.refs.length).map(({ ref }) => annotationKey$1(ref)),
2976
+ op,
2977
+ live: copies.flatMap(({ copy }) => copy && sourceOfNew(copy) === "vector" ? [annotationKey$1(copy.ref)] : []),
2978
+ copies
2979
+ };
2980
+ }
2773
2981
  /**
2774
2982
  * One stated change as its op, resolved by the engine's own rules against
2775
2983
  * `current`: what shows is what the engine will write, and a change those
@@ -2873,7 +3081,7 @@ const NOTHING_WRITTEN = {
2873
3081
  result: null
2874
3082
  };
2875
3083
  const noNumbers = () => new PluginError("not-ready", "annotation", "the document holds no object number for a new annotation right now");
2876
- function createStore(ctx, view, records, events, lending) {
3084
+ function createStore(ctx, view, records, events, lending, copySources) {
2877
3085
  let followUp = null;
2878
3086
  const builders = /* @__PURE__ */ new Map();
2879
3087
  const model = view.model;
@@ -2886,7 +3094,7 @@ function createStore(ctx, view, records, events, lending) {
2886
3094
  kind: "objectNumber",
2887
3095
  page: op.page,
2888
3096
  objectNumber: op.objectNumber
2889
- }] : op.type === "annotations.update" || op.type === "annotations.delete" ? [op.ref] : op.type === "forms.updateWidget" || op.type === "forms.deleteWidget" ? [op.widget] : op.type === "annotations.reorder" ? [...op.refs] : op.type === "forms.reorderWidgets" ? [...op.widgets] : []);
3097
+ }] : op.type === "annotations.update" || op.type === "annotations.delete" ? [op.ref] : op.type === "annotations.copy" ? [...op.refs] : op.type === "forms.updateWidget" || op.type === "forms.deleteWidget" ? [op.widget] : op.type === "annotations.reorder" ? [...op.refs] : op.type === "forms.reorderWidgets" ? [...op.widgets] : []);
2890
3098
  events.writeFailed.emit({
2891
3099
  refs,
2892
3100
  error: toPluginErrorInfo(settled.error)
@@ -2907,11 +3115,11 @@ function createStore(ctx, view, records, events, lending) {
2907
3115
  * Stage this plugin's ops and its lender's as one change. Undoing it undoes
2908
3116
  * the lent ops first: they come last.
2909
3117
  */
2910
- const stage = (ops, before, lent = []) => {
3118
+ const stage = (ops, before, lent = [], label) => {
2911
3119
  const all = [...ops, ...lent];
2912
3120
  const undo = [...lent.length ? lending.lender()?.undoOf(lent) ?? [] : [], ...undoOf(before, ops)];
2913
3121
  const change = ctx.changes.stage({
2914
- label: labelOf(all),
3122
+ label: label ?? labelOf(all),
2915
3123
  ops: all,
2916
3124
  undo
2917
3125
  });
@@ -3010,8 +3218,8 @@ function createStore(ctx, view, records, events, lending) {
3010
3218
  };
3011
3219
  const apply = (changes, options = {}) => {
3012
3220
  const shown = records.view();
3013
- const creates = changes.filter((change) => change.type === "create").length;
3014
- const taken = creates ? numbers.take(creates) : [];
3221
+ const needed = numbersFor(changes);
3222
+ const taken = needed ? numbers.take(needed) : [];
3015
3223
  if (!taken) throw noNumbers();
3016
3224
  const ops = [];
3017
3225
  /** Lent records reordered: their lender's ops, last in the change. */
@@ -3020,10 +3228,23 @@ function createStore(ctx, view, records, events, lending) {
3020
3228
  const opIndex = [];
3021
3229
  const ids = [];
3022
3230
  const vector = [];
3231
+ /** The copies the change makes, each with the annotation it copies. */
3232
+ const copied = [];
3023
3233
  let current = shown;
3024
3234
  try {
3025
3235
  for (const stated of changes) {
3026
3236
  if (stated.type === "update" || stated.type === "delete") refuseLent(lending, stated.ref);
3237
+ if (stated.type === "copy") {
3238
+ for (const ref of [...stated.refs, ...stated.along ?? []]) refuseLent(lending, ref);
3239
+ const copy = checkedCopyOf(stated, current, taken);
3240
+ ids.push(...copy.ids);
3241
+ opIndex.push(ops.length);
3242
+ ops.push(copy.op);
3243
+ vector.push(...copy.live);
3244
+ copied.push(...copy.copies);
3245
+ current = predictRecords(current, copy.op);
3246
+ continue;
3247
+ }
3027
3248
  const change = stated.type === "reorder" ? ownReorder(lending, stated, lent) : stated;
3028
3249
  if (!change) {
3029
3250
  ids.push(annotationKey$1(stated.refs[0]));
@@ -3041,6 +3262,10 @@ function createStore(ctx, view, records, events, lending) {
3041
3262
  } catch (error) {
3042
3263
  throw toPluginError("annotation", error);
3043
3264
  }
3265
+ if (options.lent) {
3266
+ lent.push(...options.lent.ops);
3267
+ ids.push(...options.lent.ids);
3268
+ }
3044
3269
  if (!ops.length && !lent.length) return {
3045
3270
  ids,
3046
3271
  written: Promise.resolve({
@@ -3057,13 +3282,26 @@ function createStore(ctx, view, records, events, lending) {
3057
3282
  }
3058
3283
  }));
3059
3284
  const selected = model().selected;
3060
- const change = stage(withoutCoveredDeletes(shown, [...ops, ...following.ops]), shown, lent);
3285
+ copySources.note(copied);
3286
+ const change = stage(withoutCoveredDeletes(shown, [...ops, ...following.ops]), shown, lent, options.label);
3061
3287
  selections.remember(change.opId, selected, options.select ? ids : selected);
3062
3288
  if (vector.length) ctx.state.update(withSession, ctx.state.get().session, vector);
3063
- if (options.select) commit({
3064
- type: "select",
3065
- ids
3066
- });
3289
+ if (options.select) {
3290
+ commit({
3291
+ type: "select",
3292
+ ids
3293
+ });
3294
+ if (ids.some((id) => !(id in model().byId))) {
3295
+ const staged = model().selected;
3296
+ const selectLate = () => {
3297
+ if (sameIds(model().selected, staged)) commit({
3298
+ type: "select",
3299
+ ids
3300
+ });
3301
+ };
3302
+ change.result.then(selectLate, () => {});
3303
+ }
3304
+ }
3067
3305
  return {
3068
3306
  ids,
3069
3307
  written: writtenOf(change, idsOf([...ops, ...lent])).then((outcome) => ({
@@ -3076,8 +3314,8 @@ function createStore(ctx, view, records, events, lending) {
3076
3314
  };
3077
3315
  };
3078
3316
  const applyWhenNumbered = async (changes, options) => {
3079
- const creates = changes.filter((change) => change.type === "create").length;
3080
- while (!numbers.hold(creates)) await ctx.changes.reserveObjectNumbers(creates);
3317
+ const needed = numbersFor(changes);
3318
+ while (!numbers.hold(needed)) await ctx.changes.reserveObjectNumbers(needed);
3081
3319
  return apply(changes, options);
3082
3320
  };
3083
3321
  ctx.watch(view.view, (next, previous) => {
@@ -3396,12 +3634,10 @@ function createBehaviors(store) {
3396
3634
  * The resolved tool table (built-ins + the `tools` setting). A tool is a named
3397
3635
  * authoring preset: it maps its id → a routing subtype, a `defaults` key
3398
3636
  * (`preset`), the kind whose properties it shows, and, for stamps, a source
3399
- * spec. The setting's tools are kept so `tools.register` can re-resolve
3400
- * `extends` against the same base pool.
3637
+ * spec. `tools.register` applies one more entry to the same table.
3401
3638
  */
3402
3639
  function createToolRegistry(ctx, settingTools, store, events) {
3403
- const configTools = [...settingTools];
3404
- const registry = buildToolRegistry(configTools);
3640
+ const registry = buildToolRegistry(settingTools);
3405
3641
  for (const tool of registry.values()) if (tool.defaults) store.commit({
3406
3642
  type: "setDefaults",
3407
3643
  preset: tool.preset,
@@ -3484,24 +3720,60 @@ function createToolRegistry(ctx, settingTools, store, events) {
3484
3720
  }
3485
3721
  return hit;
3486
3722
  };
3723
+ /** Put `tool` on the hub, in place of any tool with its id. */
3724
+ const registerOnHub = (tool) => {
3725
+ const { id, cursor, enables } = tool;
3726
+ const hubTool = {
3727
+ id,
3728
+ cursor,
3729
+ enables,
3730
+ touch: toolTouchOf(enables)
3731
+ };
3732
+ return ctx.tryGet(InteractionToken)?.registerTool(hubTool, { replace: true });
3733
+ };
3734
+ /**
3735
+ * The registrations in place, per tool id, oldest first, each with the tool
3736
+ * it replaced. Removing the newest puts that tool back; removing an older one
3737
+ * hands what it replaced to the one after it. So removals in any order end
3738
+ * with the tool the first registration replaced.
3739
+ */
3740
+ const registrations = /* @__PURE__ */ new Map();
3487
3741
  const register = (definition) => {
3488
- const resolved = buildToolRegistry([...configTools, definition]).get(definition.id);
3489
- if (!resolved) throw new Error(`[annotation] could not resolve tool '${definition.id}'`);
3490
- registry.set(resolved.id, resolved);
3491
- const un = ctx.tryGet(InteractionToken)?.registerTool({
3492
- id: resolved.id,
3493
- cursor: resolved.cursor,
3494
- enables: resolved.enables,
3495
- touch: toolTouchOf(resolved.enables)
3496
- }, { replace: true });
3497
- if (resolved.defaults) store.commit({
3742
+ const replaced = registry.get(definition.id);
3743
+ const tool = applyTool(registry, definition);
3744
+ const unregister = registerOnHub(tool);
3745
+ if (tool.defaults) store.commit({
3498
3746
  type: "setDefaults",
3499
- preset: resolved.preset,
3500
- patch: resolved.defaults
3747
+ preset: tool.preset,
3748
+ patch: tool.defaults
3501
3749
  });
3750
+ const registration = { replaced };
3751
+ registrations.set(tool.id, [...registrations.get(tool.id) ?? [], registration]);
3502
3752
  return () => {
3503
- registry.delete(resolved.id);
3504
- un?.();
3753
+ const stack = registrations.get(tool.id) ?? [];
3754
+ const at = stack.indexOf(registration);
3755
+ if (at < 0) return;
3756
+ const rest = stack.filter((other) => other !== registration);
3757
+ if (rest.length) registrations.set(tool.id, rest);
3758
+ else registrations.delete(tool.id);
3759
+ const newer = stack[at + 1];
3760
+ if (newer) {
3761
+ newer.replaced = registration.replaced;
3762
+ return;
3763
+ }
3764
+ const previous = registration.replaced;
3765
+ if (!previous) {
3766
+ registry.delete(tool.id);
3767
+ unregister?.();
3768
+ return;
3769
+ }
3770
+ registry.set(previous.id, previous);
3771
+ registerOnHub(previous);
3772
+ store.commit({
3773
+ type: "replaceDefaults",
3774
+ preset: previous.preset,
3775
+ defaults: previous.defaults ?? {}
3776
+ });
3505
3777
  };
3506
3778
  };
3507
3779
  return {
@@ -3591,7 +3863,8 @@ function createServices(ctx) {
3591
3863
  const records = createRecordsMirror(ctx, events);
3592
3864
  const lending = createLending(() => ctx.notify());
3593
3865
  const view = createView(ctx, records, lending);
3594
- const store = createStore(ctx, view, records, events, lending);
3866
+ const copySources = createCopySources(records);
3867
+ const store = createStore(ctx, view, records, events, lending, copySources);
3595
3868
  const tools = createToolRegistry(ctx, settings.get().tools, store, events);
3596
3869
  const fonts = createFontLookup(ctx);
3597
3870
  return {
@@ -3600,6 +3873,7 @@ function createServices(ctx) {
3600
3873
  records,
3601
3874
  view,
3602
3875
  lending,
3876
+ copySources,
3603
3877
  store,
3604
3878
  geometry,
3605
3879
  authority: createAuthority(ctx, store),
@@ -3963,14 +4237,16 @@ function createGhost(ctx, { store, geometry, tools }, stamps) {
3963
4237
  //#endregion
3964
4238
  //#region src/write/crud.ts
3965
4239
  /**
3966
- * Create, update, delete and reorder: the public verbs, in the engine's own
3967
- * terms, and the transfers (export, import, a resource's bytes). Each change
3968
- * states itself through `store.apply`, so it shows at once and is sent,
3969
- * answered and refused exactly like a gesture's, and each resolves with what
3970
- * the engine wrote for it: its own change's answer, never another change
3971
- * still on its way.
4240
+ * Create, update, delete, reorder and duplicate: the public verbs, in the
4241
+ * engine's own terms, and the transfers (export, import, a resource's
4242
+ * bytes). Each change states itself through `store.apply`, so it shows at
4243
+ * once and is sent, answered and refused exactly like a gesture's, and each
4244
+ * resolves with what the engine wrote for it: its own change's answer, never
4245
+ * another change still on its way. An import is a change too: the engine's
4246
+ * own verb makes it, so it is staged on the document's queue as that verb's
4247
+ * call.
3972
4248
  */
3973
- function createCrud(ctx, { store, tools, records }, annotations, settle) {
4249
+ function createCrud(ctx, { store, tools, records, lending }, annotations, settle) {
3974
4250
  /** The annotation `ref` names, as the view holds it: for a change that wrote nothing. */
3975
4251
  const current = (ref) => {
3976
4252
  const annotation = annotations.get(ref);
@@ -4050,6 +4326,68 @@ function createCrud(ctx, { store, tools, records }, annotations, settle) {
4050
4326
  position
4051
4327
  }])));
4052
4328
  };
4329
+ /**
4330
+ * Copies of annotations in this document, which the engine makes in one
4331
+ * op: they show at once, and it is one step to undo. An annotation's
4332
+ * attached link is a child of it, so it is copied along. A link `refs`
4333
+ * names itself is copied once, as one of the copies named.
4334
+ *
4335
+ * `lent` are the selection's lent records (a form's widgets, in design
4336
+ * mode), which only the selection's own duplicate passes: their lender
4337
+ * says which ops copy them, and those join the same change, so a
4338
+ * selection of both kinds is one step. Their copies are among the
4339
+ * annotations it resolves; what their lender left out is its own to tell.
4340
+ */
4341
+ const duplicate = async (refs, options = {}, lent = []) => {
4342
+ if (refs.length || !lent.length) ctx.assertAllowed("annotations:create", "annotation.duplicate");
4343
+ if (!refs.length && !lent.length) return {
4344
+ annotations: [],
4345
+ dropped: []
4346
+ };
4347
+ const page = options.page === void 0 ? void 0 : ctx.pageOf(options.page).ref;
4348
+ const placement = {
4349
+ ...page ? { page } : {},
4350
+ ...options.offset ? { offset: options.offset } : {}
4351
+ };
4352
+ const lender = lent.length ? lending.lender() : null;
4353
+ const lentCopy = lender ? await lender.copyOps(lent, placement) : null;
4354
+ const model = store.model();
4355
+ const stated = new Set(refs.map(annotationKey$1));
4356
+ const along = refs.flatMap((ref) => linkChildrenOf(model, annotationKey$1(ref)).map((child) => child.annotation.ref).filter((child) => !stated.has(annotationKey$1(child))));
4357
+ const lentIds = lentCopy?.copies.map(annotationKey$1) ?? [];
4358
+ const applied = await store.applyWhenNumbered(refs.length ? [{
4359
+ type: "copy",
4360
+ refs,
4361
+ ...along.length ? { along } : {},
4362
+ ...placement
4363
+ }] : [], {
4364
+ select: options.select,
4365
+ ...lentCopy ? {
4366
+ lent: {
4367
+ ops: lentCopy.ops,
4368
+ ids: lentIds
4369
+ },
4370
+ label: {
4371
+ key: refs.length ? "annotation.duplicate" : `${lender.owner}.duplicate`,
4372
+ count: refs.length + lentIds.length
4373
+ }
4374
+ } : {}
4375
+ });
4376
+ const items = (await ctx.cancellable(options.signal, appliedOrThrow(applied))).result?.items ?? [];
4377
+ const copied = items.find((item) => item.type === "annotations.copy");
4378
+ if (refs.length && copied?.type !== "annotations.copy") throw new PluginError("operation-failed", "annotation", "the annotations could not be copied");
4379
+ const named = new Set(applied.ids);
4380
+ const own = copied?.type === "annotations.copy" ? copied.annotations.filter((copy) => named.has(annotationKey$1(copy.ref))) : [];
4381
+ const rows = /* @__PURE__ */ new Map();
4382
+ for (const item of items) {
4383
+ const made = item.type === "forms.copy" || item.type === "forms.addWidget" ? item.widgets : item.type === "forms.updateWidget" ? [item.widget] : [];
4384
+ for (const row of made) rows.set(annotationKey$1(row.ref), row);
4385
+ }
4386
+ return {
4387
+ annotations: [...own, ...lentIds.flatMap((id) => rows.get(id) ?? [])],
4388
+ dropped: copied?.type === "annotations.copy" ? copied.dropped : []
4389
+ };
4390
+ };
4053
4391
  /** The pages a selection names, as refs: an index becomes its page's ref. */
4054
4392
  const pageRefsOf = (pages) => pages?.map((page) => ctx.pageOf(page).ref);
4055
4393
  const exportBundle = async (selection = {}, options = {}) => {
@@ -4063,13 +4401,28 @@ function createCrud(ctx, { store, tools, records }, annotations, settle) {
4063
4401
  };
4064
4402
  const importBundle = async (bundle, options = {}) => {
4065
4403
  ctx.assertAllowed("annotations:create", "annotation.import");
4066
- const { signal, ...importOptions } = options;
4067
- const result = await ctx.cancellable(signal, ctx.doc.annotations.import(bundle, importOptions));
4404
+ const { signal, history, ...importOptions } = options;
4405
+ const { items } = await ctx.changes.stage({
4406
+ label: { key: "annotation.import" },
4407
+ opId: importOptions.opId,
4408
+ history,
4409
+ send: (doc, { opId }) => ctx.cancellable(signal, doc.annotations.import(bundle, {
4410
+ ...importOptions,
4411
+ opId
4412
+ })).then((result) => ({
4413
+ items: [{
4414
+ type: "annotations.import",
4415
+ ...result
4416
+ }],
4417
+ meta: result.meta
4418
+ }))
4419
+ }).result;
4420
+ const imported = items[0];
4068
4421
  await records.settled();
4069
4422
  return {
4070
- annotations: result.annotations,
4071
- refMap: result.refMap,
4072
- dropped: result.dropped
4423
+ annotations: imported.annotations,
4424
+ refMap: imported.refMap,
4425
+ dropped: imported.dropped
4073
4426
  };
4074
4427
  };
4075
4428
  const downloadResource = async (ref, role, options = {}) => {
@@ -4079,11 +4432,13 @@ function createCrud(ctx, { store, tools, records }, annotations, settle) {
4079
4432
  };
4080
4433
  return {
4081
4434
  update,
4435
+ duplicate,
4082
4436
  api: {
4083
4437
  create,
4084
4438
  update,
4085
4439
  delete: remove,
4086
4440
  reorder,
4441
+ duplicate,
4087
4442
  export: exportBundle,
4088
4443
  import: importBundle,
4089
4444
  downloadResource
@@ -4434,7 +4789,7 @@ function createMarkupWrites(ctx, { store, authority, tools, afterCreate }, annot
4434
4789
  * measurement plugin supplies for dimension drafts, and recalibration of a
4435
4790
  * page's dimensions to a new scale.
4436
4791
  */
4437
- function createMeasurement(ctx, { store, records }, crud) {
4792
+ function createMeasurement(ctx, { store, records }) {
4438
4793
  const pageViewports = /* @__PURE__ */ new Map();
4439
4794
  ctx.cleanup(() => {
4440
4795
  pageViewports.clear();
@@ -4448,10 +4803,11 @@ function createMeasurement(ctx, { store, records }, crud) {
4448
4803
  fallback
4449
4804
  });
4450
4805
  },
4451
- remeasurePage: async (page, scale) => {
4452
- const pageObjectNumber = page.objectNumber;
4806
+ whenRemeasurable: async () => {
4453
4807
  if (records.getStatus() !== "ready") await records.refresh().catch(() => {});
4454
4808
  await records.settled();
4809
+ },
4810
+ stageRemeasure: (page, scale) => {
4455
4811
  const report = {
4456
4812
  page,
4457
4813
  scale,
@@ -4466,11 +4822,12 @@ function createMeasurement(ctx, { store, records }, crud) {
4466
4822
  const model = store.model();
4467
4823
  const candidates = Object.values(records.get().byKey).flatMap(({ dto }) => {
4468
4824
  const record = model.byId[annotationKey$1(dto.ref)];
4469
- return record && dto.page.objectNumber === pageObjectNumber && isDimension(dto) ? [{
4825
+ return record && dto.page.objectNumber === page.objectNumber && isDimension(dto) ? [{
4470
4826
  dto,
4471
4827
  annotation: record
4472
4828
  }] : [];
4473
4829
  });
4830
+ const updates = [];
4474
4831
  for (const { dto, annotation } of candidates) {
4475
4832
  const ref = dto.ref;
4476
4833
  const reason = annotation.authority?.update === false ? "no-authority" : !annotTransformable(annotation) || !annotContentsEditable(annotation) ? "locked" : "measure" in dto && dto.measure && dto.measure.subtype !== "rectilinear" ? "foreign-measure" : !isReadout(measurementReadout({
@@ -4484,19 +4841,17 @@ function createMeasurement(ctx, { store, records }, crud) {
4484
4841
  });
4485
4842
  continue;
4486
4843
  }
4487
- try {
4488
- await crud.update(ref, {
4844
+ updates.push({
4845
+ type: "update",
4846
+ ref,
4847
+ patch: {
4489
4848
  subtype: dto.subtype,
4490
4849
  measure: scale
4491
- });
4492
- report.updated.push(ref);
4493
- } catch (error) {
4494
- report.failed.push({
4495
- ref,
4496
- error: serializeError(error)
4497
- });
4498
- }
4850
+ }
4851
+ });
4852
+ report.updated.push(ref);
4499
4853
  }
4854
+ if (updates.length > 0) store.apply(updates);
4500
4855
  return report;
4501
4856
  }
4502
4857
  }
@@ -4841,13 +5196,44 @@ function createScriptEffects(ctx, { store, geometry }) {
4841
5196
  }
4842
5197
  //#endregion
4843
5198
  //#region src/write/selection.ts
5199
+ /** How far a duplicate lands from its original, in page points. */
5200
+ const DUPLICATE_OFFSET = 10;
4844
5201
  /**
4845
5202
  * The selection: what is selected, and the verbs that change its fields,
4846
- * link, delete, rotate, group and ungroup it as one, every member through the
4847
- * same `update → patch effect` path a gesture takes. Each verb is one change.
5203
+ * link, delete, rotate, group, ungroup and duplicate it as one, every member
5204
+ * through the same `update → patch effect` path a gesture takes. Each verb is
5205
+ * one change.
4848
5206
  */
4849
- function createSelectionWrites(ctx, { store, authority, fonts, behaviors, lending }, annotations, properties, chrome, text) {
5207
+ function createSelectionWrites(ctx, { store, authority, fonts, behaviors, lending, geometry }, annotations, properties, chrome, text, crud) {
4850
5208
  const selectedRefs = () => refsOfIn(store.model(), store.model().selected);
5209
+ /** `refs` as this plugin's own records and the lent ones (a form's widgets, in design mode). */
5210
+ const byOwner = (refs) => {
5211
+ const own = [];
5212
+ const lent = [];
5213
+ for (const ref of refs) (lending.owns(annotationKey$1(ref)) ? lent : own).push(ref);
5214
+ return {
5215
+ own,
5216
+ lent
5217
+ };
5218
+ };
5219
+ /**
5220
+ * Where copies of the selection land: right and down of the originals, or
5221
+ * left or up where that keeps on its page a copy that would leave it.
5222
+ */
5223
+ const beside = () => {
5224
+ const boxes = annotations.selectedRecords().flatMap(({ annotation }) => {
5225
+ const page = geometry.pageBoxOf(annotation.page.objectNumber);
5226
+ return page ? [{
5227
+ rect: annotation.rect,
5228
+ page
5229
+ }] : [];
5230
+ });
5231
+ const flips = (axis, size) => boxes.some(({ rect, page }) => rect[axis] + rect[size] + DUPLICATE_OFFSET > page[size]) && boxes.every(({ rect }) => rect[axis] - DUPLICATE_OFFSET >= 0);
5232
+ return {
5233
+ x: flips("x", "width") ? -10 : DUPLICATE_OFFSET,
5234
+ y: flips("y", "height") ? -10 : DUPLICATE_OFFSET
5235
+ };
5236
+ };
4851
5237
  /** Commit a selection message; resolves with its outcome over the refs that were selected. */
4852
5238
  const commitOverSelection = async (commit, signal) => {
4853
5239
  return batchResultOf(selectedRefs(), { failed: (await ctx.cancellable(signal, Promise.all(commit().map((committed) => committed.written)))).flatMap((outcome) => outcome.failed) });
@@ -5009,6 +5395,25 @@ function createSelectionWrites(ctx, { store, authority, fonts, behaviors, lendin
5009
5395
  const ref = refOf(record);
5010
5396
  return ref != null && authority.allowsMutation("update", ref);
5011
5397
  });
5398
+ },
5399
+ duplicate: (options = {}) => {
5400
+ const { own, lent } = byOwner(selectedRefs());
5401
+ return crud.duplicate(own, {
5402
+ offset: options.offset ?? beside(),
5403
+ select: true,
5404
+ ...options.signal ? { signal: options.signal } : {}
5405
+ }, lent);
5406
+ },
5407
+ canDuplicate: () => {
5408
+ const { own, lent } = byOwner(selectedRefs());
5409
+ if (!own.length && !lent.length) return false;
5410
+ if (own.length && !authority.canDuplicate(own)) return false;
5411
+ const lender = lending.lender();
5412
+ const model = store.model();
5413
+ return lent.every((ref) => {
5414
+ const record = model.byId[annotationKey$1(ref)];
5415
+ return !!record && !record.annotation.locked && (lender?.getAuthority(record.annotation).copy ?? false);
5416
+ });
5012
5417
  }
5013
5418
  };
5014
5419
  /** One relationship (`/IRT` + `/RT`) written onto every record, as one change. */
@@ -5487,8 +5892,8 @@ function createAnnotationController(ctx) {
5487
5892
  const ghost = createGhost(ctx, services, stamps);
5488
5893
  const render = createRenderReads(ctx, services, ghost, stamps);
5489
5894
  const icons = createIcons(ctx, services, stamps);
5490
- const selection = createSelectionWrites(ctx, services, annotations, properties, chrome, text);
5491
- const measurement = createMeasurement(ctx, services, crud);
5895
+ const selection = createSelectionWrites(ctx, services, annotations, properties, chrome, text, crud);
5896
+ const measurement = createMeasurement(ctx, services);
5492
5897
  const pointer = createPointer(ctx, services, chrome, measurement);
5493
5898
  const drafts = createDrafts(ctx, services, annotations);
5494
5899
  const markup = createMarkupWrites(ctx, services, annotations);
@@ -5533,6 +5938,7 @@ function createAnnotationController(ctx) {
5533
5938
  canCreate: authority.canCreate,
5534
5939
  canUpdate: authority.canUpdate,
5535
5940
  canDelete: authority.canDelete,
5941
+ canDuplicate: authority.canDuplicate,
5536
5942
  onCreated: events.created.on,
5537
5943
  onUpdated: events.updated.on,
5538
5944
  onDeleted: events.deleted.on,