@stll/folio-core 0.76.0 → 0.78.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 +6 -4
  2. package/dist/ai-edits/headless.js +32 -15
  3. package/dist/ai-edits/pending-suggestions.d.ts +9 -0
  4. package/dist/ai-edits/pending-suggestions.js +11 -0
  5. package/dist/ai-edits/read.js +24 -1
  6. package/dist/ai-edits/table-geometry.js +12 -4
  7. package/dist/canonical/canonicalBatchReview.js +7 -6
  8. package/dist/canonical/canonicalInlineProjection.d.ts +2 -2
  9. package/dist/canonical/canonicalInlineProjection.js +2 -2
  10. package/dist/canonical/canonicalProjectionBlocks.d.ts +10 -1
  11. package/dist/canonical/canonicalPublicOperations.js +19 -40
  12. package/dist/canonical/canonicalSeedContent.d.ts +18 -3
  13. package/dist/canonical/canonicalSeedContent.js +28 -15
  14. package/dist/canonical/canonicalSession.d.ts +22 -12
  15. package/dist/canonical/canonicalSession.js +190 -194
  16. package/dist/compare/inline-provenance.js +8 -1
  17. package/dist/controller/canonicalClipboard.d.ts +2 -1
  18. package/dist/controller/canonicalClipboard.js +312 -47
  19. package/dist/controller/canonicalComposition.js +67 -14
  20. package/dist/controller/canonicalStoryEditor.js +2 -0
  21. package/dist/controller/hiddenEditorManager.js +2 -0
  22. package/dist/docx/importedIdCollisions.js +29 -4
  23. package/dist/docx/paragraphParser.js +1 -1
  24. package/dist/docx/reviewResolutionProvenance.d.ts +2 -0
  25. package/dist/docx/reviewResolutionProvenance.js +22 -2
  26. package/dist/docx/server/templatePlan/apply.js +47 -2
  27. package/dist/docx/server/templatePlan/blocks.d.ts +34 -7
  28. package/dist/docx/server/templatePlan/blocks.js +190 -13
  29. package/dist/docx/server/templatePlan/builders.d.ts +8 -1
  30. package/dist/docx/server/templatePlan/builders.js +21 -5
  31. package/dist/docx/server/templatePlan/emit.d.ts +2 -0
  32. package/dist/docx/server/templatePlan/emit.js +108 -6
  33. package/dist/docx/server/templatePlan/plan.d.ts +26 -1
  34. package/dist/docx/server/templatePlan/plan.js +181 -21
  35. package/dist/docx/server/templatePlan/planShape.js +15 -3
  36. package/dist/docx/server/templatePlan/revisions.d.ts +55 -0
  37. package/dist/docx/server/templatePlan/revisions.js +276 -2
  38. package/dist/docx/server/templatePlan/story.d.ts +58 -1
  39. package/dist/docx/server/templatePlan/story.js +176 -12
  40. package/dist/docx/server/templatePlan/types.d.ts +153 -1
  41. package/dist/docx/server/templatePlan/verify.js +58 -15
  42. package/dist/docx/settingsHeaderFooterUpdate.d.ts +1 -1
  43. package/dist/docx/tableGridXml.d.ts +3 -7
  44. package/dist/docx/tableGridXml.js +23 -15
  45. package/dist/docx/tableParser.js +3 -1
  46. package/dist/layout-bridge/convert/footnoteLayout.js +34 -8
  47. package/dist/prosemirror/canonicalMarkupDocument.d.ts +20 -0
  48. package/dist/prosemirror/canonicalMarkupDocument.js +73 -0
  49. package/dist/prosemirror/canonicalTableCommands.d.ts +1 -1
  50. package/dist/prosemirror/canonicalTableCommands.js +7 -9
  51. package/dist/prosemirror/conversion/markupViewSource.d.ts +17 -0
  52. package/dist/prosemirror/conversion/markupViewSource.js +11 -0
  53. package/dist/prosemirror/conversion/toProseDoc.d.ts +8 -0
  54. package/dist/prosemirror/conversion/toProseDoc.js +43 -19
  55. package/dist/prosemirror/independentMarkupProjection.d.ts +27 -0
  56. package/dist/prosemirror/independentMarkupProjection.js +147 -0
  57. package/dist/prosemirror/markupViewNotes.d.ts +1 -1
  58. package/dist/prosemirror/markupViewNotes.js +24 -27
  59. package/dist/prosemirror/markupViewPositionMap.d.ts +16 -0
  60. package/dist/prosemirror/markupViewPositionMap.js +316 -0
  61. package/dist/prosemirror/markupViewProjection.d.ts +3 -46
  62. package/dist/prosemirror/markupViewProjection.js +90 -17
  63. package/dist/prosemirror/replacedAnnotations.d.ts +4 -78
  64. package/dist/prosemirror/replacedAnnotations.js +11 -194
  65. package/dist/prosemirror/styles/styleResolver.d.ts +1 -0
  66. package/dist/prosemirror/styles/styleResolver.js +4 -1
  67. package/dist/server.d.ts +2 -2
  68. package/dist/types/canonicalCapabilities.d.ts +3 -10
  69. package/dist/types/canonicalCapabilities.js +3 -10
  70. package/package.json +2 -2
  71. package/dist/internal/revisionResolutionEdits.d.ts +0 -11
  72. package/dist/internal/revisionResolutionEdits.js +0 -18
  73. package/dist/internal/revisionResolutionInline.d.ts +0 -24
  74. package/dist/internal/revisionResolutionInline.js +0 -302
  75. package/dist/internal/revisionResolutionStep.d.ts +0 -3
  76. package/dist/internal/revisionResolutionStep.js +0 -113
  77. package/dist/internal/revisionResolutionTracking.d.ts +0 -9
  78. package/dist/internal/revisionResolutionTracking.js +0 -124
  79. package/dist/internal/wholeStoryRevisionResolution.d.ts +0 -56
  80. package/dist/internal/wholeStoryRevisionResolution.js +0 -783
  81. package/dist/prosemirror/commands/resolveAllTableChanges.d.ts +0 -38
  82. package/dist/prosemirror/commands/resolveAllTableChanges.js +0 -642
  83. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.d.ts +0 -13
  84. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.js +0 -45
  85. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +0 -8
  86. package/dist/prosemirror/commands/tableCellMergeResolution.js +0 -56
  87. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +0 -60
  88. package/dist/prosemirror/commands/tableMergeFoldDecisions.js +0 -78
  89. package/dist/prosemirror/rejoinRunCarriers.d.ts +0 -42
  90. package/dist/prosemirror/rejoinRunCarriers.js +0 -65
  91. package/dist/prosemirror/runPropertyChangeResolution.d.ts +0 -15
  92. package/dist/prosemirror/runPropertyChangeResolution.js +0 -34
@@ -545,7 +545,8 @@ export declare class FolioDocxReviewer {
545
545
  /**
546
546
  * Resolve one editable story to its original or final state, its staged
547
547
  * suggestions with its other changes. A suggestion that reaches another
548
- * story resolves only whole, through the suggestion methods. A lock that
548
+ * story resolves only in this one: its part in the others stays pending,
549
+ * for their own story resolution or the suggestion methods. A lock that
549
550
  * prevents any target change from resolving refuses before mutation.
550
551
  */
551
552
  resolveReviewedStory({ story, view }: FolioResolveReviewedStoryOptions): boolean;
@@ -722,7 +723,8 @@ export declare class FolioDocxReviewer {
722
723
  /**
723
724
  * One pending suggestion through the session's suggestion intent: rejected
724
725
  * with the comments it proposes, or adopted as ordinary tracked changes by
725
- * `author`. All stories belonging to the proposal publish together.
726
+ * `author`. All stories belonging to the proposal publish together, or
727
+ * only its part in `story`.
726
728
  */
727
729
  private resolveSuggestionOnSession;
728
730
  /**
@@ -764,8 +766,8 @@ export declare class FolioDocxReviewer {
764
766
  * A story holding staged suggestions resolved to `view`: its suggestions
765
767
  * resolve with its other changes, on a fork, and the fork's operations
766
768
  * land here as one commit, so a refusal leaves this reviewer as it was. A
767
- * suggestion that reaches another story resolves only whole, so resolving
768
- * one of its stories refuses.
769
+ * suggestion that reaches another story resolves here only in this story:
770
+ * its records in the others stay pending.
769
771
  */
770
772
  private resolveStoryWithSuggestions;
771
773
  /**
@@ -31,7 +31,7 @@ import { getFolioNodeRevisionCarriers } from "../prosemirror/revisionCarriers.js
31
31
  import { schema } from "../prosemirror/schema/index.js";
32
32
  import { sectionPropertiesOf } from "../prosemirror/sectionCarrier.js";
33
33
  import { getSuggestions } from "../prosemirror/suggestionQueries.js";
34
- import { CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
34
+ import { CANONICAL_CONDITION, CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
35
35
  import { readModel } from "../types/documentModel.js";
36
36
  import { canonicalJson } from "../utils/canonicalJson.js";
37
37
  import { buildAnnotatedBlockTextWithNoteReferences } from "./clean-text.js";
@@ -123,12 +123,21 @@ const canonicalOpStory = (story) => {
123
123
  default: return panic("Unknown reviewer story", { story });
124
124
  }
125
125
  };
126
- /** The refusal of a canonical reviewer for what it cannot do on the session yet. */
126
+ /**
127
+ * The refusal of a canonical reviewer for a staged suggestion the session
128
+ * left pending: the suggestion's resolution refused without stating why.
129
+ */
127
130
  const canonicalReviewerRefusal = (action) => new CanonicalSessionError({
128
131
  ground: { gap: CANONICAL_GAP.publicHeadlessSession },
129
132
  reason: "refused",
130
133
  message: `A canonical headless reviewer cannot ${action} yet.`
131
134
  });
135
+ /** A reviewer request under one of the session's conditions. */
136
+ const canonicalReviewerConditionRefusal = (condition, message) => new CanonicalSessionError({
137
+ ground: { condition },
138
+ reason: "refused",
139
+ message
140
+ });
132
141
  const FOLIO_REVIEWED_VIEWS = Object.freeze([
133
142
  "original",
134
143
  "current-markup",
@@ -775,8 +784,8 @@ var FolioDocxReviewer = class FolioDocxReviewer {
775
784
  return copy;
776
785
  }
777
786
  canonicalComparisonAccess() {
778
- const refuse = (action) => {
779
- throw canonicalReviewerRefusal(action);
787
+ const missingNoteLabels = () => {
788
+ throw canonicalReviewerConditionRefusal(CANONICAL_CONDITION.invalidRequest, "Inline atoms are matched with the comparison's note reference labels.");
780
789
  };
781
790
  return Object.freeze({
782
791
  stageTerminalTableReviewCarrier: () => false,
@@ -792,7 +801,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
792
801
  story: canonicalOpStory(targetStory),
793
802
  snapshot: targetSnapshot
794
803
  },
795
- noteReferenceLabels: noteReferenceLabels ?? refuse("match inline atoms without the comparison's note labels"),
804
+ noteReferenceLabels: noteReferenceLabels ?? missingNoteLabels(),
796
805
  author: this.author
797
806
  });
798
807
  if (result.status !== "matched") return result;
@@ -1336,7 +1345,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1336
1345
  idSeed: revisionStamp.idSeed
1337
1346
  }
1338
1347
  });
1339
- if (matched.status === "unaddressable") throw canonicalReviewerRefusal("change the properties of a table cell without a paragraph id");
1348
+ if (matched.status === "unaddressable") throw canonicalReviewerConditionRefusal(CANONICAL_CONDITION.internal, "A paired table cell holds no paragraph to address it by.");
1340
1349
  if (matched.operations.length > 0) this.commitOpsOnSession(matched.operations);
1341
1350
  return matched.nextRevisionId;
1342
1351
  }
@@ -1364,7 +1373,8 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1364
1373
  /**
1365
1374
  * Resolve one editable story to its original or final state, its staged
1366
1375
  * suggestions with its other changes. A suggestion that reaches another
1367
- * story resolves only whole, through the suggestion methods. A lock that
1376
+ * story resolves only in this one: its part in the others stays pending,
1377
+ * for their own story resolution or the suggestion methods. A lock that
1368
1378
  * prevents any target change from resolving refuses before mutation.
1369
1379
  */
1370
1380
  resolveReviewedStory({ story = MAIN_STORY, view }) {
@@ -1691,7 +1701,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1691
1701
  const document = readModel(session.document);
1692
1702
  if (!(document.package.document.comments ?? []).some(({ id }) => id === parentId)) return null;
1693
1703
  const id = freshCommentId(document, session.idLease);
1694
- if (id.isErr()) throw canonicalReviewerRefusal("mint a comment id");
1704
+ if (id.isErr()) throw canonicalReviewerConditionRefusal(CANONICAL_CONDITION.idSpace, "No comment id is left to give the reply.");
1695
1705
  const author = input.author ?? this.author;
1696
1706
  const date = input.date ?? (/* @__PURE__ */ new Date()).toISOString();
1697
1707
  this.commitCommentOnSession(session, {
@@ -1840,15 +1850,17 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1840
1850
  /**
1841
1851
  * One pending suggestion through the session's suggestion intent: rejected
1842
1852
  * with the comments it proposes, or adopted as ordinary tracked changes by
1843
- * `author`. All stories belonging to the proposal publish together.
1853
+ * `author`. All stories belonging to the proposal publish together, or
1854
+ * only its part in `story`.
1844
1855
  */
1845
- resolveSuggestionOnSession(session, suggestionId, resolution, author) {
1856
+ resolveSuggestionOnSession(session, suggestionId, resolution, author, story) {
1846
1857
  if (!this.activeSuggestionIds().has(suggestionId)) return false;
1847
1858
  const prepared = session.prepareSuggestion(this.state, {
1848
1859
  suggestionId,
1849
1860
  resolution,
1850
1861
  author,
1851
- date: (/* @__PURE__ */ new Date()).toISOString()
1862
+ date: (/* @__PURE__ */ new Date()).toISOString(),
1863
+ ...story === void 0 ? {} : { story }
1852
1864
  });
1853
1865
  if (prepared.isErr() && prepared.error.reason === "refused") return false;
1854
1866
  return this.resolveOnSession(prepared).resolved;
@@ -1982,15 +1994,16 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1982
1994
  * A story holding staged suggestions resolved to `view`: its suggestions
1983
1995
  * resolve with its other changes, on a fork, and the fork's operations
1984
1996
  * land here as one commit, so a refusal leaves this reviewer as it was. A
1985
- * suggestion that reaches another story resolves only whole, so resolving
1986
- * one of its stories refuses.
1997
+ * suggestion that reaches another story resolves here only in this story:
1998
+ * its records in the others stay pending.
1987
1999
  */
1988
2000
  resolveStoryWithSuggestions({ story, view, staged }) {
1989
2001
  const key = editableStoryKey(story);
2002
+ const reaching = /* @__PURE__ */ new Set();
1990
2003
  for (const handle of this.listStoryHandlesInternal()) {
1991
2004
  if (editableStoryKey(handle) === key) continue;
1992
2005
  const other = this.getEditableStoryState(handle);
1993
- if (other && [...this.pendingSuggestionIdsForStory(handle, other)].some((suggestionId) => staged.has(suggestionId))) throw canonicalReviewerRefusal("resolve one story of a suggestion that reaches another");
2006
+ for (const suggestionId of other ? this.pendingSuggestionIdsForStory(handle, other) : []) if (staged.has(suggestionId)) reaching.add(suggestionId);
1994
2007
  }
1995
2008
  const copy = this.fork();
1996
2009
  const { session } = copy.engine;
@@ -1998,7 +2011,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1998
2011
  const unsubscribe = session.onCommitted(({ ops }) => operations.push(...ops));
1999
2012
  let resolved;
2000
2013
  try {
2001
- for (const suggestionId of staged) copy.resolveSuggestionOnSession(session, suggestionId, view === "final" ? "accept" : "reject", this.author);
2014
+ for (const suggestionId of staged) copy.resolveSuggestionOnSession(session, suggestionId, view === "final" ? "accept" : "reject", this.author, reaching.has(suggestionId) ? canonicalOpStory(story) : void 0);
2002
2015
  const after = copy.getEditableStoryState(story);
2003
2016
  if (after && copy.pendingSuggestionIdsForStory(story, after).size > 0) throw canonicalReviewerRefusal("resolve a story holding a suggestion the session will not resolve");
2004
2017
  resolved = copy.resolveStoryOnSession(session, story, view);
@@ -2006,6 +2019,10 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2006
2019
  unsubscribe();
2007
2020
  }
2008
2021
  if (operations.length > 0) this.commitOpsOnSession(operations);
2022
+ this.pendingSuggestions.forgetStoryRecords({
2023
+ story,
2024
+ suggestionIds: reaching
2025
+ });
2009
2026
  return resolved;
2010
2027
  }
2011
2028
  /**
@@ -99,6 +99,15 @@ export declare class FolioPendingSuggestionRegistry {
99
99
  clone(): FolioPendingSuggestionRegistry;
100
100
  /** Every suggestion id a record names. */
101
101
  suggestionIds(): Set<string>;
102
+ /**
103
+ * Forget a story's records of suggestions resolved in that story alone.
104
+ * Their records in other stories stay, and so does a record that is the
105
+ * last one its suggestion has.
106
+ */
107
+ forgetStoryRecords({ story, suggestionIds }: {
108
+ story: FolioDocumentStoryHandle;
109
+ suggestionIds: ReadonlySet<string>;
110
+ }): void;
102
111
  /**
103
112
  * Anchor every live record whose paragraph is gone from its story, a
104
113
  * resolution or an edit having removed it, where a save keeps its
@@ -562,6 +562,17 @@ var FolioPendingSuggestionRegistry = class FolioPendingSuggestionRegistry {
562
562
  return new Set([...this.records.values()].map(({ suggestionId }) => suggestionId));
563
563
  }
564
564
  /**
565
+ * Forget a story's records of suggestions resolved in that story alone.
566
+ * Their records in other stories stay, and so does a record that is the
567
+ * last one its suggestion has.
568
+ */
569
+ forgetStoryRecords({ story, suggestionIds }) {
570
+ const storyKey = canonicalJson(story);
571
+ const recordedElsewhere = new Set([...this.records.values()].flatMap(({ suggestionId, story: other }) => canonicalJson(other) === storyKey ? [] : [suggestionId]));
572
+ for (const [key, record] of this.records) if (canonicalJson(record.story) === storyKey && suggestionIds.has(record.suggestionId) && recordedElsewhere.has(record.suggestionId)) this.records.delete(key);
573
+ if (![...this.records.values()].some((record) => canonicalJson(record.story) === storyKey)) this.sourceFingerprints.delete(storyKey);
574
+ }
575
+ /**
565
576
  * Anchor every live record whose paragraph is gone from its story, a
566
577
  * resolution or an edit having removed it, where a save keeps its
567
578
  * suggestion: a split at its own paragraph mark, text proposals over the
@@ -1,5 +1,5 @@
1
1
  import { expectParagraphAttrs, expectRunPropertyChangeMarkAttrs, expectTrackedChangeMarkAttrs } from "../prosemirror/attrs/index.js";
2
- import { getFolioNodeRevisionCarriers } from "../prosemirror/revisionCarriers.js";
2
+ import { getFolioNodeRevisionCarriers, propertyRevisionMetadata } from "../prosemirror/revisionCarriers.js";
3
3
  import { expandRunFormattingCarrier, runFormattingCarrierReviewText, runFormattingInlineAtomCleanText, runFormattingInlineAtomDisposition, runFormattingInlineAtomResultText } from "../prosemirror/runFormattingInlineCarriers.js";
4
4
  import { getTableCellMergeChange } from "../prosemirror/tableCellMergeRevision.js";
5
5
  import { isTableRowRevisionCompanion } from "../prosemirror/tableRowRevisionOwnership.js";
@@ -323,6 +323,29 @@ const getTrackedChangeGroupsFromProjectedDoc = (doc, blockStarts, revisionRanges
323
323
  const change = getTableCellMergeChange(continuationCell);
324
324
  if (!change) {
325
325
  if (!isRecord(continuationCell)) continue;
326
+ const properties = continuationCell["propertyChanges"];
327
+ if (Array.isArray(properties)) for (const property of properties) {
328
+ if (!isRecord(property)) continue;
329
+ const metadata = propertyRevisionMetadata(property["info"]);
330
+ if (metadata === null || continuationRevisionsOwnedByRows.has(metadata.id)) continue;
331
+ const type = "cellPropertiesChanged";
332
+ revisionRanges?.push({
333
+ type,
334
+ author: metadata.author,
335
+ from: pos,
336
+ to: pos + node.nodeSize
337
+ });
338
+ grouped.set(`continuation:${String(pos)}:${metadata.id}`, {
339
+ ...metadata,
340
+ type,
341
+ text: "",
342
+ blockId: firstBlockIdWithin({
343
+ node,
344
+ nodePos: pos,
345
+ blockStarts
346
+ })
347
+ });
348
+ }
326
349
  const structuralChange = continuationCell["structuralChange"];
327
350
  if (!isRecord(structuralChange)) continue;
328
351
  const kind = structuralChange["type"];
@@ -176,12 +176,20 @@ const propertyChangeFor = ({ base, target, position, scope, anchorParaId }) => {
176
176
  anchorParaId
177
177
  };
178
178
  };
179
- /** The paragraph id of the last paragraph directly in a cell. */
179
+ /**
180
+ * The paragraph id of the last paragraph in a cell, through the block content
181
+ * controls and other wrappers around it but outside any nested table: a
182
+ * table operation addressed by a paragraph selects the innermost table that
183
+ * holds it, even through block wrappers.
184
+ */
180
185
  const cellAnchorParaId = (cell) => {
181
186
  let paraId;
182
- cell.forEach((child) => {
183
- const id = child.attrs["paraId"];
184
- if (child.type.name === "paragraph" && typeof id === "string") paraId = id;
187
+ cell.descendants((node) => {
188
+ if (node.type.name === "table") return false;
189
+ if (node.type.name !== "paragraph") return true;
190
+ const id = node.attrs["paraId"];
191
+ if (typeof id === "string") paraId = id;
192
+ return false;
185
193
  });
186
194
  return paraId;
187
195
  };
@@ -59,10 +59,11 @@ const resolveStory = ({ version: { document, projection }, story, ids, decision,
59
59
  };
60
60
  /**
61
61
  * Both sides of a batch resolved the same way. A revision the document held
62
- * before the batch that blocks its own resolution, alone and the same way on
63
- * both sides, stays pending on both: the proof is about what the batch
64
- * changes, and a blocker the batch did not make must not refuse every edit
65
- * of a document that holds one.
62
+ * before the batch that blocks its own resolution alone there, and blocks it
63
+ * the same way after the batch or no longer does, stays pending on both: the
64
+ * proof is about what the batch changes, and a blocker the batch did not make
65
+ * must not refuse every edit of a document that holds one, such as a
66
+ * paragraph the batch puts beside it.
66
67
  */
67
68
  const resolveStoryPair = ({ before, after, story, decision, restores }) => {
68
69
  let beforeIds = before.ids;
@@ -85,9 +86,9 @@ const resolveStoryPair = ({ before, after, story, decision, restores }) => {
85
86
  original: original.content,
86
87
  edited: edited.content
87
88
  };
88
- if (original?.type !== "refused" || edited?.type !== "refused") return void 0;
89
+ if (original?.type !== "refused" || edited === void 0) return void 0;
89
90
  const id = original.error.blockedParagraphMarkRevisionId;
90
- if (id === void 0 || edited.error.blockedParagraphMarkRevisionId !== id || edited.error.reason !== original.error.reason || edited.error.message !== original.error.message || !beforeIds.includes(id) || !afterIds.includes(id) || getTrackedChangeGroupsForIds(before.version.projection, [id]).at(0)?.length !== 1 || getTrackedChangeGroupsForIds(after.version.projection, [id]).at(0)?.length !== 1) return void 0;
91
+ if (id === void 0 || edited.type === "refused" && (edited.error.blockedParagraphMarkRevisionId !== id || edited.error.reason !== original.error.reason) || !beforeIds.includes(id) || !afterIds.includes(id) || getTrackedChangeGroupsForIds(before.version.projection, [id]).at(0)?.length !== 1 || getTrackedChangeGroupsForIds(after.version.projection, [id]).at(0)?.length !== 1) return void 0;
91
92
  beforeIds = beforeIds.filter((revisionId) => revisionId !== id);
92
93
  afterIds = afterIds.filter((revisionId) => revisionId !== id);
93
94
  }
@@ -63,7 +63,7 @@ export declare const CANONICAL_NATIVE_INLINE_POLICIES: {
63
63
  readonly sdt: "control";
64
64
  };
65
65
  declare const InlineProjectionErrorBase: TaggedErrorClass<"InlineProjectionError">;
66
- declare class InlineProjectionError extends InlineProjectionErrorBase<{
66
+ export declare class InlineProjectionError extends InlineProjectionErrorBase<{
67
67
  message: string;
68
68
  }> {}
69
69
  /** Every source variant makes a decision before conversion can discard its positions. */
@@ -109,7 +109,7 @@ export type CanonicalInlineCommentContext = {
109
109
  /** The comment ranges open where the paragraph starts. */
110
110
  openIds: ReadonlySet<number>;
111
111
  };
112
- type CanonicalInlineProjectionArgs = {
112
+ export type CanonicalInlineProjectionArgs = {
113
113
  source: document_d_exports.Paragraph;
114
114
  paragraph: Node;
115
115
  pairedBookmarkIds: StoryIdMembership;
@@ -359,7 +359,7 @@ const commentMarkTransitions = ({ source, paragraph, commentContext, explicitCom
359
359
  previous = current;
360
360
  };
361
361
  const visit = (node, position) => {
362
- if (issue !== void 0) return;
362
+ if (issue !== void 0 || node.type.name === "commentRangeBoundary") return;
363
363
  if (nativePolicies.get(node.type.name) === "control" && node.childCount > 0) {
364
364
  node.forEach((child, offset) => visit(child, position + 1 + offset));
365
365
  return;
@@ -666,4 +666,4 @@ var InlineProjectionCache = class {
666
666
  return projected;
667
667
  }
668
668
  };
669
- export { CANONICAL_NATIVE_INLINE_POLICIES, CANONICAL_SOURCE_INLINE_POLICIES, InlineProjectionCache, canonicalInlineSourceIssue, canonicalNativeCells, projectCanonicalInline };
669
+ export { CANONICAL_NATIVE_INLINE_POLICIES, CANONICAL_SOURCE_INLINE_POLICIES, InlineProjectionCache, InlineProjectionError, canonicalInlineSourceIssue, canonicalNativeCells, projectCanonicalInline };
@@ -11,6 +11,7 @@
11
11
  import { ParagraphCommentMarkers } from "../docx/commentAnchorIndex.js";
12
12
  import { document_d_exports } from "../types/document.js";
13
13
  import { CanonicalInlineGaps } from "./canonicalInlineGaps.js";
14
+ import { Result } from "better-result";
14
15
  import { Node } from "prosemirror-model";
15
16
  export type ParagraphAddress = {
16
17
  blockId: string;
@@ -22,6 +23,8 @@ export type ParagraphAddress = {
22
23
  node: Node;
23
24
  source: document_d_exports.Paragraph;
24
25
  };
26
+ /** A paragraph's text and the editor positions of each of its offsets. */
27
+ export type ParagraphInline = Pick<ParagraphAddress, "text" | "gaps">;
25
28
  /** A paragraph as the top-level block holding it projects it. */
26
29
  export type BlockParagraph = {
27
30
  blockId: string;
@@ -29,7 +32,13 @@ export type BlockParagraph = {
29
32
  container: readonly document_d_exports.BlockContent[] | undefined;
30
33
  /** From the start of the top-level node holding it. */
31
34
  offset: number;
32
- inline: Pick<ParagraphAddress, "text" | "gaps">;
35
+ /**
36
+ * The paragraph's text and gaps, worked out on the first call: a
37
+ * projection that opens a story aligns each paragraph's source with its
38
+ * editor node only when the paragraph is first addressed. The message
39
+ * says why the two do not align.
40
+ */
41
+ inline: () => Result<ParagraphInline, string>;
33
42
  node: Node;
34
43
  source: document_d_exports.Paragraph;
35
44
  };
@@ -31,11 +31,11 @@ import { standaloneTableRowsFromProseMirror, tableAttrsToFormatting } from "../p
31
31
  import { insertionGap } from "../prosemirror/insertionGaps.js";
32
32
  import { ensureParaIdsInDoc } from "../prosemirror/paraIds.js";
33
33
  import { forEachAnnotationIdInDoc } from "../prosemirror/plugins/revisionIds.js";
34
- import { preservesReplacementCommentAlignment, splitAtKeptCommentBoundaries, surveyAcceptedReplacedAnnotations } from "../prosemirror/replacedAnnotations.js";
34
+ import { surveyAcceptedReplacedAnnotations } from "../prosemirror/replacedAnnotations.js";
35
35
  import { createStyleResolver } from "../prosemirror/styles/styleResolver.js";
36
36
  import { insertedColumnWidth, omittedSlotTakingColumn } from "../prosemirror/tableGridMutation.js";
37
37
  import { paragraphGoes, tableGoes } from "../prosemirror/tableRunIn.js";
38
- import { CANONICAL_CONDITION, CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
38
+ import { CANONICAL_CONDITION, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
39
39
  import { readModel } from "../types/documentModel.js";
40
40
  import { batchCommentReferenceShift, mapIntentPositions } from "./batchCommentReferences.js";
41
41
  import { createCanonicalBatchReview } from "./canonicalBatchReview.js";
@@ -2017,6 +2017,19 @@ const mergesDownOverEmptyCells = (table, map, rectangle) => {
2017
2017
  }
2018
2018
  return true;
2019
2019
  };
2020
+ /** A merge across one row can absorb empty cells without moving blocks. */
2021
+ const mergesAcrossEmptyCells = (table, map, rectangle) => {
2022
+ if (rectangle.bottom - rectangle.top !== 1) return false;
2023
+ const cells = new Set(cellsIn(map, rectangle));
2024
+ const owner = map.map[rectangle.top * map.width + rectangle.left];
2025
+ if (owner === void 0) return false;
2026
+ cells.delete(owner);
2027
+ for (const offset of cells) {
2028
+ const cell = table.nodeAt(offset);
2029
+ if (cell?.childCount !== 1 || !cell.firstChild?.isTextblock || cell.firstChild.content.size > 0) return false;
2030
+ }
2031
+ return cells.size > 0;
2032
+ };
2020
2033
  const isTableStructureOperation = (operation) => operation.type === "deleteTable" || operation.type === "insertTableRow" || operation.type === "deleteTableRow" || operation.type === "insertTableColumn" || operation.type === "deleteTableColumn" || operation.type === "mergeTableCells" || operation.type === "splitTableCell";
2021
2034
  /**
2022
2035
  * A table, row or column change, addressed through the paragraph the
@@ -2107,10 +2120,6 @@ const resolveTableStructure = ({ operation, paragraph, projection, story, refusa
2107
2120
  left: cell.leftColumnIndex,
2108
2121
  right: cell.leftColumnIndex + 1
2109
2122
  };
2110
- if (tracked && Array.from({ length: map.height }, (_, rowIndex) => {
2111
- const position = map.map[rowIndex * map.width + column.left];
2112
- return position === void 0 ? null : row.table.nodeAt(position);
2113
- }).some((node) => node?.attrs["_omittedGridSlot"] == null && Number(node?.attrs["colspan"] ?? 1) !== 1)) return skipTracked("A suggested column deletion cannot narrow a cell that spans other columns.");
2114
2123
  const at = tableAnchor({
2115
2124
  map,
2116
2125
  table: row.table,
@@ -2129,7 +2138,7 @@ const resolveTableStructure = ({ operation, paragraph, projection, story, refusa
2129
2138
  deleted,
2130
2139
  skipsCell: (cellPosition) => {
2131
2140
  const rect = map.findCell(cellPosition - row.tableStart);
2132
- return rect.left <= column.left && column.left < rect.right;
2141
+ return rect.left >= column.left && rect.right <= column.right;
2133
2142
  }
2134
2143
  }) ?? address.blockId : address.blockId;
2135
2144
  return resolved({
@@ -2200,7 +2209,7 @@ const resolveTableStructure = ({ operation, paragraph, projection, story, refusa
2200
2209
  if (rectangle.right - rectangle.left === 1 && rectangle.bottom - rectangle.top === 1) return skipAlike("noopOperation", "A merge of one cell changes nothing.");
2201
2210
  if (tableRectangleCutsMergedCell(map, rectangle) || holdsOmittedSlot(row.table, map, rectangle)) return skipAlike("unsupportedBlock", "The merge would cut a merged cell or a slot its row omits.");
2202
2211
  if (new Set(cellsIn(map, rectangle)).size < 2) return skipAlike("unsupportedBlock", "The merge covers a single merged cell.");
2203
- if (tracked && !mergesDownOverEmptyCells(row.table, map, rectangle)) return skipTracked("A suggested merge takes one column over empty cells.");
2212
+ if (tracked && !mergesDownOverEmptyCells(row.table, map, rectangle) && !mergesAcrossEmptyCells(row.table, map, rectangle)) return skipTracked("A suggested merge can absorb only empty cells in one row or column.");
2204
2213
  const blockId = tableBlockAddress(projection, row, deleted);
2205
2214
  if (blockId === void 0) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
2206
2215
  return resolved({
@@ -2217,7 +2226,6 @@ const resolveTableStructure = ({ operation, paragraph, projection, story, refusa
2217
2226
  const cell = findEnclosingTableCell(doc, blockFrom);
2218
2227
  if (cell === null) return notInTable();
2219
2228
  if (cell.rightColumnIndex - cell.leftColumnIndex === 1 && cell.bottomRowIndex - cell.topRowIndex === 1) return skipAlike("noopOperation", "A one-row, one-column cell has nothing to split.");
2220
- if (tracked && cell.rightColumnIndex - cell.leftColumnIndex !== 1) return skipTracked("A suggested split takes a cell merged down one column.");
2221
2229
  return resolved({
2222
2230
  type: "table",
2223
2231
  operation: {
@@ -4885,8 +4893,7 @@ var CanonicalPublicOperations = class {
4885
4893
  placed.push({
4886
4894
  ...change,
4887
4895
  from: gap.from,
4888
- to: afterLast === void 0 ? gap.to : Math.max(gap.from, Math.min(gap.to, afterLast)),
4889
- markers: "retained"
4896
+ to: afterLast === void 0 ? gap.to : Math.max(gap.from, Math.min(gap.to, afterLast))
4890
4897
  });
4891
4898
  }
4892
4899
  return placed;
@@ -4908,35 +4915,6 @@ var CanonicalPublicOperations = class {
4908
4915
  if (whole === void 0) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
4909
4916
  replacementChanges = whole;
4910
4917
  }
4911
- const comments = readModel(this.options.session.document).package.document.comments ?? [];
4912
- let retiredCommentIds;
4913
- if (!tracked) {
4914
- const split = splitAtKeptCommentBoundaries({
4915
- doc: state.doc,
4916
- changes: replacementChanges,
4917
- comments
4918
- });
4919
- replacementChanges = split.changes;
4920
- retiredCommentIds = split.retiredCommentIds;
4921
- }
4922
- if (!preservesReplacementCommentAlignment({
4923
- doc: state.doc,
4924
- source: {
4925
- from: paragraph.start,
4926
- to: paragraph.start + paragraph.node.content.size
4927
- },
4928
- changes: replacementChanges,
4929
- retiredCommentIds,
4930
- removal: tracked ? { type: suggested ? "suggested" : "tracked" } : {
4931
- type: "direct",
4932
- comments
4933
- }
4934
- })) return Result.err(new CanonicalPublicOperationResolutionError({
4935
- reason: "unsupportedBlock",
4936
- ground: { gap: CANONICAL_GAP.commentReplacementAlignment },
4937
- message: "Canonical replacement cannot preserve the aligned comment ranges.",
4938
- detail: "Canonical replacement cannot preserve the aligned comment ranges."
4939
- }));
4940
4918
  if (tracked && !suggested) deletionSpans = replacementChanges.filter((span) => span.from < span.to);
4941
4919
  if (intent.runPropsPatch !== void 0) {
4942
4920
  const nodeAtCharacter = (index) => {
@@ -5134,6 +5112,7 @@ var CanonicalPublicOperations = class {
5134
5112
  }));
5135
5113
  } else intents.push(intent);
5136
5114
  const nextParagraph = operation.type === "mergeBlockWithNext" && intent.type === "joinParagraphs" ? projection.value.paragraph(intent.nextBlockId) : void 0;
5115
+ if (operation.type === "mergeBlockWithNext" && intent.type === "joinParagraphs" && nextParagraph === void 0) return refusal("unsupportedBlock", void 0, INVALID_REQUEST);
5137
5116
  let claimedTo = range.to;
5138
5117
  if (operation.type === "mergeBlockWithNext") claimedTo = paragraph.start + paragraph.node.content.size;
5139
5118
  if (nextParagraph) claimedTo = nextParagraph.start + nextParagraph.node.content.size;
@@ -1,11 +1,26 @@
1
1
  import { document_d_exports } from "../types/document.js";
2
2
  import { OpStory } from "@stll/docx-core/ops";
3
+ /**
4
+ * What makes a story one the session cannot hold:
5
+ *
6
+ * - `comments`: the comments and their anchors are not a valid set, as
7
+ * `commentDocumentIssue` judges them;
8
+ * - `emptyStory`: a story holds no block;
9
+ * - `content`: a block or inline item no document operation writes, such as
10
+ * unstructured field characters or text holding a tab or a line feed. The
11
+ * reader keeps loose field markup as preserved XML, so only a document
12
+ * built by hand holds one.
13
+ */
14
+ export type CanonicalSeedIssue = {
15
+ kind: "comments" | "emptyStory" | "content";
16
+ message: string;
17
+ };
3
18
  /**
4
19
  * Why the session cannot hold these stories of `document`, or `null`: the
5
20
  * first block it cannot hold, else the first paragraph whose content it
6
21
  * cannot hold, in each story in turn.
7
22
  */
8
- export declare const unsupportedSeedReason: (document: document_d_exports.Document, stories?: OpStory[]) => string | null;
23
+ export declare const unsupportedSeedReason: (document: document_d_exports.Document, stories?: OpStory[]) => CanonicalSeedIssue | null;
9
24
  /** The blocks of a story an edit replaced, and the ones it put in their place. */
10
25
  export declare const changedWindow: (before: readonly document_d_exports.BlockContent[], after: readonly document_d_exports.BlockContent[]) => {
11
26
  removed: readonly document_d_exports.BlockContent[];
@@ -27,10 +42,10 @@ type UnsupportedEditOptions = {
27
42
  * and the stories are the ones `previous` had and each story's replaced
28
43
  * blocks carried the anchors its new blocks carry, it stays as it was.
29
44
  */
30
- export declare const unsupportedEditReason: ({ previous, document, stories }: UnsupportedEditOptions) => string | null;
45
+ export declare const unsupportedEditReason: ({ previous, document, stories }: UnsupportedEditOptions) => CanonicalSeedIssue | null;
31
46
  /**
32
47
  * The same verdict from one walk of every story, judging nothing once: the
33
48
  * reference the block judgments above must equal.
34
49
  */
35
- export declare const unsupportedSeedReasonWholeDocument: (document: document_d_exports.Document, stories?: OpStory[]) => string | null;
50
+ export declare const unsupportedSeedReasonWholeDocument: (document: document_d_exports.Document, stories?: OpStory[]) => CanonicalSeedIssue | null;
36
51
  export {};
@@ -1,8 +1,22 @@
1
1
  import { canonicalInlineSourceIssue } from "./canonicalInlineProjection.js";
2
2
  import { OP_STORIES, commentAnchorSequence, commentDocumentIssue, documentStories, findStoryBody } from "@stll/docx-core/ops";
3
3
  // src/canonical/canonicalSeedContent.ts
4
- const STRUCTURE_ISSUE = "Canonical sessions currently require paragraphs, tables and supported inline atoms.";
5
- const REVIEW_CARRIER_ISSUE = "Canonical sessions currently require plain paragraphs and supported inline atoms.";
4
+ const STRUCTURE_ISSUE = {
5
+ kind: "content",
6
+ message: "Canonical sessions currently require paragraphs, tables and supported inline atoms."
7
+ };
8
+ const EMPTY_STORY_ISSUE = {
9
+ kind: "emptyStory",
10
+ message: "Canonical sessions require a nonempty paragraph story."
11
+ };
12
+ const contentIssue = (message) => message === null ? null : {
13
+ kind: "content",
14
+ message
15
+ };
16
+ const commentIssueOf = (message) => message === void 0 ? null : {
17
+ kind: "comments",
18
+ message
19
+ };
6
20
  /** Range markers may open or close between blocks; they hold no text. */
7
21
  const BETWEEN_BLOCK_MARKERS = /* @__PURE__ */ new Set([
8
22
  "commentRangeStart",
@@ -40,7 +54,7 @@ const issuesIn = (block) => {
40
54
  const structure = collect([block]);
41
55
  let paragraph = null;
42
56
  for (const candidate of paragraphs) {
43
- paragraph = candidate.reviewCarrier === void 0 ? canonicalInlineSourceIssue(candidate.content) : REVIEW_CARRIER_ISSUE;
57
+ paragraph = contentIssue(canonicalInlineSourceIssue(candidate.content));
44
58
  if (paragraph !== null) break;
45
59
  }
46
60
  return {
@@ -63,8 +77,8 @@ const issuesOf = (block) => {
63
77
  * cannot hold, in each story in turn.
64
78
  */
65
79
  const unsupportedSeedReason = (document, stories = documentStories(document)) => {
66
- const commentIssue = commentDocumentIssue(document, "all");
67
- if (commentIssue !== void 0) return commentIssue;
80
+ const commentIssue = commentIssueOf(commentDocumentIssue(document, "all"));
81
+ if (commentIssue !== null) return commentIssue;
68
82
  for (const story of stories) {
69
83
  const body = findStoryBody(document, story);
70
84
  if (story !== OP_STORIES.MAIN && (story.kind === "footnote" || story.kind === "endnote")) {
@@ -72,7 +86,7 @@ const unsupportedSeedReason = (document, stories = documentStories(document)) =>
72
86
  if (note?.noteType !== void 0 && note.noteType !== "normal") continue;
73
87
  }
74
88
  const content = body?.content;
75
- if (!content || content.length === 0) return "Canonical sessions require a nonempty paragraph story.";
89
+ if (!content || content.length === 0) return EMPTY_STORY_ISSUE;
76
90
  const issues = content.map(issuesOf);
77
91
  const structure = issues.find((issue) => issue.structure !== null);
78
92
  if (structure !== void 0) return structure.structure;
@@ -115,12 +129,12 @@ const unsupportedEditReason = ({ previous, document, stories }) => {
115
129
  ...changedWindow(findStoryBody(previous, story)?.content ?? [], findStoryBody(document, story)?.content ?? [])
116
130
  }));
117
131
  if (!(document.package.document.comments === previous.package.document.comments && documentStories(document).length === documentStories(previous).length && windows.every(({ removed, added }) => sameSequence(commentAnchorSequence(removed), commentAnchorSequence(added))))) {
118
- const commentIssue = commentDocumentIssue(document, "all");
119
- if (commentIssue !== void 0) return commentIssue;
132
+ const commentIssue = commentIssueOf(commentDocumentIssue(document, "all"));
133
+ if (commentIssue !== null) return commentIssue;
120
134
  }
121
135
  for (const { story, content, added } of windows) {
122
136
  if (skippedNote(document, story)) continue;
123
- if (!content || content.length === 0) return "Canonical sessions require a nonempty paragraph story.";
137
+ if (!content || content.length === 0) return EMPTY_STORY_ISSUE;
124
138
  const issues = added.map(issuesOf);
125
139
  const structure = issues.find((issue) => issue.structure !== null);
126
140
  if (structure !== void 0) return structure.structure;
@@ -134,8 +148,8 @@ const unsupportedEditReason = ({ previous, document, stories }) => {
134
148
  * reference the block judgments above must equal.
135
149
  */
136
150
  const unsupportedSeedReasonWholeDocument = (document, stories = documentStories(document)) => {
137
- const commentIssue = commentDocumentIssue(document, "all");
138
- if (commentIssue !== void 0) return commentIssue;
151
+ const commentIssue = commentIssueOf(commentDocumentIssue(document, "all"));
152
+ if (commentIssue !== null) return commentIssue;
139
153
  for (const story of stories) {
140
154
  const body = findStoryBody(document, story);
141
155
  if (story !== OP_STORIES.MAIN && (story.kind === "footnote" || story.kind === "endnote")) {
@@ -143,7 +157,7 @@ const unsupportedSeedReasonWholeDocument = (document, stories = documentStories(
143
157
  if (note?.noteType !== void 0 && note.noteType !== "normal") continue;
144
158
  }
145
159
  const content = body?.content;
146
- if (!content || content.length === 0) return "Canonical sessions require a nonempty paragraph story.";
160
+ if (!content || content.length === 0) return EMPTY_STORY_ISSUE;
147
161
  const paragraphs = [];
148
162
  const collect = (blocks) => {
149
163
  for (const block of blocks) {
@@ -158,7 +172,7 @@ const unsupportedSeedReasonWholeDocument = (document, stories = documentStories(
158
172
  if (issue !== null) return issue;
159
173
  continue;
160
174
  }
161
- if (block.type !== "table") return "Canonical sessions currently require paragraphs, tables and supported inline atoms.";
175
+ if (block.type !== "table") return STRUCTURE_ISSUE;
162
176
  for (const row of block.rows) for (const cell of row.cells) {
163
177
  const issue = collect(cell.content);
164
178
  if (issue !== null) return issue;
@@ -169,8 +183,7 @@ const unsupportedSeedReasonWholeDocument = (document, stories = documentStories(
169
183
  const blockIssue = collect(content);
170
184
  if (blockIssue !== null) return blockIssue;
171
185
  for (const paragraph of paragraphs) {
172
- if (paragraph.reviewCarrier !== void 0) return "Canonical sessions currently require plain paragraphs and supported inline atoms.";
173
- const issue = canonicalInlineSourceIssue(paragraph.content);
186
+ const issue = contentIssue(canonicalInlineSourceIssue(paragraph.content));
174
187
  if (issue !== null) return issue;
175
188
  }
176
189
  }