@stll/folio-core 0.75.0 → 0.76.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 (92) hide show
  1. package/dist/ai-edits/headless.d.ts +2 -1
  2. package/dist/ai-edits/headless.js +18 -12
  3. package/dist/ai-edits/pending-suggestions.js +2 -3
  4. package/dist/ai-edits/read.js +9 -3
  5. package/dist/ai-edits/types.d.ts +9 -4
  6. package/dist/canonical/batchCommentReferences.js +2 -1
  7. package/dist/canonical/canonicalBatchReview.js +5 -8
  8. package/dist/canonical/canonicalComments.js +8 -2
  9. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  10. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  11. package/dist/canonical/canonicalPublicOperations.js +203 -71
  12. package/dist/canonical/canonicalSession.js +3 -1
  13. package/dist/controller/canonicalClipboard.d.ts +1 -1
  14. package/dist/controller/canonicalClipboard.js +71 -17
  15. package/dist/controller/canonicalContentControlValue.js +7 -7
  16. package/dist/controller/canonicalReview.d.ts +21 -0
  17. package/dist/controller/canonicalReview.js +44 -9
  18. package/dist/controller/canonicalStructure.d.ts +1 -2
  19. package/dist/controller/canonicalStructure.js +51 -24
  20. package/dist/controller/fontReadiness.js +50 -23
  21. package/dist/controller/hiddenEditorManager.js +5 -20
  22. package/dist/docx/bulletMarkers.d.ts +8 -0
  23. package/dist/docx/bulletMarkers.js +9 -1
  24. package/dist/docx/canonicalSessionInput.js +25 -11
  25. package/dist/docx/ensureParaIds.d.ts +31 -0
  26. package/dist/docx/ensureParaIds.js +57 -32
  27. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  28. package/dist/docx/ensureUniqueControlIds.js +47 -29
  29. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  30. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  31. package/dist/docx/server/templatePlan/apply.js +62 -8
  32. package/dist/docx/server/templatePlan/blocks.d.ts +55 -3
  33. package/dist/docx/server/templatePlan/blocks.js +182 -6
  34. package/dist/docx/server/templatePlan/builders.d.ts +16 -1
  35. package/dist/docx/server/templatePlan/builders.js +31 -3
  36. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  37. package/dist/docx/server/templatePlan/effects.js +188 -0
  38. package/dist/docx/server/templatePlan/emit.d.ts +2 -1
  39. package/dist/docx/server/templatePlan/emit.js +44 -2
  40. package/dist/docx/server/templatePlan/inspect.js +21 -1
  41. package/dist/docx/server/templatePlan/labels.js +16 -1
  42. package/dist/docx/server/templatePlan/plan.d.ts +12 -3
  43. package/dist/docx/server/templatePlan/plan.js +36 -12
  44. package/dist/docx/server/templatePlan/planShape.js +47 -22
  45. package/dist/docx/server/templatePlan/revisions.d.ts +46 -0
  46. package/dist/docx/server/templatePlan/revisions.js +407 -0
  47. package/dist/docx/server/templatePlan/story.d.ts +15 -1
  48. package/dist/docx/server/templatePlan/story.js +50 -2
  49. package/dist/docx/server/templatePlan/types.d.ts +217 -1
  50. package/dist/docx/server/templatePlan/verify.js +117 -8
  51. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  52. package/dist/docx/server/templatePlan/xml.js +4 -1
  53. package/dist/internal/revisionResolutionStep.d.ts +2 -31
  54. package/dist/internal/revisionResolutionStep.js +2 -171
  55. package/dist/prosemirror/commands/comments.d.ts +6 -234
  56. package/dist/prosemirror/commands/comments.js +5 -2464
  57. package/dist/prosemirror/commands/index.d.ts +4 -2
  58. package/dist/prosemirror/commands/index.js +4 -2
  59. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -11
  60. package/dist/prosemirror/commands/tableCellMergeResolution.js +3 -154
  61. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  62. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  63. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  64. package/dist/prosemirror/paraIds.d.ts +1 -14
  65. package/dist/prosemirror/paraIds.js +1 -14
  66. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  67. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  68. package/dist/prosemirror/projectionReview.d.ts +49 -0
  69. package/dist/prosemirror/projectionReview.js +292 -0
  70. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  71. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  72. package/dist/prosemirror/replacedAnnotations.d.ts +2 -5
  73. package/dist/prosemirror/replacedAnnotations.js +1 -10
  74. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  75. package/dist/prosemirror/revisionCarriers.js +15 -1
  76. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  77. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  78. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  79. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  80. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  81. package/dist/prosemirror/suggestionQueries.js +320 -0
  82. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  83. package/dist/prosemirror/tableGridMutation.js +1 -78
  84. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  85. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  86. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  87. package/dist/server.d.ts +2 -2
  88. package/dist/types/canonicalCapabilities.d.ts +1 -25
  89. package/dist/types/canonicalCapabilities.js +1 -23
  90. package/package.json +2 -2
  91. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  92. package/dist/internal/headlessRevisionResolutionGuard.js +0 -18
@@ -978,6 +978,7 @@ const intentStory = (intent) => {
978
978
  case "replaceFragment":
979
979
  case "pasteBlocks":
980
980
  case "moveFragment":
981
+ case "moveBlocks":
981
982
  case "replaceText":
982
983
  case "formatRun":
983
984
  case "insertAtom": return intent.from.story;
@@ -1374,7 +1375,8 @@ var CanonicalSession = class {
1374
1375
  case "insertHyperlink":
1375
1376
  case "replaceFragment":
1376
1377
  case "pasteBlocks":
1377
- case "moveFragment": return true;
1378
+ case "moveFragment":
1379
+ case "moveBlocks": return true;
1378
1380
  case "replaceText":
1379
1381
  case "insertAtom":
1380
1382
  case "formatRun":
@@ -29,5 +29,5 @@ type PrepareCanonicalPasteOptions = {
29
29
  to: number;
30
30
  };
31
31
  };
32
- export declare const prepareCanonicalPaste: ({ session, state, slice, plain, moveTarget, pasteTarget, sourceDocument, moveSource }: PrepareCanonicalPasteOptions) => Result<CanonicalCommit, CanonicalSessionError>;
32
+ export declare const prepareCanonicalPaste: ({ session, state, slice: copied, plain, moveTarget, pasteTarget, sourceDocument, moveSource }: PrepareCanonicalPasteOptions) => Result<CanonicalCommit, CanonicalSessionError>;
33
33
  export {};
@@ -9,6 +9,7 @@ import { canonicalSelectionRange } from "../prosemirror/canonicalSelectionRange.
9
9
  import { proseDocToBlocks } from "../prosemirror/conversion/fromProseDoc.js";
10
10
  import { completeNumberingForDoc } from "../prosemirror/listInstanceReferences.js";
11
11
  import { marksToTextFormatting } from "../prosemirror/runFormattingFromMarks.js";
12
+ import { pastedCells } from "../prosemirror/tableCellPaste.js";
12
13
  import { CANONICAL_CONDITION, CANONICAL_GAP } from "../types/canonicalCapabilities.js";
13
14
  import { readModel } from "../types/documentModel.js";
14
15
  import { bytesToDataUrl } from "../utils/base64.js";
@@ -17,7 +18,7 @@ import { flattenClipboardStyleReferences, importClipboardStyles } from "./canoni
17
18
  import { Result, panic } from "better-result";
18
19
  import { NUMBER_FORMATS, paragraphNumberingReference, relationshipIdOf } from "@stll/docx-core/model";
19
20
  import { packageResourcesOpOf } from "@stll/docx-core/ops";
20
- import { CellSelection } from "prosemirror-tables";
21
+ import { CellSelection, tableNodeTypes } from "prosemirror-tables";
21
22
  import { Fragment, Slice } from "prosemirror-model";
22
23
  // src/controller/canonicalClipboard.ts
23
24
  /** A refusal under the gap, rule or condition it belongs to. */
@@ -29,16 +30,61 @@ const refuse = (message, ground) => Result.err(new CanonicalSessionError({
29
30
  /** Clipboard content the paste cannot read or resolve as given. */
30
31
  const INVALID_CLIPBOARD = { condition: CANONICAL_CONDITION.invalidRequest };
31
32
  /**
32
- * The gap a clipboard block the paste cannot place falls under: a table's,
33
- * or for any other block, the story content the session cannot project.
33
+ * The gap a clipboard block the paste cannot place falls under: a block
34
+ * other than a paragraph or a table, at the top or in a cell, is story
35
+ * content the session cannot project.
34
36
  */
35
- const unplacedBlockGround = (slice) => {
36
- let table = false;
37
- slice.content.descendants((node) => {
38
- if (node.type.name === "table") table = true;
39
- return !table;
40
- });
41
- return { gap: table ? CANONICAL_GAP.trackedTableStructure : CANONICAL_GAP.storyContentProjection };
37
+ const UNPLACED_BLOCK = { gap: CANONICAL_GAP.storyContentProjection };
38
+ const tableRole = (node) => node?.type.spec["tableRole"];
39
+ /**
40
+ * A table the clipboard holds part of, opened `left` levels deep at its start
41
+ * and `right` at its end, as the table of the cells it holds: a first or last
42
+ * row cut short keeps the cells copied and is filled out with empty ones.
43
+ * Undefined when the part holds no cells.
44
+ */
45
+ const closedTable = (table, left, right) => {
46
+ if (left <= 1 && right <= 1) return table;
47
+ const cells = pastedCells(new Slice(Fragment.from(table), left, right));
48
+ if (cells === null) return void 0;
49
+ const rowType = tableNodeTypes(table.type.schema).row;
50
+ return table.type.create(table.attrs, cells.rows.map((row, index) => rowType.create(index < table.childCount ? table.child(index).attrs : null, row)), table.marks);
51
+ };
52
+ /**
53
+ * A slice that opens or closes inside a table, its edges closed at the table:
54
+ * it pastes the table of the cells it holds, as a selection of cells pastes.
55
+ * Selected cells, rows or cells without their table, paste as a table
56
+ * of their own. The slice is returned as given when no table edge is open,
57
+ * and undefined when an open table edge holds no cells.
58
+ */
59
+ const withClosedTableEdges = (slice) => {
60
+ const { content } = slice;
61
+ const first = content.firstChild;
62
+ const last = content.lastChild;
63
+ const role = tableRole(first);
64
+ if (role === "row" || role === "cell" || role === "header_cell") {
65
+ if (first === null) return slice;
66
+ const cells = pastedCells(slice);
67
+ if (cells === null) return void 0;
68
+ const { table, row } = tableNodeTypes(first.type.schema);
69
+ return new Slice(Fragment.from(table.create(null, cells.rows.map((cellsOfRow) => row.create(null, cellsOfRow)))), 0, 0);
70
+ }
71
+ const opensTable = slice.openStart > 1 && tableRole(first) === "table";
72
+ const closesTable = slice.openEnd > 1 && tableRole(last) === "table";
73
+ if (!opensTable && !closesTable) return slice;
74
+ const blocks = [];
75
+ content.forEach((node) => blocks.push(node));
76
+ const lastIndex = blocks.length - 1;
77
+ const edges = /* @__PURE__ */ new Set();
78
+ if (opensTable) edges.add(0);
79
+ if (closesTable) edges.add(lastIndex);
80
+ for (const index of edges) {
81
+ const node = blocks[index];
82
+ if (node === void 0) continue;
83
+ const closed = closedTable(node, opensTable && index === 0 ? slice.openStart : 0, closesTable && index === lastIndex ? slice.openEnd : 0);
84
+ if (closed === void 0) return void 0;
85
+ blocks[index] = closed;
86
+ }
87
+ return new Slice(Fragment.from(blocks), opensTable ? 1 : slice.openStart, closesTable ? 1 : slice.openEnd);
42
88
  };
43
89
  /**
44
90
  * A pasted block's paragraphs in document order, a table's cell paragraphs
@@ -280,14 +326,16 @@ const clipboardAnnotations = ({ paragraphs, source }) => {
280
326
  if (annotations.notes.length !== notes.size || annotations.comments.length !== comments.size) return refusal("A clipboard comment or note reference names none in the document it was copied from.");
281
327
  return Result.ok(annotations);
282
328
  };
283
- const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarget, pasteTarget, sourceDocument, moveSource }) => {
329
+ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, moveTarget, pasteTarget, sourceDocument, moveSource }) => {
284
330
  if (session.isComposing) return refuse("Composition must finish before using the clipboard.", { condition: CANONICAL_CONDITION.composing });
285
- if (slice.content.size === 0) return Result.err(new CanonicalSessionError({
331
+ if (copied.content.size === 0) return Result.err(new CanonicalSessionError({
286
332
  ground: INVALID_CLIPBOARD,
287
333
  message: "The clipboard contains no content.",
288
334
  reason: "noChange"
289
335
  }));
290
- if (slice.openStart > 1 || slice.openEnd > 1) return refuse("Clipboard tables and nested block containers require canonical table editing.", unplacedBlockGround(slice));
336
+ const slice = withClosedTableEdges(copied);
337
+ if (slice === void 0) return refuse("The clipboard table holds no cells.", INVALID_CLIPBOARD);
338
+ if (slice.openStart > 1 || slice.openEnd > 1) return refuse("Clipboard tables and nested block containers require canonical table editing.", UNPLACED_BLOCK);
291
339
  const paragraphType = state.schema.nodes["paragraph"];
292
340
  if (paragraphType === void 0) return refuse("Clipboard input requires a paragraph schema.", { condition: CANONICAL_CONDITION.internal });
293
341
  const tableType = state.schema.nodes["table"];
@@ -297,7 +345,7 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
297
345
  inline &&= node.isInline;
298
346
  blocksOnly &&= node.type === paragraphType || node.type === tableType;
299
347
  });
300
- if (!inline && !blocksOnly) return refuse("Clipboard tables and embedded blocks require canonical table editing.", unplacedBlockGround(slice));
348
+ if (!inline && !blocksOnly) return refuse("Clipboard tables and embedded blocks require canonical table editing.", UNPLACED_BLOCK);
301
349
  const importedSlice = inline ? new Slice(Fragment.from(paragraphType.create(null, slice.content)), 1, 1) : slice;
302
350
  const converted = Result.try({
303
351
  try: () => proseDocToBlocks(state.schema.topNodeType.create(null, importedSlice.content), []),
@@ -310,7 +358,7 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
310
358
  if (converted.isErr()) return converted;
311
359
  const blocks = [];
312
360
  for (const block of converted.value) {
313
- if (block.type !== "paragraph" && block.type !== "table" || clipboardParagraphs(block) === void 0) return refuse("The clipboard contains an unsupported block.", unplacedBlockGround(slice));
361
+ if (block.type !== "paragraph" && block.type !== "table" || clipboardParagraphs(block) === void 0) return refuse("The clipboard contains an unsupported block.", UNPLACED_BLOCK);
314
362
  blocks.push(cloneClipboardBlock(block));
315
363
  }
316
364
  const places = blocks.flatMap((block, index) => clipboardParagraphs(block, (next) => {
@@ -651,17 +699,23 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
651
699
  resourceOps,
652
700
  semantic: "paste"
653
701
  });
654
- if (topParagraphs.length !== blocks.length) return refuse("Moving a table by dragging requires a table move operation.", { gap: CANONICAL_GAP.trackedTableStructure });
655
702
  const target = session.projection.addressAt(moveTarget);
656
703
  if (target.isErr()) return target;
657
704
  return session.prepareIntents(state, {
658
- intents: [{
705
+ intents: [topParagraphs.length === blocks.length ? {
659
706
  type: "moveFragment",
660
707
  target: target.value,
661
708
  ...range,
662
709
  paragraphs: topParagraphs,
663
710
  openStart,
664
711
  openEnd
712
+ } : {
713
+ type: "moveBlocks",
714
+ target: target.value,
715
+ ...range,
716
+ blocks,
717
+ openStart,
718
+ openEnd
665
719
  }],
666
720
  resourceOps,
667
721
  semantic: "paste"
@@ -1,7 +1,7 @@
1
1
  import { CanonicalSessionError } from "../canonical/canonicalSession.js";
2
2
  import { ContentControlBoundError, ContentControlLockedError, ContentControlTypeError } from "../content-controls/errors.js";
3
3
  import { setContentControlValue } from "../content-controls/mutateContentControls.js";
4
- import { CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
4
+ import { CANONICAL_CONDITION, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
5
5
  import { readModel } from "../types/documentModel.js";
6
6
  import { Result, panic } from "better-result";
7
7
  import { DOCUMENT_OP_TYPES, blockControlHolding, storyBody } from "@stll/docx-core/ops";
@@ -14,35 +14,35 @@ import { DOCUMENT_OP_TYPES, blockControlHolding, storyBody } from "@stll/docx-co
14
14
  * The headless content-control rules decide the new value: a lock, a type
15
15
  * mismatch or a data binding refuses, and the refusal names its ground.
16
16
  */
17
- const refuse = (message, ground = { gap: CANONICAL_GAP.commands }) => Result.err(new CanonicalSessionError({
17
+ const refuse = (message, ground) => Result.err(new CanonicalSessionError({
18
18
  ground,
19
19
  message,
20
20
  reason: "refused"
21
21
  }));
22
22
  const prepareContentControlValue = (session, state, command) => {
23
23
  const node = session.projection.doc.nodeAt(command.at);
24
- if (node?.type.name !== "blockSdt") return refuse("The content control is no longer there.");
24
+ if (node?.type.name !== "blockSdt") return refuse("The content control is no longer there.", { condition: CANONICAL_CONDITION.stale });
25
25
  let paragraphsOnly = node.childCount > 0;
26
26
  node.forEach((child) => {
27
27
  if (child.type.name !== "paragraph") paragraphsOnly = false;
28
28
  });
29
- if (!paragraphsOnly) return refuse("A control that holds more than paragraphs has no value.");
29
+ if (!paragraphsOnly) return refuse("A control that holds more than paragraphs has no value.", { condition: CANONICAL_CONDITION.invalidRequest });
30
30
  const from = session.projection.addressAt(command.at + 2);
31
31
  if (from.isErr()) return from;
32
32
  const to = session.projection.addressAt(command.at + node.nodeSize - 2);
33
33
  if (to.isErr()) return to;
34
34
  const document = readModel(session.document);
35
35
  const held = blockControlHolding(storyBody(document, from.value.story).content, from.value.blockId);
36
- if (held === void 0) return refuse("The content control is no longer there.");
36
+ if (held === void 0) return refuse("The content control is no longer there.", { condition: CANONICAL_CONDITION.stale });
37
37
  const { control } = held;
38
38
  const controlId = control.properties.id;
39
- if (controlId === void 0) return refuse("A content control without an id cannot be set.");
39
+ if (controlId === void 0) return refuse("A content control without an id cannot be set.", { condition: CANONICAL_CONDITION.invalidRequest });
40
40
  let next;
41
41
  try {
42
42
  next = setContentControlValue({ package: { document: { content: [control] } } }, { id: controlId }, command.input).package.document.content.at(0);
43
43
  } catch (error) {
44
44
  if (error instanceof ContentControlLockedError) return refuse(error.message, { rule: CANONICAL_RULE.contentControlLock });
45
- if (error instanceof ContentControlTypeError || error instanceof ContentControlBoundError) return refuse(error.message);
45
+ if (error instanceof ContentControlTypeError || error instanceof ContentControlBoundError) return refuse(error.message, { condition: CANONICAL_CONDITION.invalidRequest });
46
46
  throw error;
47
47
  }
48
48
  if (next?.type !== "blockSdt") return panic("A control's value keeps it a block-level control.");
@@ -1,4 +1,25 @@
1
1
  import { FolioEditor } from "./folioEditor.js";
2
+ import { EditorState } from "prosemirror-state";
3
+ import { OpStory } from "@stll/docx-core/ops";
4
+ export type ReviewRange = {
5
+ from: number;
6
+ to: number;
7
+ };
8
+ export type CanonicalReviewEditor = Pick<FolioEditor, "getCanonicalStoryProjection" | "getDocument">;
9
+ type CanonicalReviewLockOptions = {
10
+ editor: CanonicalReviewEditor | null | undefined;
11
+ state: EditorState;
12
+ story: OpStory;
13
+ target: ({
14
+ type: "range";
15
+ } & ReviewRange) | {
16
+ type: "revisions";
17
+ ids: readonly number[];
18
+ };
19
+ };
20
+ type HeldReviewRevisionIds = Record<"accept" | "reject", ReadonlySet<number>>;
21
+ /** Predict the session's lock decision for the groups its review will settle. */
22
+ export declare const canonicalReviewHeldRevisionIds: ({ editor, state, story, target }: CanonicalReviewLockOptions) => HeldReviewRevisionIds;
2
23
  type ResolveCanonicalReviewRangeOptions = {
3
24
  editor: Pick<FolioEditor, "getCanonicalDocument" | "getState" | "resolveCanonicalRevisions"> | null | undefined;
4
25
  from: number;
@@ -1,11 +1,11 @@
1
- import { getTrackedChangeGroupIdsFromDoc, getTrackedChangesFromDoc } from "../ai-edits/read.js";
2
- import { findAIEditRevisionRange } from "../prosemirror/commands/comments.js";
1
+ import { getTrackedChangeGroupIdsFromDoc, getTrackedChangeGroupsForIds, getTrackedChangesFromDoc } from "../ai-edits/read.js";
2
+ import { hasLockedControls } from "../canonical/canonicalLockGuard.js";
3
+ import { canonicalRevisionLocks } from "../canonical/canonicalRevisionLocks.js";
4
+ import { findAIEditRevisionRange } from "../prosemirror/revisionRangeQueries.js";
5
+ import { readModel } from "../types/documentModel.js";
6
+ import { OP_STORIES } from "@stll/docx-core/ops";
3
7
  // src/controller/canonicalReview.ts
4
- /** Null when the editor holds no canonical session, which leaves the review as it is. */
5
- const resolveCanonicalReviewRange = ({ editor, from, to, resolution }) => {
6
- if (!editor?.getCanonicalDocument()) return null;
7
- const state = editor.getState();
8
- if (!state) return false;
8
+ const revisionIdsAtRange = (state, { from, to }) => {
9
9
  const ids = /* @__PURE__ */ new Set();
10
10
  for (const change of getTrackedChangesFromDoc(state.doc)) {
11
11
  const groupIds = getTrackedChangeGroupIdsFromDoc(state.doc, change.id);
@@ -13,6 +13,41 @@ const resolveCanonicalReviewRange = ({ editor, from, to, resolution }) => {
13
13
  if (!range) continue;
14
14
  if (from === to ? range.from <= from && range.to >= to : range.from < to && range.to > from) for (const id of groupIds) ids.add(id);
15
15
  }
16
- return ids.size > 0 && editor.resolveCanonicalRevisions([...ids], resolution);
16
+ return [...ids];
17
+ };
18
+ const NO_HELD_REVISIONS = {
19
+ accept: /* @__PURE__ */ new Set(),
20
+ reject: /* @__PURE__ */ new Set()
21
+ };
22
+ /** Predict the session's lock decision for the groups its review will settle. */
23
+ const canonicalReviewHeldRevisionIds = ({ editor, state, story, target }) => {
24
+ if (!editor?.getCanonicalStoryProjection(OP_STORIES.MAIN)) return NO_HELD_REVISIONS;
25
+ const model = editor.getDocument();
26
+ if (!model) return NO_HELD_REVISIONS;
27
+ const document = readModel(model);
28
+ if (!hasLockedControls(document)) return NO_HELD_REVISIONS;
29
+ const ids = target.type === "range" ? revisionIdsAtRange(state, target) : target.ids;
30
+ const groups = getTrackedChangeGroupsForIds(state.doc, ids);
31
+ const heldIds = (decision) => new Set(canonicalRevisionLocks({
32
+ document,
33
+ story,
34
+ groups,
35
+ decision
36
+ }).held.flatMap((group) => group.ids));
37
+ return {
38
+ accept: heldIds("accept"),
39
+ reject: heldIds("reject")
40
+ };
41
+ };
42
+ /** Null when the editor holds no canonical session, which leaves the review as it is. */
43
+ const resolveCanonicalReviewRange = ({ editor, from, to, resolution }) => {
44
+ if (!editor?.getCanonicalDocument()) return null;
45
+ const state = editor.getState();
46
+ if (!state) return false;
47
+ const ids = revisionIdsAtRange(state, {
48
+ from,
49
+ to
50
+ });
51
+ return ids.length > 0 && editor.resolveCanonicalRevisions(ids, resolution);
17
52
  };
18
- export { resolveCanonicalReviewRange };
53
+ export { canonicalReviewHeldRevisionIds, resolveCanonicalReviewRange };
@@ -5,14 +5,13 @@ import { CanonicalStructureInput } from "./canonicalInput.js";
5
5
  import { Result } from "better-result";
6
6
  import { EditorState } from "prosemirror-state";
7
7
  import { OpStory } from "@stll/docx-core/ops";
8
- export declare const CELL_SELECTION_PLACEMENT_REFUSAL = "A note or table of contents goes at a caret, not over selected cells.";
9
8
  /** Whether a paragraph is in a list, by numbering of its own or its style's. */
10
9
  export declare const isCanonicalListParagraph: (paragraph: document_d_exports.Paragraph | undefined) => boolean;
11
10
  /**
12
11
  * Toolbar meanings enter the same operation journal as native input, in the
13
12
  * story whose editor holds `state`: the body, or a header, footer or note.
14
13
  */
15
- export declare const prepareCanonicalCommands: (session: CanonicalSession, state: EditorState, commands: readonly CanonicalCommandIntent[], story?: OpStory) => Result<CanonicalCommit, CanonicalSessionError>;
14
+ export declare const prepareCanonicalCommands: (session: CanonicalSession, state: EditorState, requested: readonly CanonicalCommandIntent[], story?: OpStory) => Result<CanonicalCommit, CanonicalSessionError>;
16
15
  /**
17
16
  * The structure edit a key asks for at the selection of the editor showing
18
17
  * `story`, the body or a header, footer or note, as one commit: Enter splits
@@ -4,11 +4,12 @@ import { createNote } from "../docx/noteReferenceMark.js";
4
4
  import { getCachedNumberingMap, numberingLevelUsesBulletMarker } from "../docx/numberingParser.js";
5
5
  import { cloneParagraphWithoutPropertySource } from "../docx/paragraphPropertySource.js";
6
6
  import { visitDocxParagraphs } from "../docx/paragraphTraversal.js";
7
+ import { canonicalCellSelectionRanges } from "../prosemirror/canonicalSelectionRange.js";
7
8
  import { listRequestsForMarker } from "../prosemirror/listAutoformatMarkers.js";
8
9
  import { unusedListInstanceFor } from "../prosemirror/listNumbering.js";
9
10
  import { effectiveParagraphNumbering, paragraphNumberingSourcesFromBoundary } from "../prosemirror/numberingAttr.js";
10
11
  import { createStyleResolver } from "../prosemirror/styles/styleResolver.js";
11
- import { CANONICAL_CONDITION, CANONICAL_GAP } from "../types/canonicalCapabilities.js";
12
+ import { CANONICAL_CONDITION } from "../types/canonicalCapabilities.js";
12
13
  import { readModel } from "../types/documentModel.js";
13
14
  import { maxOf } from "../utils/extremes.js";
14
15
  import { collectHeadings } from "../utils/headingCollector.js";
@@ -31,14 +32,14 @@ const currentSectionEndpoint = (paragraph) => {
31
32
  if (Object.hasOwn(paragraph, "sectionProperties")) return { type: "undefined" };
32
33
  return { type: "omitted" };
33
34
  };
34
- const CELL_SELECTION_PLACEMENT_REFUSAL = "A note or table of contents goes at a caret, not over selected cells.";
35
- const refuse = (message) => Result.err(new CanonicalSessionError({
36
- ground: { gap: CANONICAL_GAP.commands },
35
+ const refuse = (message, condition) => Result.err(new CanonicalSessionError({
36
+ ground: { condition },
37
37
  message,
38
38
  reason: "refused"
39
39
  }));
40
+ /** The request asks for nothing to change; hosts report no refusal for it. */
40
41
  const noChange = (message) => Result.err(new CanonicalSessionError({
41
- ground: { gap: CANONICAL_GAP.commands },
42
+ ground: { condition: CANONICAL_CONDITION.invalidRequest },
42
43
  message,
43
44
  reason: "noChange"
44
45
  }));
@@ -78,9 +79,9 @@ const paragraphPositions = (projection, paragraphs) => {
78
79
  const positions = [];
79
80
  for (const paragraph of paragraphs) {
80
81
  const address = projection.paragraph(paragraph.paraId ?? "");
81
- if (address === void 0) return refuse("A selected paragraph has no canonical address.");
82
+ if (address === void 0) return refuse("A selected paragraph has no canonical address.", CANONICAL_CONDITION.stale);
82
83
  const index = address.container.findIndex((item) => item === paragraph);
83
- if (index < 0) return refuse("A selected paragraph is missing from its block container.");
84
+ if (index < 0) return refuse("A selected paragraph is missing from its block container.", CANONICAL_CONDITION.stale);
84
85
  positions.push({
85
86
  container: address.container,
86
87
  index,
@@ -190,21 +191,48 @@ const numberingIntent = (session, positions, request, story = OP_STORIES.MAIN) =
190
191
  };
191
192
  };
192
193
  /**
194
+ * Note and contents commands over selected cells, placed as over the text
195
+ * they hold: a note reference follows the selected text, at the end of the
196
+ * last selected cell's text; a table of contents goes where the selection
197
+ * starts, at the start of the first selected cell's text. A note reference is
198
+ * deleted only from a selected cell, not from a cell the range passes over.
199
+ */
200
+ const placeInSelectedCells = (state, commands) => {
201
+ const { selection } = state;
202
+ if (!(selection instanceof CellSelection)) return commands;
203
+ const ranges = canonicalCellSelectionRanges(selection);
204
+ const first = ranges.at(0);
205
+ const last = ranges.at(-1);
206
+ if ((first === void 0 || last === void 0) && commands.some(({ type }) => type === "insertNote" || type === "generateTOC")) return null;
207
+ return commands.flatMap((command) => {
208
+ switch (command.type) {
209
+ case "insertNote": return last === void 0 ? [] : [{
210
+ ...command,
211
+ at: last.to
212
+ }];
213
+ case "generateTOC": return first === void 0 ? [] : [{
214
+ ...command,
215
+ at: first.from
216
+ }];
217
+ case "deleteNote": return ranges.some(({ from, to }) => from <= command.from && command.from <= to) ? [command] : [];
218
+ default: return [command];
219
+ }
220
+ });
221
+ };
222
+ /**
193
223
  * Toolbar meanings enter the same operation journal as native input, in the
194
224
  * story whose editor holds `state`: the body, or a header, footer or note.
195
225
  */
196
- const prepareCanonicalCommands = (session, state, commands, story = OP_STORIES.MAIN) => {
197
- if (story !== OP_STORIES.MAIN && commands.some(({ type }) => type === "setSectionBreak" || type === "removeSectionBreak" || type === "insertNote" || type === "deleteNote" || type === "generateTOC")) return Result.err(new CanonicalSessionError({
198
- ground: { condition: CANONICAL_CONDITION.invalidRequest },
199
- message: "Section breaks, notes and tables of contents go in the main story.",
200
- reason: "refused"
201
- }));
226
+ const prepareCanonicalCommands = (session, state, requested, story = OP_STORIES.MAIN) => {
227
+ if (story !== OP_STORIES.MAIN && requested.some(({ type }) => type === "setSectionBreak" || type === "removeSectionBreak" || type === "insertNote" || type === "deleteNote" || type === "generateTOC")) return refuse("Section breaks, notes and tables of contents go in the main story.", CANONICAL_CONDITION.invalidRequest);
202
228
  const projected = session.projectStory(story);
203
229
  if (projected.isErr()) return projected;
204
230
  const projection = projected.value;
231
+ const commands = placeInSelectedCells(state, requested);
232
+ if (commands === null) return refuse("The selected cells hold no text for a note or a table of contents.", CANONICAL_CONDITION.invalidRequest);
205
233
  const replacements = commands.filter((command) => command.type === "replaceText");
206
234
  if (replacements.length > 0) {
207
- if (replacements.length !== commands.length) return refuse("A text replacement must be prepared on its own.");
235
+ if (replacements.length !== commands.length) return refuse("A text replacement must be prepared on its own.", CANONICAL_CONDITION.invalidRequest);
208
236
  const [only] = replacements;
209
237
  if (only !== void 0 && replacements.length === 1) return session.prepareReplace(state, {
210
238
  from: only.from,
@@ -228,19 +256,18 @@ const prepareCanonicalCommands = (session, state, commands, story = OP_STORIES.M
228
256
  }
229
257
  return session.prepareIntents(state, { intents });
230
258
  }
231
- if (state.selection instanceof CellSelection && commands.some(({ type }) => type === "generateTOC" || type === "insertNote" || type === "deleteNote")) return refuse(CELL_SELECTION_PLACEMENT_REFUSAL);
232
259
  const intents = [];
233
260
  const valueCommands = commands.filter((command) => command.type === "setContentControlValue");
234
261
  if (valueCommands.length > 0) {
235
262
  const [valueCommand] = valueCommands;
236
- if (valueCommand === void 0 || commands.length !== 1) return refuse("A content control's value must be set on its own.");
263
+ if (valueCommand === void 0 || commands.length !== 1) return refuse("A content control's value must be set on its own.", CANONICAL_CONDITION.invalidRequest);
237
264
  return prepareContentControlValue(session, state, valueCommand);
238
265
  }
239
266
  const sectionCommands = commands.filter((command) => command.type === "setSectionBreak" || command.type === "removeSectionBreak");
240
267
  if (sectionCommands.length > 0) {
241
- if (sectionCommands.length !== commands.length || sectionCommands.length !== 1) return refuse("A section change must be prepared on its own.");
268
+ if (sectionCommands.length !== commands.length || sectionCommands.length !== 1) return refuse("A section change must be prepared on its own.", CANONICAL_CONDITION.invalidRequest);
242
269
  const paragraphs = selectedParagraphs(projection, state, true);
243
- if (paragraphs.length === 0) return refuse("Section breaks require a top-level document paragraph.");
270
+ if (paragraphs.length === 0) return refuse("Section breaks require a top-level document paragraph.", CANONICAL_CONDITION.invalidRequest);
244
271
  const command = sectionCommands.at(0) ?? panic("A section command was counted.");
245
272
  return session.prepareOperations(state, paragraphs.map((paragraph) => {
246
273
  const current = paragraph.sectionProperties;
@@ -265,7 +292,7 @@ const prepareCanonicalCommands = (session, state, commands, story = OP_STORIES.M
265
292
  const paragraphs = selectedParagraphs(projection, state);
266
293
  const noteCommands = commands.filter((command) => command.type === "insertNote" || command.type === "deleteNote");
267
294
  if (noteCommands.length > 0) {
268
- if (noteCommands.length !== commands.length) return refuse("Note changes must be prepared on their own.");
295
+ if (noteCommands.length !== commands.length) return refuse("Note changes must be prepared on their own.", CANONICAL_CONDITION.invalidRequest);
269
296
  const ops = [];
270
297
  const ordered = noteCommands.toReversed();
271
298
  const blockIdGroups = session.freshBlockIds(ordered.map((command) => command.type === "insertNote" ? command.content.length : 0));
@@ -286,7 +313,7 @@ const prepareCanonicalCommands = (session, state, commands, story = OP_STORIES.M
286
313
  }
287
314
  const at = projection.addressAt(command.at);
288
315
  if (at.isErr()) return at;
289
- if (command.content.some((block) => block.type !== "paragraph")) return refuse("Canonical note insertion requires paragraph content.");
316
+ if (command.content.some((block) => block.type !== "paragraph")) return refuse("Canonical note insertion requires paragraph content.", CANONICAL_CONDITION.invalidRequest);
290
317
  const blockIds = blockIdGroups.value[commandIndex] ?? panic("A fresh identity group was reserved per note.");
291
318
  const content = command.content.map((block, index) => {
292
319
  if (block.type !== "paragraph") panic("Canonical note content was already validated.");
@@ -311,7 +338,7 @@ const prepareCanonicalCommands = (session, state, commands, story = OP_STORIES.M
311
338
  const address = projection.addressAt(heading.pmPos + 1);
312
339
  if (address.isErr()) return address;
313
340
  const outline = headingOutlineLevel(heading.level);
314
- if (outline?.kind !== "heading") return refuse("A TOC heading has an invalid outline level.");
341
+ if (outline?.kind !== "heading") return refuse("A TOC heading has an invalid outline level.", CANONICAL_CONDITION.invalidRequest);
315
342
  const styleId = styles.styleIdForTableOfContentsLevel(outline.level + 1);
316
343
  headings.push({
317
344
  blockId: address.value.blockId,
@@ -580,9 +607,9 @@ const prepareCanonicalCommands = (session, state, commands, story = OP_STORIES.M
580
607
  };
581
608
  } else {
582
609
  const start = command.start ?? 1;
583
- if (!Number.isSafeInteger(start) || start < 0) return refuse("The numbering start must be a non-negative integer.");
610
+ if (!Number.isSafeInteger(start) || start < 0) return refuse("The numbering start must be a non-negative integer.", CANONICAL_CONDITION.invalidRequest);
584
611
  const original = definitions.nums.find((num) => num.numId === numPr.numId);
585
- if (original === void 0) return refuse("The numbering instance does not exist.");
612
+ if (original === void 0) return refuse("The numbering instance does not exist.", CANONICAL_CONDITION.invalidRequest);
586
613
  targetId = maxOf(definitions.nums.map((num) => num.numId), 0) + 1;
587
614
  const level = numPr.ilvl ?? 0;
588
615
  target = {
@@ -753,4 +780,4 @@ const prepareCanonicalAutoformat = (session, state, typed) => {
753
780
  text: ""
754
781
  }, paragraphIntent] });
755
782
  };
756
- export { CELL_SELECTION_PLACEMENT_REFUSAL, isCanonicalListParagraph, prepareCanonicalAutoformat, prepareCanonicalCommands, prepareCanonicalStructure };
783
+ export { isCanonicalListParagraph, prepareCanonicalAutoformat, prepareCanonicalCommands, prepareCanonicalStructure };
@@ -124,8 +124,20 @@ function waitForInitialLayoutFonts(model, pmDoc, fontSet = getDocumentFontSet())
124
124
  */
125
125
  function collectLayoutText(documentModel, pmDoc) {
126
126
  const characters = /* @__PURE__ */ new Set([" "]);
127
+ const seenUnits = /* @__PURE__ */ new Uint8Array(65536);
128
+ seenUnits[32] = 1;
127
129
  const addText = (text) => {
128
- for (const character of text) if (character >= " ") characters.add(character);
130
+ for (let index = 0; index < text.length; index += 1) {
131
+ const unit = text.charCodeAt(index);
132
+ if (isHighSurrogate(unit) && isLowSurrogate(text.charCodeAt(index + 1))) {
133
+ characters.add(text.slice(index, index + 2));
134
+ index += 1;
135
+ continue;
136
+ }
137
+ if (unit < 32 || seenUnits[unit] === 1) continue;
138
+ seenUnits[unit] = 1;
139
+ characters.add(String.fromCharCode(unit));
140
+ }
129
141
  };
130
142
  pmDoc.descendants((node) => {
131
143
  if (node.isText) addText(node.text ?? "");
@@ -148,7 +160,9 @@ function collectInitialLayoutFontFaces(documentModel, pmDoc) {
148
160
  const faces = /* @__PURE__ */ new Map();
149
161
  const resolution = {
150
162
  fontAlternates: buildFontAlternates(documentModel?.package.fontTable),
151
- documentFontFacts: buildDocumentFontFacts(documentModel?.package.fontTable)
163
+ documentFontFacts: buildDocumentFontFacts(documentModel?.package.fontTable),
164
+ resolvedFamilies: /* @__PURE__ */ new Map(),
165
+ requested: /* @__PURE__ */ new Set()
152
166
  };
153
167
  addLayoutFontFamilyFace({
154
168
  faces,
@@ -261,14 +275,13 @@ function layoutDescriptorFromFormattingAndMarks(formatting, marks) {
261
275
  weight: bold ? 700 : 400
262
276
  };
263
277
  }
264
- function addLayoutFontFamilyFace({ faces, value, descriptor, fontAlternates, documentFontFacts, complexScriptDescriptor = descriptor }) {
278
+ function addLayoutFontFamilyFace({ faces, value, descriptor, complexScriptDescriptor = descriptor, ...resolution }) {
265
279
  if (typeof value === "string") {
266
280
  addLayoutFontFamilyNameFace({
267
281
  faces,
268
282
  family: value,
269
283
  descriptor,
270
- fontAlternates,
271
- documentFontFacts
284
+ ...resolution
272
285
  });
273
286
  return;
274
287
  }
@@ -278,42 +291,54 @@ function addLayoutFontFamilyFace({ faces, value, descriptor, fontAlternates, doc
278
291
  faces,
279
292
  value: fontFamily.ascii,
280
293
  descriptor,
281
- fontAlternates,
282
- documentFontFacts
294
+ ...resolution
283
295
  });
284
296
  addLayoutFontFamilyFace({
285
297
  faces,
286
298
  value: fontFamily.hAnsi,
287
299
  descriptor,
288
- fontAlternates,
289
- documentFontFacts
300
+ ...resolution
290
301
  });
291
302
  addLayoutFontFamilyFace({
292
303
  faces,
293
304
  value: fontFamily.cs,
294
305
  descriptor: complexScriptDescriptor,
295
- fontAlternates,
296
- documentFontFacts
306
+ ...resolution
297
307
  });
298
308
  addLayoutFontFamilyFace({
299
309
  faces,
300
310
  value: fontFamily.eastAsia,
301
311
  descriptor,
302
- fontAlternates,
303
- documentFontFacts
312
+ ...resolution
304
313
  });
305
314
  }
306
- function addLayoutFontFamilyNameFace({ faces, family, descriptor, fontAlternates, documentFontFacts }) {
315
+ function addLayoutFontFamilyNameFace({ faces, family, descriptor, ...resolution }) {
316
+ const request = `${family}|${descriptor.style}|${descriptor.weight}`;
317
+ if (resolution.requested.has(request)) return;
318
+ resolution.requested.add(request);
319
+ for (const resolved of resolveLayoutFamilies(family, resolution)) addLayoutFontFace(faces, resolved, descriptor);
320
+ }
321
+ /**
322
+ * The families an authored name loads: the name, its alternate and the stack
323
+ * the renderer resolves it to, or none for a blank or generic name.
324
+ */
325
+ function resolveLayoutFamilies(family, resolution) {
326
+ const known = resolution.resolvedFamilies.get(family);
327
+ if (known !== void 0) return known;
307
328
  const normalized = family.trim();
308
- if (!normalized || CSS_GENERIC_FONT_FAMILIES.has(normalized)) return;
309
- addLayoutFontFace(faces, normalized, descriptor);
310
- const alternate = getFontAlternate(normalized, fontAlternates);
311
- if (alternate) addLayoutFontFace(faces, alternate, descriptor);
312
- for (const stackFamily of resolvedStackFamilies({
313
- family: normalized,
314
- alternate,
315
- documentFontFacts
316
- })) addLayoutFontFace(faces, stackFamily, descriptor);
329
+ const resolved = [];
330
+ if (normalized && !CSS_GENERIC_FONT_FAMILIES.has(normalized)) {
331
+ resolved.push(normalized);
332
+ const alternate = getFontAlternate(normalized, resolution.fontAlternates);
333
+ if (alternate) resolved.push(alternate);
334
+ resolved.push(...resolvedStackFamilies({
335
+ family: normalized,
336
+ alternate,
337
+ documentFontFacts: resolution.documentFontFacts
338
+ }));
339
+ }
340
+ resolution.resolvedFamilies.set(family, resolved);
341
+ return resolved;
317
342
  }
318
343
  function resolvedStackFamilies({ family, alternate, documentFontFacts }) {
319
344
  const { cssFallback } = resolveFontFamily(family, {
@@ -328,6 +353,8 @@ function addLayoutFontFace(faces, family, descriptor) {
328
353
  ...descriptor
329
354
  });
330
355
  }
356
+ const isHighSurrogate = (unit) => unit >= 55296 && unit <= 56319;
357
+ const isLowSurrogate = (unit) => unit >= 56320 && unit <= 57343;
331
358
  function escapeCssFontFamily(family) {
332
359
  return family.replace(/\\/gu, "\\\\").replace(/"/gu, "\\\"");
333
360
  }