@embedpdf/plugin-annotation 3.1.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-nPw63clg.js → contract-BrvLUGi2.js} +3 -1
  6. package/dist/contract-BrvLUGi2.js.map +1 -0
  7. package/dist/{contract-CimdVhUD.d.cts → contract-CQfRsCVj.d.ts} +77 -12
  8. package/dist/{contract-uV_HOYTW.d.ts → contract-DkxvCGXL.d.cts} +77 -12
  9. package/dist/{contract-DlJK3S9O.cjs → contract-X3gZNpwu.cjs} +3 -1
  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-Ckl6r4Ch.d.cts → host-contract-BSH_muud.d.cts} +21 -3
  16. package/dist/{host-contract-Os6ryEkJ.cjs → host-contract-C7vx6wTQ.cjs} +2 -2
  17. package/dist/host-contract-C7vx6wTQ.cjs.map +1 -0
  18. package/dist/{host-contract-DP61yEHS.js → host-contract-CDp5skzD.js} +2 -2
  19. package/dist/host-contract-CDp5skzD.js.map +1 -0
  20. package/dist/{host-contract-Br2Nwfm8.d.ts → host-contract-DU3CxFE1.d.ts} +21 -3
  21. package/dist/index.cjs +419 -47
  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 +421 -49
  26. package/dist/index.js.map +1 -1
  27. package/package.json +12 -12
  28. package/dist/contract-DlJK3S9O.cjs.map +0 -1
  29. package/dist/contract-nPw63clg.js.map +0 -1
  30. package/dist/host-contract-DP61yEHS.js.map +0 -1
  31. package/dist/host-contract-Os6ryEkJ.cjs.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_contract = require("./contract-DlJK3S9O.cjs");
3
- const require_host_contract = require("./host-contract-Os6ryEkJ.cjs");
2
+ const require_contract = require("./contract-X3gZNpwu.cjs");
3
+ const require_host_contract = require("./host-contract-C7vx6wTQ.cjs");
4
4
  require("./authoring.cjs");
5
5
  let _embedpdf_core = require("@embedpdf/core");
6
6
  let _embedpdf_plugin_actions_contract = require("@embedpdf/plugin-actions/contract");
@@ -896,6 +896,11 @@ function createAnnotationReads(ctx, { store, records, lending }) {
896
896
  const record = model.byId[(0, _embedpdf_engine_core_runtime.annotationKey)(ref)];
897
897
  return !!record && (0, _embedpdf_core_annotation.isEditableByHand)(model, record.annotation);
898
898
  };
899
+ /** Whether it is an annotation people move: its kind moves, and it doesn't sit on text. */
900
+ const isMovable = (ref) => {
901
+ const record = store.model().byId[(0, _embedpdf_engine_core_runtime.annotationKey)(ref)];
902
+ return !!record && (0, _embedpdf_core_annotation.isMovable)(record);
903
+ };
899
904
  return {
900
905
  get,
901
906
  listAnnots,
@@ -909,7 +914,8 @@ function createAnnotationReads(ctx, { store, records, lending }) {
909
914
  list,
910
915
  isPending,
911
916
  getHovered,
912
- isEditable
917
+ isEditable,
918
+ isMovable
913
919
  }
914
920
  };
915
921
  }
@@ -1529,10 +1535,10 @@ function programsOf(id, doc, body, bodyPrograms, text) {
1529
1535
  * areas, and the baked-appearance seam (epoch and pictures). The engine's
1530
1536
  * pictures come through the render plugin, which shares and keeps them. A
1531
1537
  * stamp this session placed shows the preview it was placed with until the
1532
- * engine's picture of it exists, and an annotation an undo brings back the
1533
- * picture it had.
1538
+ * engine's picture of it exists, an annotation an undo brings back the
1539
+ * picture it had, and a copy of a stamp its original's.
1534
1540
  */
1535
- function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLookup, textFonts }, ghost, stamps) {
1541
+ function createRenderReads(ctx, { view: { pageModel }, lending, records, copySources, fonts: fontLookup, textFonts }, ghost, stamps) {
1536
1542
  const itemsCache = /* @__PURE__ */ new Map();
1537
1543
  const fonts = () => ctx.tryGet(_embedpdf_plugin_fonts_contract.FontsToken);
1538
1544
  /**
@@ -1677,8 +1683,9 @@ function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLooku
1677
1683
  * annotations the engine draws on it, each at its picture version
1678
1684
  * (`pictureVersion`, which advances when the engine confirms a re-bake).
1679
1685
  * `placed`: the stamps this session placed that the engine hasn't written
1680
- * yet, which show the preview they were placed with, and the records an
1681
- * undo brought back, which show the pictures kept of them. Position,
1686
+ * yet, which show the preview they were placed with (`previewOf`), and
1687
+ * the records an undo brought back or a copy made, which show the pictures
1688
+ * kept of them or of their original (`keptOf`). Position,
1682
1689
  * rotation and the state shown are absent: the blit translates (`apBox`)
1683
1690
  * and turns (`apRot`) the same pixels, and every state is held, so a move,
1684
1691
  * a spin or a switch costs no new picture. `lent`: the lender's epoch for
@@ -1695,8 +1702,8 @@ function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLooku
1695
1702
  if (!record || record.annotation.page.objectNumber !== pageObjectNumber || record.source !== "baked") continue;
1696
1703
  if ((0, _embedpdf_core_annotation.isSubstrateOnly)(record)) continue;
1697
1704
  if (record.unconfirmed) {
1698
- if (stamps.lookOf(record)) placed.push(`${id}@placed`);
1699
- else if (keptOf(id, record.annotation.ref).length) placed.push(`${id}@kept`);
1705
+ if (previewOf(record)) placed.push(`${id}@placed`);
1706
+ else if (keptOf(record).length) placed.push(`${id}@kept`);
1700
1707
  continue;
1701
1708
  }
1702
1709
  if (lending.owns(id)) {
@@ -1736,8 +1743,64 @@ function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLooku
1736
1743
  };
1737
1744
  /** The family whose pictures a record's are: the lender's widgets, or annotations. */
1738
1745
  const familyOf = (id) => lending.owns(id) ? "widgets" : "annotations";
1739
- /** The engine's last pictures of a record, kept a while after it left its page. */
1740
- const keptOf = (id, ref) => ctx.tryGet(_embedpdf_plugin_render_contract_host.RenderToken)?.getKeptAppearances(familyOf(id), ref) ?? [];
1746
+ /**
1747
+ * The annotations a copy the engine hasn't written stands in for, nearest
1748
+ * first: the one it copies, then, while that one is such a copy too, the
1749
+ * one behind it, and last the source noted when the copy was staged
1750
+ * (services/copy-sources.ts), which still holds once the engine wrote a
1751
+ * copy in between. A copy of a copy finds its look this way.
1752
+ */
1753
+ const originalsOf = (id) => {
1754
+ const { byKey } = records.view();
1755
+ const originals = [];
1756
+ const seen = /* @__PURE__ */ new Set([id]);
1757
+ let next = byKey[id]?.copyOf;
1758
+ while (next && !seen.has((0, _embedpdf_engine_core_runtime.annotationKey)(next))) {
1759
+ seen.add((0, _embedpdf_engine_core_runtime.annotationKey)(next));
1760
+ originals.push(next);
1761
+ next = byKey[(0, _embedpdf_engine_core_runtime.annotationKey)(next)]?.copyOf;
1762
+ }
1763
+ const noted = copySources.of(id);
1764
+ if (noted && !seen.has((0, _embedpdf_engine_core_runtime.annotationKey)(noted))) originals.push(noted);
1765
+ return originals;
1766
+ };
1767
+ /**
1768
+ * The preview a record the engine hasn't written shows: the one it was
1769
+ * placed with (a stamp this session placed), or, for a copy of a stamp
1770
+ * that is still being placed, that stamp's.
1771
+ */
1772
+ const previewOf = (record) => {
1773
+ const own = stamps.lookOf(record);
1774
+ if (own || !record.unconfirmed) return own;
1775
+ for (const original of originalsOf(record.id)) {
1776
+ const placed = pageModel(original.page.objectNumber).byId[(0, _embedpdf_engine_core_runtime.annotationKey)(original)];
1777
+ const look = placed ? stamps.lookOf(placed) : null;
1778
+ if (look) return look;
1779
+ }
1780
+ return null;
1781
+ };
1782
+ /**
1783
+ * The pictures a record the engine hasn't written shows when it has no
1784
+ * live drawing: the engine's last pictures of it, kept a while after it
1785
+ * left its page (an undo brings it back), or, for a copy, the ones of the
1786
+ * annotation it copies, where the copy is.
1787
+ */
1788
+ const keptOf = (record) => {
1789
+ const render = ctx.tryGet(_embedpdf_plugin_render_contract_host.RenderToken);
1790
+ if (!render) return [];
1791
+ const { ref } = record.annotation;
1792
+ const own = render.getKeptAppearances(familyOf(record.id), ref);
1793
+ if (own.length) return own;
1794
+ for (const original of originalsOf(record.id)) {
1795
+ const kept = render.getKeptAppearances("annotations", original);
1796
+ if (kept.length) return kept.map((each) => ({
1797
+ ...each,
1798
+ ref,
1799
+ rect: record.apBox ?? each.rect
1800
+ }));
1801
+ }
1802
+ return [];
1803
+ };
1741
1804
  /**
1742
1805
  * The pictures of what shows on `page` that the engine hasn't written yet:
1743
1806
  * a stamp this session placed shows its preview, at the size the page shows
@@ -1750,8 +1813,8 @@ function createRenderReads(ctx, { view: { pageModel }, lending, fonts: fontLooku
1750
1813
  const record = model.byId[id];
1751
1814
  if (!record.unconfirmed) return [];
1752
1815
  const version = record.pictureVersion ?? 0;
1753
- const look = stamps.lookOf(record);
1754
- if (!look) return keptOf(id, record.annotation.ref).map((kept) => ({
1816
+ const look = previewOf(record);
1817
+ if (!look) return keptOf(record).map((kept) => ({
1755
1818
  ...kept,
1756
1819
  version
1757
1820
  }));
@@ -1815,11 +1878,29 @@ function createAuthority(ctx, store) {
1815
1878
  }).map((member) => member.ref);
1816
1879
  };
1817
1880
  const canDelete = (ref) => blockersOf(ref).length === 0;
1881
+ /**
1882
+ * Whether a person may copy these annotations: the right to create, each
1883
+ * one here and copied whole by the engine's own rule
1884
+ * (`planAnnotationCopies`), and none locked. A copy of a locked annotation
1885
+ * is locked too, so a person could neither move nor delete it.
1886
+ */
1887
+ const canDuplicate = (refs) => {
1888
+ if (!refs.length || !canCreate()) return false;
1889
+ const model = store.model();
1890
+ const sources = [];
1891
+ for (const ref of refs) {
1892
+ const annotation = model.byId[(0, _embedpdf_engine_core_runtime.annotationKey)(ref)]?.annotation;
1893
+ if (!annotation || annotation.locked) return false;
1894
+ sources.push(annotation);
1895
+ }
1896
+ return (0, _embedpdf_engine_core_runtime.planAnnotationCopies)(sources, {}).dropped.length === 0;
1897
+ };
1818
1898
  return {
1819
1899
  canRead,
1820
1900
  canCreate,
1821
1901
  canUpdate,
1822
1902
  canDelete,
1903
+ canDuplicate,
1823
1904
  blockersOf,
1824
1905
  allowsMutation
1825
1906
  };
@@ -2089,6 +2170,19 @@ const NO_RECORDS$1 = [];
2089
2170
  const sameItems = (left, right) => left.length === right.length && left.every((item, index) => Object.is(item, right[index]));
2090
2171
  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);
2091
2172
  //#endregion
2173
+ //#region src/services/copy-sources.ts
2174
+ function createCopySources(records) {
2175
+ const sources = /* @__PURE__ */ new Map();
2176
+ return {
2177
+ note(copies) {
2178
+ const { byKey } = records.view();
2179
+ for (const key of sources.keys()) if (!(key in byKey)) sources.delete(key);
2180
+ for (const { ref, of } of copies) sources.set((0, _embedpdf_engine_core_runtime.annotationKey)(ref), sources.get((0, _embedpdf_engine_core_runtime.annotationKey)(of)) ?? of);
2181
+ },
2182
+ of: (id) => sources.get(id) ?? null
2183
+ };
2184
+ }
2185
+ //#endregion
2092
2186
  //#region src/services/events.ts
2093
2187
  /**
2094
2188
  * The plugin's events. Record events (created, updated, deleted, reordered,
@@ -2473,6 +2567,54 @@ function annotationOfCreate(draft, ref) {
2473
2567
  };
2474
2568
  }
2475
2569
  /**
2570
+ * The copies a copy makes, each with the annotation it copies: the engine's
2571
+ * own rule (`planAnnotationCopies`) over the records, and each copy read as
2572
+ * a create of the same data is (`annotationOfCreate`). None for a copy the
2573
+ * engine numbers itself, which has no keys to show its copies by, and none
2574
+ * when the engine would refuse it (an annotation it names is gone).
2575
+ */
2576
+ function copiesOf(records, op) {
2577
+ const { objectNumbers } = op;
2578
+ if (!objectNumbers || objectNumbers.length !== op.refs.length) return [];
2579
+ const sources = [];
2580
+ for (const ref of op.refs) {
2581
+ const stored = records.byKey[(0, _embedpdf_engine_core_runtime.annotationKey)(ref)];
2582
+ if (!stored) return [];
2583
+ sources.push(stored.dto);
2584
+ }
2585
+ const { copies } = (0, _embedpdf_engine_core_runtime.planAnnotationCopies)(sources, {
2586
+ ...op.page ? { page: op.page } : {},
2587
+ ...op.offset ? { offset: op.offset } : {}
2588
+ });
2589
+ const refs = copies.map((copy) => ({
2590
+ kind: "objectNumber",
2591
+ page: copy.page,
2592
+ objectNumber: objectNumbers[copy.source]
2593
+ }));
2594
+ return copies.map((copy, at) => {
2595
+ const draft = {
2596
+ ...copy.data,
2597
+ ...copy.replyTo ? { reply: {
2598
+ to: refs[copy.replyTo.copy],
2599
+ type: copy.replyTo.type
2600
+ } } : {},
2601
+ ...copy.parent !== void 0 ? { parent: refs[copy.parent] } : {}
2602
+ };
2603
+ let read;
2604
+ try {
2605
+ read = annotationOfCreate(draft, refs[at]);
2606
+ } catch {
2607
+ read = null;
2608
+ }
2609
+ return {
2610
+ ref: refs[at],
2611
+ copy: read,
2612
+ of: sources[copy.source].ref,
2613
+ source: copy.source
2614
+ };
2615
+ });
2616
+ }
2617
+ /**
2476
2618
  * The record keys of one page in a new drawing order: `keys` moved to
2477
2619
  * `position` among the page's others, in the order given, as the engine
2478
2620
  * reorders. Other pages keep their places. Unchanged when the engine would
@@ -2533,6 +2675,23 @@ function predictRecords(records, op) {
2533
2675
  order
2534
2676
  };
2535
2677
  }
2678
+ case "annotations.copy": {
2679
+ const made = copiesOf(records, op).flatMap(({ copy, of }) => copy && !((0, _embedpdf_engine_core_runtime.annotationKey)(copy.ref) in records.byKey) ? [{
2680
+ copy,
2681
+ of
2682
+ }] : []);
2683
+ if (!made.length) return records;
2684
+ const byKey = { ...records.byKey };
2685
+ for (const { copy, of } of made) byKey[(0, _embedpdf_engine_core_runtime.annotationKey)(copy.ref)] = {
2686
+ dto: copy,
2687
+ pictureVersion: 0,
2688
+ copyOf: of
2689
+ };
2690
+ return {
2691
+ byKey,
2692
+ order: [...records.order, ...made.map(({ copy }) => (0, _embedpdf_engine_core_runtime.annotationKey)(copy.ref))]
2693
+ };
2694
+ }
2536
2695
  case "annotations.restore": {
2537
2696
  const key = (0, _embedpdf_engine_core_runtime.annotationKey)(op.annotation.ref);
2538
2697
  if (key in records.byKey) return records;
@@ -2596,6 +2755,10 @@ function undoOfOp(records, op) {
2596
2755
  index
2597
2756
  }] : []);
2598
2757
  }
2758
+ case "annotations.copy": return copiesOf(records, op).map(({ ref }) => ({
2759
+ type: "annotations.delete",
2760
+ ref
2761
+ }));
2599
2762
  case "annotations.reorder": return [{
2600
2763
  type: "annotations.reorder",
2601
2764
  page: op.page,
@@ -2656,6 +2819,8 @@ function createRecordsMirror(ctx, events) {
2656
2819
  * update; the deletes another delete covers; the records it names and what it
2657
2820
  * is called. Pure functions.
2658
2821
  */
2822
+ /** The annotations a stated copy copies: the ones it names, then what comes along. */
2823
+ const copiedBy = (change) => change.along?.length ? [...change.refs, ...change.along] : change.refs;
2659
2824
  /**
2660
2825
  * A stated change as its op, as given: what an op builder adds for changes
2661
2826
  * worked out in the engine's terms (a link's children).
@@ -2684,12 +2849,19 @@ const opOfStated = (change) => {
2684
2849
  refs: change.refs,
2685
2850
  position: change.position
2686
2851
  };
2852
+ case "copy": return {
2853
+ type: "annotations.copy",
2854
+ refs: copiedBy(change),
2855
+ ...change.page ? { page: change.page } : {},
2856
+ ...change.offset ? { offset: change.offset } : {}
2857
+ };
2687
2858
  }
2688
2859
  };
2689
2860
  /** The record keys an op names. */
2690
2861
  const keysOf = (op) => {
2691
2862
  switch (op.type) {
2692
2863
  case "annotations.create": return op.objectNumber === void 0 ? [] : [`obj:${op.objectNumber}`];
2864
+ case "annotations.copy": return (op.objectNumbers ?? []).map((objectNumber) => `obj:${objectNumber}`);
2693
2865
  case "annotations.update":
2694
2866
  case "annotations.delete": return [(0, _embedpdf_engine_core_runtime.annotationKey)(op.ref)];
2695
2867
  case "annotations.reorder": return op.refs.map(_embedpdf_engine_core_runtime.annotationKey);
@@ -2702,8 +2874,15 @@ const keysOf = (op) => {
2702
2874
  /** The records a change names, each once. */
2703
2875
  const idsOf = (ops) => [...new Set(ops.flatMap(keysOf))];
2704
2876
  /**
2705
- * What a change is called, from what it does: one kind of op (`annotation.move`,
2706
- * or a lent record's own, `form.updateWidget`), or several (`annotation.change`).
2877
+ * The verb of this plugin that makes an op, where the engine names the op
2878
+ * differently: `duplicate()` makes copies, and the page plugin calls its own
2879
+ * `pages.duplicate`.
2880
+ */
2881
+ const LABEL_VERBS = { "annotations.copy": "duplicate" };
2882
+ /**
2883
+ * What a change is called, from what it does: one kind of op, by the verb
2884
+ * that makes it (`annotation.update`, `annotation.duplicate`, or a lent
2885
+ * record's own, `form.updateWidget`), or several (`annotation.change`).
2707
2886
  * History and refusals show it.
2708
2887
  */
2709
2888
  const labelOf = (ops) => {
@@ -2711,7 +2890,7 @@ const labelOf = (ops) => {
2711
2890
  const [only] = kinds;
2712
2891
  const [plane, verb] = kinds.size === 1 && only ? only.split(".") : ["annotations", "change"];
2713
2892
  return {
2714
- key: `${plane === "annotations" ? "annotation" : plane === "forms" ? "form" : plane}.${verb}`,
2893
+ key: `${plane === "annotations" ? "annotation" : plane === "forms" ? "form" : plane}.${(kinds.size === 1 && only ? LABEL_VERBS[only] : void 0) ?? verb}`,
2715
2894
  count: idsOf(ops).length
2716
2895
  };
2717
2896
  };
@@ -2772,6 +2951,35 @@ function modelAfter(before, result) {
2772
2951
  };
2773
2952
  }
2774
2953
  const notFound = (ref) => new _embedpdf_core.PluginError("not-found", "annotation", `no annotation ${(0, _embedpdf_engine_core_runtime.annotationKey)(ref)}`);
2954
+ /** How many object numbers stated changes take: one per create, and one per annotation a copy copies. */
2955
+ const numbersFor = (changes) => changes.reduce((count, change) => count + (change.type === "create" ? 1 : change.type === "copy" ? copiedBy(change).length : 0), 0);
2956
+ /**
2957
+ * A stated copy as its op, with an object number for each annotation it
2958
+ * copies, so the copies show at once under them. `ids`: the copies of the
2959
+ * annotations it names, in their order (one the engine leaves out has none),
2960
+ * each by the object number it gets, whether it shows before the engine
2961
+ * answers or not; `live`: the copies that draw live from now on; `copies`:
2962
+ * every copy it makes, each with the annotation it copies. Throws for an
2963
+ * annotation the view doesn't have.
2964
+ */
2965
+ function checkedCopyOf(change, current, taken) {
2966
+ const refs = copiedBy(change);
2967
+ for (const ref of refs) if (!((0, _embedpdf_engine_core_runtime.annotationKey)(ref) in current.byKey)) throw notFound(ref);
2968
+ const op = {
2969
+ type: "annotations.copy",
2970
+ refs,
2971
+ ...change.page ? { page: change.page } : {},
2972
+ ...change.offset ? { offset: change.offset } : {},
2973
+ objectNumbers: taken.splice(0, refs.length)
2974
+ };
2975
+ const copies = copiesOf(current, op);
2976
+ return {
2977
+ ids: copies.filter(({ source }) => source < change.refs.length).map(({ ref }) => (0, _embedpdf_engine_core_runtime.annotationKey)(ref)),
2978
+ op,
2979
+ live: copies.flatMap(({ copy }) => copy && (0, _embedpdf_core_annotation.sourceOfNew)(copy) === "vector" ? [(0, _embedpdf_engine_core_runtime.annotationKey)(copy.ref)] : []),
2980
+ copies
2981
+ };
2982
+ }
2775
2983
  /**
2776
2984
  * One stated change as its op, resolved by the engine's own rules against
2777
2985
  * `current`: what shows is what the engine will write, and a change those
@@ -2875,7 +3083,7 @@ const NOTHING_WRITTEN = {
2875
3083
  result: null
2876
3084
  };
2877
3085
  const noNumbers = () => new _embedpdf_core.PluginError("not-ready", "annotation", "the document holds no object number for a new annotation right now");
2878
- function createStore(ctx, view, records, events, lending) {
3086
+ function createStore(ctx, view, records, events, lending, copySources) {
2879
3087
  let followUp = null;
2880
3088
  const builders = /* @__PURE__ */ new Map();
2881
3089
  const model = view.model;
@@ -2888,7 +3096,7 @@ function createStore(ctx, view, records, events, lending) {
2888
3096
  kind: "objectNumber",
2889
3097
  page: op.page,
2890
3098
  objectNumber: op.objectNumber
2891
- }] : 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] : []);
3099
+ }] : 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] : []);
2892
3100
  events.writeFailed.emit({
2893
3101
  refs,
2894
3102
  error: (0, _embedpdf_core.toPluginErrorInfo)(settled.error)
@@ -2909,11 +3117,11 @@ function createStore(ctx, view, records, events, lending) {
2909
3117
  * Stage this plugin's ops and its lender's as one change. Undoing it undoes
2910
3118
  * the lent ops first: they come last.
2911
3119
  */
2912
- const stage = (ops, before, lent = []) => {
3120
+ const stage = (ops, before, lent = [], label) => {
2913
3121
  const all = [...ops, ...lent];
2914
3122
  const undo = [...lent.length ? lending.lender()?.undoOf(lent) ?? [] : [], ...undoOf(before, ops)];
2915
3123
  const change = ctx.changes.stage({
2916
- label: labelOf(all),
3124
+ label: label ?? labelOf(all),
2917
3125
  ops: all,
2918
3126
  undo
2919
3127
  });
@@ -3012,8 +3220,8 @@ function createStore(ctx, view, records, events, lending) {
3012
3220
  };
3013
3221
  const apply = (changes, options = {}) => {
3014
3222
  const shown = records.view();
3015
- const creates = changes.filter((change) => change.type === "create").length;
3016
- const taken = creates ? numbers.take(creates) : [];
3223
+ const needed = numbersFor(changes);
3224
+ const taken = needed ? numbers.take(needed) : [];
3017
3225
  if (!taken) throw noNumbers();
3018
3226
  const ops = [];
3019
3227
  /** Lent records reordered: their lender's ops, last in the change. */
@@ -3022,10 +3230,23 @@ function createStore(ctx, view, records, events, lending) {
3022
3230
  const opIndex = [];
3023
3231
  const ids = [];
3024
3232
  const vector = [];
3233
+ /** The copies the change makes, each with the annotation it copies. */
3234
+ const copied = [];
3025
3235
  let current = shown;
3026
3236
  try {
3027
3237
  for (const stated of changes) {
3028
3238
  if (stated.type === "update" || stated.type === "delete") refuseLent(lending, stated.ref);
3239
+ if (stated.type === "copy") {
3240
+ for (const ref of [...stated.refs, ...stated.along ?? []]) refuseLent(lending, ref);
3241
+ const copy = checkedCopyOf(stated, current, taken);
3242
+ ids.push(...copy.ids);
3243
+ opIndex.push(ops.length);
3244
+ ops.push(copy.op);
3245
+ vector.push(...copy.live);
3246
+ copied.push(...copy.copies);
3247
+ current = predictRecords(current, copy.op);
3248
+ continue;
3249
+ }
3029
3250
  const change = stated.type === "reorder" ? ownReorder(lending, stated, lent) : stated;
3030
3251
  if (!change) {
3031
3252
  ids.push((0, _embedpdf_engine_core_runtime.annotationKey)(stated.refs[0]));
@@ -3043,6 +3264,10 @@ function createStore(ctx, view, records, events, lending) {
3043
3264
  } catch (error) {
3044
3265
  throw (0, _embedpdf_core.toPluginError)("annotation", error);
3045
3266
  }
3267
+ if (options.lent) {
3268
+ lent.push(...options.lent.ops);
3269
+ ids.push(...options.lent.ids);
3270
+ }
3046
3271
  if (!ops.length && !lent.length) return {
3047
3272
  ids,
3048
3273
  written: Promise.resolve({
@@ -3059,13 +3284,26 @@ function createStore(ctx, view, records, events, lending) {
3059
3284
  }
3060
3285
  }));
3061
3286
  const selected = model().selected;
3062
- const change = stage(withoutCoveredDeletes(shown, [...ops, ...following.ops]), shown, lent);
3287
+ copySources.note(copied);
3288
+ const change = stage(withoutCoveredDeletes(shown, [...ops, ...following.ops]), shown, lent, options.label);
3063
3289
  selections.remember(change.opId, selected, options.select ? ids : selected);
3064
3290
  if (vector.length) ctx.state.update(withSession, ctx.state.get().session, vector);
3065
- if (options.select) commit({
3066
- type: "select",
3067
- ids
3068
- });
3291
+ if (options.select) {
3292
+ commit({
3293
+ type: "select",
3294
+ ids
3295
+ });
3296
+ if (ids.some((id) => !(id in model().byId))) {
3297
+ const staged = model().selected;
3298
+ const selectLate = () => {
3299
+ if (sameIds(model().selected, staged)) commit({
3300
+ type: "select",
3301
+ ids
3302
+ });
3303
+ };
3304
+ change.result.then(selectLate, () => {});
3305
+ }
3306
+ }
3069
3307
  return {
3070
3308
  ids,
3071
3309
  written: writtenOf(change, idsOf([...ops, ...lent])).then((outcome) => ({
@@ -3078,8 +3316,8 @@ function createStore(ctx, view, records, events, lending) {
3078
3316
  };
3079
3317
  };
3080
3318
  const applyWhenNumbered = async (changes, options) => {
3081
- const creates = changes.filter((change) => change.type === "create").length;
3082
- while (!numbers.hold(creates)) await ctx.changes.reserveObjectNumbers(creates);
3319
+ const needed = numbersFor(changes);
3320
+ while (!numbers.hold(needed)) await ctx.changes.reserveObjectNumbers(needed);
3083
3321
  return apply(changes, options);
3084
3322
  };
3085
3323
  ctx.watch(view.view, (next, previous) => {
@@ -3627,7 +3865,8 @@ function createServices(ctx) {
3627
3865
  const records = createRecordsMirror(ctx, events);
3628
3866
  const lending = createLending(() => ctx.notify());
3629
3867
  const view = createView(ctx, records, lending);
3630
- const store = createStore(ctx, view, records, events, lending);
3868
+ const copySources = createCopySources(records);
3869
+ const store = createStore(ctx, view, records, events, lending, copySources);
3631
3870
  const tools = createToolRegistry(ctx, settings.get().tools, store, events);
3632
3871
  const fonts = createFontLookup(ctx);
3633
3872
  return {
@@ -3636,6 +3875,7 @@ function createServices(ctx) {
3636
3875
  records,
3637
3876
  view,
3638
3877
  lending,
3878
+ copySources,
3639
3879
  store,
3640
3880
  geometry,
3641
3881
  authority: createAuthority(ctx, store),
@@ -3999,14 +4239,16 @@ function createGhost(ctx, { store, geometry, tools }, stamps) {
3999
4239
  //#endregion
4000
4240
  //#region src/write/crud.ts
4001
4241
  /**
4002
- * Create, update, delete and reorder: the public verbs, in the engine's own
4003
- * terms, and the transfers (export, import, a resource's bytes). Each change
4004
- * states itself through `store.apply`, so it shows at once and is sent,
4005
- * answered and refused exactly like a gesture's, and each resolves with what
4006
- * the engine wrote for it: its own change's answer, never another change
4007
- * still on its way.
4242
+ * Create, update, delete, reorder and duplicate: the public verbs, in the
4243
+ * engine's own terms, and the transfers (export, import, a resource's
4244
+ * bytes). Each change states itself through `store.apply`, so it shows at
4245
+ * once and is sent, answered and refused exactly like a gesture's, and each
4246
+ * resolves with what the engine wrote for it: its own change's answer, never
4247
+ * another change still on its way. An import is a change too: the engine's
4248
+ * own verb makes it, so it is staged on the document's queue as that verb's
4249
+ * call.
4008
4250
  */
4009
- function createCrud(ctx, { store, tools, records }, annotations, settle) {
4251
+ function createCrud(ctx, { store, tools, records, lending }, annotations, settle) {
4010
4252
  /** The annotation `ref` names, as the view holds it: for a change that wrote nothing. */
4011
4253
  const current = (ref) => {
4012
4254
  const annotation = annotations.get(ref);
@@ -4086,6 +4328,68 @@ function createCrud(ctx, { store, tools, records }, annotations, settle) {
4086
4328
  position
4087
4329
  }])));
4088
4330
  };
4331
+ /**
4332
+ * Copies of annotations in this document, which the engine makes in one
4333
+ * op: they show at once, and it is one step to undo. An annotation's
4334
+ * attached link is a child of it, so it is copied along. A link `refs`
4335
+ * names itself is copied once, as one of the copies named.
4336
+ *
4337
+ * `lent` are the selection's lent records (a form's widgets, in design
4338
+ * mode), which only the selection's own duplicate passes: their lender
4339
+ * says which ops copy them, and those join the same change, so a
4340
+ * selection of both kinds is one step. Their copies are among the
4341
+ * annotations it resolves; what their lender left out is its own to tell.
4342
+ */
4343
+ const duplicate = async (refs, options = {}, lent = []) => {
4344
+ if (refs.length || !lent.length) ctx.assertAllowed("annotations:create", "annotation.duplicate");
4345
+ if (!refs.length && !lent.length) return {
4346
+ annotations: [],
4347
+ dropped: []
4348
+ };
4349
+ const page = options.page === void 0 ? void 0 : ctx.pageOf(options.page).ref;
4350
+ const placement = {
4351
+ ...page ? { page } : {},
4352
+ ...options.offset ? { offset: options.offset } : {}
4353
+ };
4354
+ const lender = lent.length ? lending.lender() : null;
4355
+ const lentCopy = lender ? await lender.copyOps(lent, placement) : null;
4356
+ const model = store.model();
4357
+ const stated = new Set(refs.map(_embedpdf_engine_core_runtime.annotationKey));
4358
+ const along = refs.flatMap((ref) => (0, _embedpdf_core_annotation.linkChildrenOf)(model, (0, _embedpdf_engine_core_runtime.annotationKey)(ref)).map((child) => child.annotation.ref).filter((child) => !stated.has((0, _embedpdf_engine_core_runtime.annotationKey)(child))));
4359
+ const lentIds = lentCopy?.copies.map(_embedpdf_engine_core_runtime.annotationKey) ?? [];
4360
+ const applied = await store.applyWhenNumbered(refs.length ? [{
4361
+ type: "copy",
4362
+ refs,
4363
+ ...along.length ? { along } : {},
4364
+ ...placement
4365
+ }] : [], {
4366
+ select: options.select,
4367
+ ...lentCopy ? {
4368
+ lent: {
4369
+ ops: lentCopy.ops,
4370
+ ids: lentIds
4371
+ },
4372
+ label: {
4373
+ key: refs.length ? "annotation.duplicate" : `${lender.owner}.duplicate`,
4374
+ count: refs.length + lentIds.length
4375
+ }
4376
+ } : {}
4377
+ });
4378
+ const items = (await ctx.cancellable(options.signal, appliedOrThrow(applied))).result?.items ?? [];
4379
+ const copied = items.find((item) => item.type === "annotations.copy");
4380
+ if (refs.length && copied?.type !== "annotations.copy") throw new _embedpdf_core.PluginError("operation-failed", "annotation", "the annotations could not be copied");
4381
+ const named = new Set(applied.ids);
4382
+ const own = copied?.type === "annotations.copy" ? copied.annotations.filter((copy) => named.has((0, _embedpdf_engine_core_runtime.annotationKey)(copy.ref))) : [];
4383
+ const rows = /* @__PURE__ */ new Map();
4384
+ for (const item of items) {
4385
+ const made = item.type === "forms.copy" || item.type === "forms.addWidget" ? item.widgets : item.type === "forms.updateWidget" ? [item.widget] : [];
4386
+ for (const row of made) rows.set((0, _embedpdf_engine_core_runtime.annotationKey)(row.ref), row);
4387
+ }
4388
+ return {
4389
+ annotations: [...own, ...lentIds.flatMap((id) => rows.get(id) ?? [])],
4390
+ dropped: copied?.type === "annotations.copy" ? copied.dropped : []
4391
+ };
4392
+ };
4089
4393
  /** The pages a selection names, as refs: an index becomes its page's ref. */
4090
4394
  const pageRefsOf = (pages) => pages?.map((page) => ctx.pageOf(page).ref);
4091
4395
  const exportBundle = async (selection = {}, options = {}) => {
@@ -4099,13 +4403,28 @@ function createCrud(ctx, { store, tools, records }, annotations, settle) {
4099
4403
  };
4100
4404
  const importBundle = async (bundle, options = {}) => {
4101
4405
  ctx.assertAllowed("annotations:create", "annotation.import");
4102
- const { signal, ...importOptions } = options;
4103
- const result = await ctx.cancellable(signal, ctx.doc.annotations.import(bundle, importOptions));
4406
+ const { signal, history, ...importOptions } = options;
4407
+ const { items } = await ctx.changes.stage({
4408
+ label: { key: "annotation.import" },
4409
+ opId: importOptions.opId,
4410
+ history,
4411
+ send: (doc, { opId }) => ctx.cancellable(signal, doc.annotations.import(bundle, {
4412
+ ...importOptions,
4413
+ opId
4414
+ })).then((result) => ({
4415
+ items: [{
4416
+ type: "annotations.import",
4417
+ ...result
4418
+ }],
4419
+ meta: result.meta
4420
+ }))
4421
+ }).result;
4422
+ const imported = items[0];
4104
4423
  await records.settled();
4105
4424
  return {
4106
- annotations: result.annotations,
4107
- refMap: result.refMap,
4108
- dropped: result.dropped
4425
+ annotations: imported.annotations,
4426
+ refMap: imported.refMap,
4427
+ dropped: imported.dropped
4109
4428
  };
4110
4429
  };
4111
4430
  const downloadResource = async (ref, role, options = {}) => {
@@ -4115,11 +4434,13 @@ function createCrud(ctx, { store, tools, records }, annotations, settle) {
4115
4434
  };
4116
4435
  return {
4117
4436
  update,
4437
+ duplicate,
4118
4438
  api: {
4119
4439
  create,
4120
4440
  update,
4121
4441
  delete: remove,
4122
4442
  reorder,
4443
+ duplicate,
4123
4444
  export: exportBundle,
4124
4445
  import: importBundle,
4125
4446
  downloadResource
@@ -4877,13 +5198,44 @@ function createScriptEffects(ctx, { store, geometry }) {
4877
5198
  }
4878
5199
  //#endregion
4879
5200
  //#region src/write/selection.ts
5201
+ /** How far a duplicate lands from its original, in page points. */
5202
+ const DUPLICATE_OFFSET = 10;
4880
5203
  /**
4881
5204
  * The selection: what is selected, and the verbs that change its fields,
4882
- * link, delete, rotate, group and ungroup it as one, every member through the
4883
- * same `update → patch effect` path a gesture takes. Each verb is one change.
5205
+ * link, delete, rotate, group, ungroup and duplicate it as one, every member
5206
+ * through the same `update → patch effect` path a gesture takes. Each verb is
5207
+ * one change.
4884
5208
  */
4885
- function createSelectionWrites(ctx, { store, authority, fonts, behaviors, lending }, annotations, properties, chrome, text) {
5209
+ function createSelectionWrites(ctx, { store, authority, fonts, behaviors, lending, geometry }, annotations, properties, chrome, text, crud) {
4886
5210
  const selectedRefs = () => refsOfIn(store.model(), store.model().selected);
5211
+ /** `refs` as this plugin's own records and the lent ones (a form's widgets, in design mode). */
5212
+ const byOwner = (refs) => {
5213
+ const own = [];
5214
+ const lent = [];
5215
+ for (const ref of refs) (lending.owns((0, _embedpdf_engine_core_runtime.annotationKey)(ref)) ? lent : own).push(ref);
5216
+ return {
5217
+ own,
5218
+ lent
5219
+ };
5220
+ };
5221
+ /**
5222
+ * Where copies of the selection land: right and down of the originals, or
5223
+ * left or up where that keeps on its page a copy that would leave it.
5224
+ */
5225
+ const beside = () => {
5226
+ const boxes = annotations.selectedRecords().flatMap(({ annotation }) => {
5227
+ const page = geometry.pageBoxOf(annotation.page.objectNumber);
5228
+ return page ? [{
5229
+ rect: annotation.rect,
5230
+ page
5231
+ }] : [];
5232
+ });
5233
+ const flips = (axis, size) => boxes.some(({ rect, page }) => rect[axis] + rect[size] + DUPLICATE_OFFSET > page[size]) && boxes.every(({ rect }) => rect[axis] - DUPLICATE_OFFSET >= 0);
5234
+ return {
5235
+ x: flips("x", "width") ? -10 : DUPLICATE_OFFSET,
5236
+ y: flips("y", "height") ? -10 : DUPLICATE_OFFSET
5237
+ };
5238
+ };
4887
5239
  /** Commit a selection message; resolves with its outcome over the refs that were selected. */
4888
5240
  const commitOverSelection = async (commit, signal) => {
4889
5241
  return batchResultOf(selectedRefs(), { failed: (await ctx.cancellable(signal, Promise.all(commit().map((committed) => committed.written)))).flatMap((outcome) => outcome.failed) });
@@ -5045,6 +5397,25 @@ function createSelectionWrites(ctx, { store, authority, fonts, behaviors, lendin
5045
5397
  const ref = (0, _embedpdf_core_annotation.refOf)(record);
5046
5398
  return ref != null && authority.allowsMutation("update", ref);
5047
5399
  });
5400
+ },
5401
+ duplicate: (options = {}) => {
5402
+ const { own, lent } = byOwner(selectedRefs());
5403
+ return crud.duplicate(own, {
5404
+ offset: options.offset ?? beside(),
5405
+ select: true,
5406
+ ...options.signal ? { signal: options.signal } : {}
5407
+ }, lent);
5408
+ },
5409
+ canDuplicate: () => {
5410
+ const { own, lent } = byOwner(selectedRefs());
5411
+ if (!own.length && !lent.length) return false;
5412
+ if (own.length && !authority.canDuplicate(own)) return false;
5413
+ const lender = lending.lender();
5414
+ const model = store.model();
5415
+ return lent.every((ref) => {
5416
+ const record = model.byId[(0, _embedpdf_engine_core_runtime.annotationKey)(ref)];
5417
+ return !!record && !record.annotation.locked && (lender?.getAuthority(record.annotation).copy ?? false);
5418
+ });
5048
5419
  }
5049
5420
  };
5050
5421
  /** One relationship (`/IRT` + `/RT`) written onto every record, as one change. */
@@ -5523,7 +5894,7 @@ function createAnnotationController(ctx) {
5523
5894
  const ghost = createGhost(ctx, services, stamps);
5524
5895
  const render = createRenderReads(ctx, services, ghost, stamps);
5525
5896
  const icons = createIcons(ctx, services, stamps);
5526
- const selection = createSelectionWrites(ctx, services, annotations, properties, chrome, text);
5897
+ const selection = createSelectionWrites(ctx, services, annotations, properties, chrome, text, crud);
5527
5898
  const measurement = createMeasurement(ctx, services);
5528
5899
  const pointer = createPointer(ctx, services, chrome, measurement);
5529
5900
  const drafts = createDrafts(ctx, services, annotations);
@@ -5569,6 +5940,7 @@ function createAnnotationController(ctx) {
5569
5940
  canCreate: authority.canCreate,
5570
5941
  canUpdate: authority.canUpdate,
5571
5942
  canDelete: authority.canDelete,
5943
+ canDuplicate: authority.canDuplicate,
5572
5944
  onCreated: events.created.on,
5573
5945
  onUpdated: events.updated.on,
5574
5946
  onDeleted: events.deleted.on,