@stll/folio-core 0.76.0 → 0.77.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 (86) 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/canonicalInlineProjection.d.ts +2 -2
  8. package/dist/canonical/canonicalInlineProjection.js +2 -2
  9. package/dist/canonical/canonicalProjectionBlocks.d.ts +10 -1
  10. package/dist/canonical/canonicalPublicOperations.js +13 -38
  11. package/dist/canonical/canonicalSeedContent.d.ts +18 -3
  12. package/dist/canonical/canonicalSeedContent.js +28 -15
  13. package/dist/canonical/canonicalSession.d.ts +22 -12
  14. package/dist/canonical/canonicalSession.js +178 -186
  15. package/dist/controller/canonicalClipboard.d.ts +2 -1
  16. package/dist/controller/canonicalClipboard.js +312 -47
  17. package/dist/controller/canonicalComposition.js +67 -14
  18. package/dist/controller/canonicalStoryEditor.js +2 -0
  19. package/dist/controller/hiddenEditorManager.js +2 -0
  20. package/dist/docx/importedIdCollisions.js +29 -4
  21. package/dist/docx/server/templatePlan/apply.js +47 -2
  22. package/dist/docx/server/templatePlan/blocks.d.ts +27 -7
  23. package/dist/docx/server/templatePlan/blocks.js +103 -12
  24. package/dist/docx/server/templatePlan/builders.d.ts +6 -0
  25. package/dist/docx/server/templatePlan/builders.js +7 -1
  26. package/dist/docx/server/templatePlan/emit.d.ts +2 -0
  27. package/dist/docx/server/templatePlan/emit.js +108 -6
  28. package/dist/docx/server/templatePlan/plan.d.ts +24 -1
  29. package/dist/docx/server/templatePlan/plan.js +165 -12
  30. package/dist/docx/server/templatePlan/planShape.js +13 -2
  31. package/dist/docx/server/templatePlan/revisions.d.ts +55 -0
  32. package/dist/docx/server/templatePlan/revisions.js +276 -2
  33. package/dist/docx/server/templatePlan/story.d.ts +46 -1
  34. package/dist/docx/server/templatePlan/story.js +125 -11
  35. package/dist/docx/server/templatePlan/types.d.ts +97 -1
  36. package/dist/docx/server/templatePlan/verify.js +63 -9
  37. package/dist/docx/settingsHeaderFooterUpdate.d.ts +1 -1
  38. package/dist/docx/tableGridXml.d.ts +3 -7
  39. package/dist/docx/tableGridXml.js +5 -13
  40. package/dist/layout-bridge/convert/footnoteLayout.js +34 -8
  41. package/dist/prosemirror/canonicalMarkupDocument.d.ts +20 -0
  42. package/dist/prosemirror/canonicalMarkupDocument.js +73 -0
  43. package/dist/prosemirror/canonicalTableCommands.d.ts +1 -1
  44. package/dist/prosemirror/canonicalTableCommands.js +1 -3
  45. package/dist/prosemirror/conversion/markupViewSource.d.ts +17 -0
  46. package/dist/prosemirror/conversion/markupViewSource.js +11 -0
  47. package/dist/prosemirror/conversion/toProseDoc.d.ts +3 -0
  48. package/dist/prosemirror/conversion/toProseDoc.js +31 -14
  49. package/dist/prosemirror/independentMarkupProjection.d.ts +27 -0
  50. package/dist/prosemirror/independentMarkupProjection.js +147 -0
  51. package/dist/prosemirror/markupViewNotes.d.ts +1 -1
  52. package/dist/prosemirror/markupViewNotes.js +24 -27
  53. package/dist/prosemirror/markupViewPositionMap.d.ts +16 -0
  54. package/dist/prosemirror/markupViewPositionMap.js +316 -0
  55. package/dist/prosemirror/markupViewProjection.d.ts +3 -46
  56. package/dist/prosemirror/markupViewProjection.js +90 -17
  57. package/dist/prosemirror/replacedAnnotations.d.ts +4 -78
  58. package/dist/prosemirror/replacedAnnotations.js +11 -194
  59. package/dist/prosemirror/styles/styleResolver.d.ts +1 -0
  60. package/dist/prosemirror/styles/styleResolver.js +4 -1
  61. package/dist/server.d.ts +2 -2
  62. package/dist/types/canonicalCapabilities.d.ts +3 -10
  63. package/dist/types/canonicalCapabilities.js +3 -10
  64. package/package.json +2 -2
  65. package/dist/internal/revisionResolutionEdits.d.ts +0 -11
  66. package/dist/internal/revisionResolutionEdits.js +0 -18
  67. package/dist/internal/revisionResolutionInline.d.ts +0 -24
  68. package/dist/internal/revisionResolutionInline.js +0 -302
  69. package/dist/internal/revisionResolutionStep.d.ts +0 -3
  70. package/dist/internal/revisionResolutionStep.js +0 -113
  71. package/dist/internal/revisionResolutionTracking.d.ts +0 -9
  72. package/dist/internal/revisionResolutionTracking.js +0 -124
  73. package/dist/internal/wholeStoryRevisionResolution.d.ts +0 -56
  74. package/dist/internal/wholeStoryRevisionResolution.js +0 -783
  75. package/dist/prosemirror/commands/resolveAllTableChanges.d.ts +0 -38
  76. package/dist/prosemirror/commands/resolveAllTableChanges.js +0 -642
  77. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.d.ts +0 -13
  78. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.js +0 -45
  79. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +0 -8
  80. package/dist/prosemirror/commands/tableCellMergeResolution.js +0 -56
  81. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +0 -60
  82. package/dist/prosemirror/commands/tableMergeFoldDecisions.js +0 -78
  83. package/dist/prosemirror/rejoinRunCarriers.d.ts +0 -42
  84. package/dist/prosemirror/rejoinRunCarriers.js +0 -65
  85. package/dist/prosemirror/runPropertyChangeResolution.d.ts +0 -15
  86. package/dist/prosemirror/runPropertyChangeResolution.js +0 -34
@@ -151,6 +151,31 @@ const IMPORTED_ID_COLLISION_REGISTRY = {
151
151
  encoding: "string"
152
152
  }
153
153
  };
154
+ /**
155
+ * The rules naming each element local name, in registry order, each with the
156
+ * namespaces it names that local name in: most elements of a part are named by
157
+ * no rule, and are passed over without resolving their namespace.
158
+ */
159
+ const RULES_BY_LOCAL_NAME = (() => {
160
+ const index = /* @__PURE__ */ new Map();
161
+ for (const rule of Object.values(IMPORTED_ID_COLLISION_REGISTRY)) for (const site of rule.sites) for (const localName of site.elements) {
162
+ let rules = index.get(localName);
163
+ if (rules === void 0) {
164
+ rules = [];
165
+ index.set(localName, rules);
166
+ }
167
+ let entry = rules.find((candidate) => candidate.rule === rule);
168
+ if (entry === void 0) {
169
+ entry = {
170
+ rule,
171
+ namespaces: /* @__PURE__ */ new Set()
172
+ };
173
+ rules.push(entry);
174
+ }
175
+ entry.namespaces.add(site.namespace);
176
+ }
177
+ return index;
178
+ })();
154
179
  const normalizedIdentity = (value, encoding) => {
155
180
  if (encoding === "string") return value;
156
181
  if (encoding === "hex") return /^[0-9a-f]{8}$/iu.test(value) ? value.toUpperCase() : void 0;
@@ -161,18 +186,18 @@ const normalizedIdentity = (value, encoding) => {
161
186
  };
162
187
  /** Reports repeated source definitions without changing the package or choosing a winner. */
163
188
  const diagnoseImportedIdCollisions = (parts, context) => {
164
- const rules = Object.values(IMPORTED_ID_COLLISION_REGISTRY);
165
189
  const packageSeen = /* @__PURE__ */ new Map();
166
190
  for (const [part, xml] of parts) {
167
191
  const partSeen = /* @__PURE__ */ new Map();
168
192
  const scoped = context.scoped({ part });
169
193
  scanSelectedStreamingXmlElements(xml, ({ element, attributeValueSpans }) => {
170
194
  if (element.name === void 0) return;
195
+ const candidates = RULES_BY_LOCAL_NAME.get(getLocalName(element.name));
196
+ if (candidates === void 0) return;
171
197
  const namespace = toTransitionalNamespaceUri(getNamespaceUri(element) ?? "");
172
- const localName = getLocalName(element.name);
173
- for (const rule of rules) {
198
+ for (const { rule, namespaces } of candidates) {
174
199
  const kind = rule.kind;
175
- if (!rule.sites.some((site) => namespace === site.namespace && site.elements.has(localName))) continue;
200
+ if (!namespaces.has(namespace)) continue;
176
201
  const paragraphIdentity = paragraphIdentityForKind(kind, element);
177
202
  const seen = rule.scope === "package" ? packageSeen : partSeen;
178
203
  for (const [name, rawValue] of Object.entries(element.attributes ?? {})) {
@@ -4,13 +4,13 @@ import { spliceXml } from "../../selectiveXmlPatch.js";
4
4
  import { NAMESPACES, getLocalName } from "../../xmlParser.js";
5
5
  import { appendToXmlRoot } from "../../xmlRootInsertion.js";
6
6
  import { analyzeDocument, analyzeSource, viewOf } from "./blocks.js";
7
- import { freezeFields, inheritedReferencesXml, sectionPropertiesXml, setKeepShiftReturnSpacing, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
7
+ import { bookmarkIdsOf, freezeFields, inheritedReferencesXml, sectionPropertiesXml, setKeepShiftReturnSpacing, setTrackingOff, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
8
8
  import { removeInvisibleEffects } from "./effects.js";
9
9
  import { createRelationshipsEditor, noteXml, paragraphContentXml, paragraphXml, tableXml, templateCharacterStyles } from "./emit.js";
10
10
  import { readHeaderFooterParts } from "./inspect.js";
11
11
  import { styleNumbering } from "./labels.js";
12
12
  import { guarded, readPartText, relationshipsPathFor } from "./package.js";
13
- import { resolvePlan } from "./plan.js";
13
+ import { fieldSeparatorRun, resolvePlan } from "./plan.js";
14
14
  import { readStoryResources } from "./resources.js";
15
15
  import { TemplatePlanError } from "./types.js";
16
16
  import { reportTemplatePlanOutput } from "./verify.js";
@@ -69,6 +69,8 @@ const RANGE_MARKERS = [["bookmarkStart", "bookmarkEnd"], ["commentRangeStart", "
69
69
  * Splices removing range markers whose other half the output does not carry:
70
70
  * a bookmark or comment range that started in a block the plan dropped.
71
71
  */
72
+ /** How far above the bookmarks' ids the ids of kept tracked changes start. */
73
+ const REVISION_ID_OFFSET = 1e5;
72
74
  const orphanMarkerSplices = ({ kept, replaced }) => {
73
75
  const splices = [];
74
76
  for (const [startName, endName] of RANGE_MARKERS) {
@@ -363,6 +365,7 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
363
365
  const media = /* @__PURE__ */ new Map();
364
366
  const mediaPaths = /* @__PURE__ */ new Set();
365
367
  let unsupportedMedia = null;
368
+ let revisionId = maxOf(bookmarkIdsOf(template.document.root), 0) + REVISION_ID_OFFSET;
366
369
  let drawingId = 0;
367
370
  const noteDrawingIds = (root) => {
368
371
  walkElements(root, (element) => {
@@ -413,6 +416,10 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
413
416
  nextDrawingId: () => {
414
417
  drawingId += 1;
415
418
  return drawingId;
419
+ },
420
+ nextRevisionId: () => {
421
+ revisionId += 1;
422
+ return revisionId;
416
423
  }
417
424
  };
418
425
  const documentContext = {
@@ -474,6 +481,36 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
474
481
  end: inner.end
475
482
  });
476
483
  }
484
+ for (const { element } of resolved.emptied) {
485
+ const inner = innerRangeOf(template.document.xml, element);
486
+ if (inner === null) continue;
487
+ const properties = wChild(element, "pPr");
488
+ const start = (properties === null ? null : rangeOf(properties)?.end) ?? inner.start;
489
+ templateSplices.push({
490
+ start,
491
+ end: inner.end,
492
+ newXml: ""
493
+ });
494
+ replaced.push({
495
+ start,
496
+ end: inner.end
497
+ });
498
+ }
499
+ for (const { element } of resolved.emptiedContents.keys()) {
500
+ const start = rangeOf(fieldSeparatorRun(element) ?? element)?.end;
501
+ const inner = innerRangeOf(template.document.xml, element);
502
+ if (start === void 0 || inner === null) continue;
503
+ const { w } = documentContext.prefixes;
504
+ templateSplices.push({
505
+ start,
506
+ end: inner.end,
507
+ newXml: `<${w}:r><${w}:fldChar ${w}:fldCharType="end"/></${w}:r>`
508
+ });
509
+ replaced.push({
510
+ start,
511
+ end: inner.end
512
+ });
513
+ }
477
514
  const keptElements = [
478
515
  ...resolved.keptTemplateBlocks.map(({ element }) => element),
479
516
  ...resolved.items.flatMap((item) => item.kind === "slot" ? [item.templateBlock.element] : []),
@@ -670,6 +707,14 @@ const writeOutput = async ({ source, template, plan, resolved }) => {
670
707
  if (settings === null) return Result.err(unreadable(settingsPath, "The settings part could not be updated."));
671
708
  if (settings !== settingsXml.value) parts.set(settingsPath, settings);
672
709
  }
710
+ if (plan.trackedChanges === "keep") {
711
+ const settingsPath = pkg.partPath("settings");
712
+ const written = settingsPath === null ? void 0 : parts.get(settingsPath);
713
+ const settingsXml = typeof written === "string" ? Result.ok(written) : await readTemplateText(settingsPath);
714
+ if (Result.isError(settingsXml)) return settingsXml;
715
+ const settings = settingsXml.value === null ? null : setTrackingOff(settingsXml.value);
716
+ if (settingsPath !== null && settings !== null && settings !== settingsXml.value) parts.set(settingsPath, settings);
717
+ }
673
718
  if (plan.textEffects !== "keep") {
674
719
  const kept = [
675
720
  [pkg.documentPath, documentXml],
@@ -7,7 +7,7 @@ import { Emphasis } from "./emphasis.js";
7
7
  import { LabelCounter, ParagraphLabel } from "./labels.js";
8
8
  import { LoadedPackage } from "./package.js";
9
9
  import { ParagraphRead, StoryState } from "./story.js";
10
- import { DocxBlock, DocxBlockManifest, DocxSection, TemplatePlanError, TemplatePlanTrackedView } from "./types.js";
10
+ import { DocxBlock, DocxBlockManifest, DocxSection, TemplatePlanError, TemplatePlanTrackedChanges } from "./types.js";
11
11
  import { RawPart } from "./xml.js";
12
12
  import { Result } from "better-result";
13
13
  export declare const blockHash: (text: string, label: string | null) => string;
@@ -99,9 +99,11 @@ type AnalyzeStoryOptions = {
99
99
  container: XmlElement;
100
100
  resources: StoryResources;
101
101
  counter?: LabelCounter;
102
+ /** Read inline insertions and deletions as tagged atoms. */
103
+ keepsRevisions?: boolean;
102
104
  };
103
105
  /** Read the blocks under `container` into ids, text, labels and hashes. */
104
- export declare const analyzeStory: ({ container, resources, counter }: AnalyzeStoryOptions) => AnalyzedStory;
106
+ export declare const analyzeStory: ({ container, resources, counter, keepsRevisions }: AnalyzeStoryOptions) => AnalyzedStory;
105
107
  export type AnalyzedNote = {
106
108
  id: string;
107
109
  element: XmlElement;
@@ -140,10 +142,27 @@ export type AnalyzedDocument = {
140
142
  manifest: DocxBlockManifest;
141
143
  };
142
144
  /** Open a package and analyse its main story, notes, styles and numbering. */
143
- export declare const analyzeDocument: (bytes: Uint8Array) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
145
+ export declare const analyzeDocument: (bytes: Uint8Array, { keepsRevisions }?: {
146
+ keepsRevisions?: boolean;
147
+ }) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
144
148
  /** The view a plan states, when what was handed in is shaped like a plan
145
149
  * at all; its shape is checked where the plan is resolved. */
146
- export declare const viewOf: (plan: unknown) => TemplatePlanTrackedView | undefined;
150
+ export declare const viewOf: (plan: unknown) => TemplatePlanTrackedChanges | undefined;
151
+ /**
152
+ * A source read with its tracked changes kept: the blocks are those of the
153
+ * accepted view, and the atoms of an insertion or a deletion carry its tag,
154
+ * a paragraph mark's among them; an inserted table row keeps its record and
155
+ * a deleted one is set aside whole. A change that is not carried yet (a
156
+ * table cell, a move) or cannot be tagged is refused with what stands in the
157
+ * way, for the caller to offer one view instead.
158
+ */
159
+ /**
160
+ * A document read with its tracked changes kept, source or output alike:
161
+ * deleted paragraph marks carried as deletions inside the joined paragraph,
162
+ * inline insertions and deletions as tagged atoms. The manifest keeps the
163
+ * hash of the bytes that were given.
164
+ */
165
+ export declare const analyzeKeptForm: (bytes: Uint8Array) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
147
166
  /**
148
167
  * Analyse a source in the view a caller chose of its tracked changes, or
149
168
  * as it stands. In a view, the package that is analysed is the resolved
@@ -151,14 +170,15 @@ export declare const viewOf: (plan: unknown) => TemplatePlanTrackedView | undefi
151
170
  * plan pins the file, not a rewriting of it. Without a view, a document
152
171
  * that tracks changes says what it tracks.
153
172
  */
154
- export declare const analyzeSource: (bytes: Uint8Array, view: TemplatePlanTrackedView | undefined) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
173
+ export declare const analyzeSource: (bytes: Uint8Array, view: TemplatePlanTrackedChanges | undefined) => Promise<Result<AnalyzedDocument, TemplatePlanError>>;
155
174
  /**
156
175
  * Read a DOCX into the blocks a template plan addresses: ids, visible text,
157
176
  * rendered list labels, styles and a hash per block, plus its notes. With
158
177
  * `trackedChanges`, the blocks are those of that view of a document with
159
- * tracked changes.
178
+ * tracked changes; with `keep`, those of the accepted view, read off the
179
+ * document as it stands, or the refusal a plan that keeps them would get.
160
180
  */
161
181
  export declare const analyzeDocxBlocks: (docx: Uint8Array, options?: {
162
- trackedChanges?: TemplatePlanTrackedView;
182
+ trackedChanges?: TemplatePlanTrackedChanges;
163
183
  }) => Promise<Result<DocxBlockManifest, TemplatePlanError>>;
164
184
  export {};
@@ -5,7 +5,7 @@ import { keepsShiftReturnSpacing } from "./builders.js";
5
5
  import { defaultsBaseline } from "./emphasis.js";
6
6
  import { createLabelCounter } from "./labels.js";
7
7
  import { guarded, loadPackage, readPartText, sha256Hex } from "./package.js";
8
- import { resolveTrackedChanges } from "./revisions.js";
8
+ import { keptRevisionObstacles, resolveTrackedChanges, withDeletedMarksJoined } from "./revisions.js";
9
9
  import { createStoryState, endStory, readParagraph, toggleOf, walkBlocks } from "./story.js";
10
10
  import { TemplatePlanError } from "./types.js";
11
11
  import { elementChildren, halfPointsOrNull, integerOrNull, isW, readRawPart, twipsOrNull, wAttr, wChild, wChildVal, wChildren } from "./xml.js";
@@ -210,9 +210,38 @@ const selfNumbersOf = ({ atoms }) => {
210
210
  }
211
211
  return offsets;
212
212
  };
213
+ /**
214
+ * The tracked changes a paragraph read with them kept holds, by where they
215
+ * sit in its text. Neighbouring pieces of one change are one entry.
216
+ */
217
+ const revisionsOf = ({ atoms }) => {
218
+ const found = [];
219
+ let at = 0;
220
+ for (const { text, revision } of atoms) {
221
+ const start = at;
222
+ at += text.length;
223
+ if (revision === void 0) continue;
224
+ const kind = revision.kind === "ins" ? "insertion" : "deletion";
225
+ const paragraphMark = revision.mark === true || revision.deleted === "";
226
+ const last = found.at(-1);
227
+ if (last !== void 0 && !paragraphMark && last.paragraphMark === void 0 && last.kind === kind && last.end === start && last.author === revision.author && last.date === revision.date) {
228
+ last.end = at;
229
+ continue;
230
+ }
231
+ found.push({
232
+ kind,
233
+ start,
234
+ end: at,
235
+ author: revision.author,
236
+ date: revision.date,
237
+ ...paragraphMark ? { paragraphMark: true } : {}
238
+ });
239
+ }
240
+ return found;
241
+ };
213
242
  /** Read the blocks under `container` into ids, text, labels and hashes. */
214
- const analyzeStory = ({ container, resources, counter = createLabelCounter(resources) }) => {
215
- const state = createStoryState();
243
+ const analyzeStory = ({ container, resources, counter = createLabelCounter(resources), keepsRevisions = false }) => {
244
+ const state = createStoryState({ keepsRevisions });
216
245
  const story = {
217
246
  topLevel: [],
218
247
  order: [],
@@ -272,10 +301,17 @@ const analyzeStory = ({ container, resources, counter = createLabelCounter(resou
272
301
  if (pageBreaks > 0) block.pageBreaks = pageBreaks;
273
302
  const selfNumbers = selfNumbersOf(read);
274
303
  if (selfNumbers.length > 0) block.selfNumbers = selfNumbers;
304
+ const revisions = revisionsOf(read);
305
+ if (revisions.length > 0) block.revisions = revisions;
275
306
  if (read.pageBreakBefore ?? style?.pPr?.pageBreakBefore === true) block.pageBreakBefore = true;
276
307
  if (read.hasSectionBreak) block.endsSection = true;
277
308
  const alignment = read.alignment ?? (resources.alignments === void 0 ? null : styleAlignment(styleId ?? resources.defaultStyleId, resources.styles, resources.alignments));
278
309
  if (alignment !== null) block.alignment = alignment;
310
+ const { before, after } = read.spacing;
311
+ if (before !== null || after !== null) block.spacing = {
312
+ ...before === null ? {} : { before },
313
+ ...after === null ? {} : { after }
314
+ };
279
315
  const ofLevel = (label.numbering === null ? void 0 : resources.levelIndents?.get(levelKey(label.numbering.abstractNumId, label.numbering.ilvl))) ?? NO_INDENT;
280
316
  const ofStyle = modelIndent(style?.pPr);
281
317
  const ofDefaults = resources.defaultIndent ?? NO_INDENT;
@@ -389,7 +425,7 @@ const NOTE_ELEMENT = {
389
425
  footnotes: "footnote",
390
426
  endnotes: "endnote"
391
427
  };
392
- const analyzeNotes = (kind, path, xml) => {
428
+ const analyzeNotes = (kind, path, xml, keepsRevisions = false) => {
393
429
  const notes = {
394
430
  kind,
395
431
  path,
@@ -397,7 +433,7 @@ const analyzeNotes = (kind, path, xml) => {
397
433
  notes: [],
398
434
  byId: /* @__PURE__ */ new Map(),
399
435
  usedIds: [],
400
- state: createStoryState()
436
+ state: createStoryState({ keepsRevisions })
401
437
  };
402
438
  if (path === null || xml === null) return notes;
403
439
  const part = readRawPart(path, xml);
@@ -455,7 +491,7 @@ const countComments = (xml) => {
455
491
  return part === null ? 0 : elementChildren(part.root).filter(({ name }) => (name ?? "").endsWith("comment")).length;
456
492
  };
457
493
  /** Open a package and analyse its main story, notes, styles and numbering. */
458
- const analyzeDocument = async (bytes) => {
494
+ const analyzeDocument = async (bytes, { keepsRevisions = false } = {}) => {
459
495
  const loaded = await loadPackage(bytes);
460
496
  if (Result.isError(loaded)) return loaded;
461
497
  const pkg = loaded.value;
@@ -519,10 +555,11 @@ const analyzeDocument = async (bytes) => {
519
555
  alignments: statedAlignments(stylesPath, stylesXml),
520
556
  levelIndents: statedLevelIndents(numberingPath, numberingXml),
521
557
  defaultIndent: statedDefaultIndent(stylesPath, stylesXml)
522
- }
558
+ },
559
+ keepsRevisions
523
560
  }),
524
- footnotes: analyzeNotes("footnotes", footnotesPath, footnotesXml),
525
- endnotes: analyzeNotes("endnotes", endnotesPath, endnotesXml)
561
+ footnotes: analyzeNotes("footnotes", footnotesPath, footnotesXml, keepsRevisions),
562
+ endnotes: analyzeNotes("endnotes", endnotesPath, endnotesXml, keepsRevisions)
526
563
  };
527
564
  },
528
565
  catch: (cause) => cause instanceof TemplatePlanError ? cause : new TemplatePlanError({
@@ -569,7 +606,59 @@ const analyzeDocument = async (bytes) => {
569
606
  * at all; its shape is checked where the plan is resolved. */
570
607
  const viewOf = (plan) => {
571
608
  const view = typeof plan === "object" && plan !== null && "trackedChanges" in plan ? plan.trackedChanges : void 0;
572
- return view === "accept" || view === "reject" ? view : void 0;
609
+ return view === "accept" || view === "reject" || view === "keep" ? view : void 0;
610
+ };
611
+ /**
612
+ * A source read with its tracked changes kept: the blocks are those of the
613
+ * accepted view, and the atoms of an insertion or a deletion carry its tag,
614
+ * a paragraph mark's among them; an inserted table row keeps its record and
615
+ * a deleted one is set aside whole. A change that is not carried yet (a
616
+ * table cell, a move) or cannot be tagged is refused with what stands in the
617
+ * way, for the caller to offer one view instead.
618
+ */
619
+ /**
620
+ * A document read with its tracked changes kept, source or output alike:
621
+ * deleted paragraph marks carried as deletions inside the joined paragraph,
622
+ * inline insertions and deletions as tagged atoms. The manifest keeps the
623
+ * hash of the bytes that were given.
624
+ */
625
+ const analyzeKeptForm = async (bytes) => {
626
+ const joined = await withDeletedMarksJoined(bytes);
627
+ if (Result.isError(joined)) return joined;
628
+ const analyzed = await analyzeDocument(joined.value, { keepsRevisions: true });
629
+ if (Result.isError(analyzed)) return analyzed;
630
+ return Result.ok({
631
+ ...analyzed.value,
632
+ manifest: {
633
+ ...analyzed.value.manifest,
634
+ sha256: sha256Hex(bytes)
635
+ }
636
+ });
637
+ };
638
+ const analyzeKeeping = async (bytes) => {
639
+ const obstacles = await keptRevisionObstacles(bytes);
640
+ if (Result.isError(obstacles)) return obstacles;
641
+ const analyzed = await analyzeKeptForm(bytes);
642
+ if (Result.isError(analyzed)) return analyzed;
643
+ const { story, footnotes, endnotes, manifest } = analyzed.value;
644
+ const untagged = story.state.untaggedRevisions + footnotes.state.untaggedRevisions + endnotes.state.untaggedRevisions;
645
+ const { tableCells, moves } = obstacles.value.obstacles;
646
+ const found = [
647
+ [tableCells, "table cell change(s)"],
648
+ [moves, "move(s)"],
649
+ [untagged, "change(s) inside another change, a drawing or an equation, or deleted paragraph mark(s) with no paragraph to join"]
650
+ ].flatMap(([count, what]) => typeof count === "number" && count > 0 ? [`${String(count)} ${what}`] : []);
651
+ if (found.length > 0) return Result.err(new TemplatePlanError({
652
+ code: "tracked-changes",
653
+ message: `The tracked changes of the source cannot be kept: ${found.join(", ")}. Format one view of it instead.`
654
+ }));
655
+ return Result.ok({
656
+ ...analyzed.value,
657
+ manifest: {
658
+ ...manifest,
659
+ trackedChangesKept: obstacles.value.tracked
660
+ }
661
+ });
573
662
  };
574
663
  /**
575
664
  * Analyse a source in the view a caller chose of its tracked changes, or
@@ -579,6 +668,7 @@ const viewOf = (plan) => {
579
668
  * that tracks changes says what it tracks.
580
669
  */
581
670
  const analyzeSource = async (bytes, view) => {
671
+ if (view === "keep") return await analyzeKeeping(bytes);
582
672
  if (view === void 0) {
583
673
  const analyzed = await analyzeDocument(bytes);
584
674
  if (Result.isError(analyzed) || analyzed.value.manifest.trackedChanges === 0) return analyzed;
@@ -611,7 +701,8 @@ const analyzeSource = async (bytes, view) => {
611
701
  * Read a DOCX into the blocks a template plan addresses: ids, visible text,
612
702
  * rendered list labels, styles and a hash per block, plus its notes. With
613
703
  * `trackedChanges`, the blocks are those of that view of a document with
614
- * tracked changes.
704
+ * tracked changes; with `keep`, those of the accepted view, read off the
705
+ * document as it stands, or the refusal a plan that keeps them would get.
615
706
  */
616
707
  const analyzeDocxBlocks = async (docx, options = {}) => await guarded(async () => (await analyzeSource(docx, options.trackedChanges)).map(({ manifest }) => manifest));
617
- export { analyzeDocument, analyzeDocxBlocks, analyzeSource, analyzeStory, blockHash, statedAlignments, statedLooks, storySections, styleAlignment, styleLook, styleOutlineLevel, viewOf };
708
+ export { analyzeDocument, analyzeDocxBlocks, analyzeKeptForm, analyzeSource, analyzeStory, blockHash, statedAlignments, statedLooks, storySections, styleAlignment, styleLook, styleOutlineLevel, viewOf };
@@ -57,6 +57,12 @@ export declare const fieldBookmarkOf: (instruction: string) => string | null;
57
57
  * place in the schema's child order. Null when the part is not a settings part.
58
58
  */
59
59
  export declare const setUpdateFieldsOnOpen: (settingsXml: string, enabled: boolean) => string | null;
60
+ /**
61
+ * `settingsXml` without `w:trackRevisions`: a document that carries tracked
62
+ * changes of its source records no new ones until its reader switches
63
+ * tracking on. Null when the part is not a settings part.
64
+ */
65
+ export declare const setTrackingOff: (settingsXml: string) => string | null;
60
66
  /** Whether a settings part keeps the spacing of a justified line that ends
61
67
  * in a manual line break (`w:compat/w:doNotExpandShiftReturn`). */
62
68
  export declare const keepsShiftReturnSpacing: (settingsXml: string) => boolean;
@@ -139,6 +139,12 @@ const fieldBookmarkOf = (instruction) => /^\s*(?:REF|PAGEREF|NOTEREF)\s+"?(?<nam
139
139
  * place in the schema's child order. Null when the part is not a settings part.
140
140
  */
141
141
  const setUpdateFieldsOnOpen = (settingsXml, enabled) => updateSettingsOnOffChild(settingsXml, "updateFields", enabled ? true : void 0);
142
+ /**
143
+ * `settingsXml` without `w:trackRevisions`: a document that carries tracked
144
+ * changes of its source records no new ones until its reader switches
145
+ * tracking on. Null when the part is not a settings part.
146
+ */
147
+ const setTrackingOff = (settingsXml) => updateSettingsOnOffChild(settingsXml, "trackRevisions", void 0);
142
148
  const SHIFT_RETURN = "doNotExpandShiftReturn";
143
149
  /** The children of `w:compat` the schema orders in front of the setting. */
144
150
  const COMPAT_BEFORE_SHIFT_RETURN = /* @__PURE__ */ new Set([
@@ -453,4 +459,4 @@ const freezeFields = (part, kinds) => {
453
459
  }))
454
460
  };
455
461
  };
456
- export { applyRefCaseFormat, bookmarkEndXml, bookmarkIdsOf, bookmarkStartXml, complexFieldXml, fieldBookmarkOf, freezeFields, inheritedReferencesXml, keepsShiftReturnSpacing, mintRefBookmarkName, refCaseFormat, refFieldInstruction, sectionPropertiesXml, setKeepShiftReturnSpacing, setUpdateFieldsOnOpen, withoutContained, wrapParagraphContentInBookmark };
462
+ export { applyRefCaseFormat, bookmarkEndXml, bookmarkIdsOf, bookmarkStartXml, complexFieldXml, fieldBookmarkOf, freezeFields, inheritedReferencesXml, keepsShiftReturnSpacing, mintRefBookmarkName, refCaseFormat, refFieldInstruction, sectionPropertiesXml, setKeepShiftReturnSpacing, setTrackingOff, setUpdateFieldsOnOpen, withoutContained, wrapParagraphContentInBookmark };
@@ -55,6 +55,8 @@ export type EmitShared = {
55
55
  /** Register a media part of the output and return its absolute target. */
56
56
  addMedia: (sourcePath: string, media: SourceMedia) => string;
57
57
  nextDrawingId: () => number;
58
+ /** A fresh id for a tracked change the output carries. */
59
+ nextRevisionId: () => number;
58
60
  };
59
61
  export type EmitContext = EmitShared & {
60
62
  prefixes: PartPrefixes;
@@ -5,6 +5,7 @@ import { appendToXmlRoot } from "../../xmlRootInsertion.js";
5
5
  import { bookmarkEndXml, bookmarkStartXml, complexFieldXml, wrapParagraphContentInBookmark } from "./builders.js";
6
6
  import { runPropertiesXml } from "./emphasis.js";
7
7
  import { paragraphPieces } from "./plan.js";
8
+ import { deletedRowMarkOf, insertedRowMarkOf, keptDeletedRowOf, rowTextOf } from "./revisions.js";
8
9
  import { TemplatePlanError } from "./types.js";
9
10
  import { MATH_NAMESPACE, elementChildren, escapeXmlAttribute, escapeXmlText, wAttr, wChild, wChildren, wName } from "./xml.js";
10
11
  import { Result, panic } from "better-result";
@@ -189,7 +190,55 @@ const wSubtreeXml = (element, prefix) => {
189
190
  const open = `<${prefix}:${name}${wAttributesXml(element, prefix)}`;
190
191
  return children === "" ? `${open}/>` : `${open}>${children}</${prefix}:${name}>`;
191
192
  };
193
+ /**
194
+ * What stands in a paragraph's runs for a deleted paragraph mark until the
195
+ * paragraph is written: the attributes of the mark between two of these. No
196
+ * run holds the character (XML text cannot).
197
+ */
198
+ const MARK_SPLIT = "\0";
199
+ /** The inserted mark of a paragraph's last piece, when it has one. */
200
+ const insertedMarkOf = (segments) => {
201
+ const last = segments.at(-1);
202
+ const revision = (last === void 0 || last.kind === "piece" ? [last?.piece] : last.pieces).at(-1)?.atom?.revision;
203
+ return revision?.mark === true ? revision : void 0;
204
+ };
205
+ /** The attributes a kept tracked change is written with: its own author and
206
+ * date, and an id of the output's. */
207
+ const revisionAttributesXml = ({ author, date }, { prefixes: { w }, nextRevisionId }) => ` ${w}:id="${String(nextRevisionId())}" ${w}:author="${escapeXmlAttribute(author)}"${date === null ? "" : ` ${w}:date="${escapeXmlAttribute(date)}"`}`;
208
+ /** Deleted text as the content of a deleted run: tabs and line breaks are
209
+ * elements, the rest is `w:delText`. */
210
+ const deletedContentXml = (deleted, w) => deleted.split(/(\t|\n)/u).map((part) => {
211
+ if (part === " ") return `<${w}:tab/>`;
212
+ if (part === "\n") return `<${w}:br/>`;
213
+ return part === "" ? "" : `<${w}:delText xml:space="preserve">${escapeXmlText(part)}</${w}:delText>`;
214
+ }).join("");
215
+ /**
216
+ * The runs of one piece. A piece of a kept tracked change is written inside
217
+ * its insertion or deletion; a deletion holds the text that was deleted and
218
+ * takes no place in the text around it.
219
+ */
192
220
  const pieceRunXml = (piece, context, linked) => {
221
+ const revision = piece.atom?.revision;
222
+ if (revision === void 0) return plainPieceRunXml(piece, context, linked);
223
+ const { w } = context.prefixes;
224
+ if (revision.mark === true) return Result.ok("");
225
+ const attributes = revisionAttributesXml(revision, context);
226
+ if (revision.deleted === "") return Result.ok(`${MARK_SPLIT}${attributes}${MARK_SPLIT}`);
227
+ if (revision.kind === "del") {
228
+ const deletion = `<${w}:del${attributes}><${w}:r>${runPropertiesXml({
229
+ prefix: w,
230
+ signature: piece.signature,
231
+ rStyle: linked ? context.styles.hyperlink : null,
232
+ escapeAttribute: escapeXmlAttribute
233
+ })}${deletedContentXml(revision.deleted ?? "", w)}</${w}:r></${w}:del>`;
234
+ return Result.ok(revision.within === void 0 ? deletion : `<${w}:ins${revisionAttributesXml({
235
+ kind: "ins",
236
+ ...revision.within
237
+ }, context)}>${deletion}</${w}:ins>`);
238
+ }
239
+ return plainPieceRunXml(piece, context, linked).map((runs) => runs === "" ? "" : `<${w}:ins${attributes}>${runs}</${w}:ins>`);
240
+ };
241
+ const plainPieceRunXml = (piece, context, linked) => {
193
242
  const { w } = context.prefixes;
194
243
  const properties = (rStyle) => runPropertiesXml({
195
244
  prefix: w,
@@ -242,7 +291,7 @@ const mergedPieces = (pieces) => {
242
291
  const merged = [];
243
292
  for (const piece of pieces) {
244
293
  const last = merged.at(-1);
245
- if (last !== void 0 && last.kind === "text" && piece.kind === "text" && last.signature === piece.signature && last.origin === piece.origin && sameLink(last.link, piece.link)) merged[merged.length - 1] = {
294
+ if (last !== void 0 && last.kind === "text" && piece.kind === "text" && last.signature === piece.signature && last.origin === piece.origin && last.atom?.revision === void 0 && piece.atom?.revision === void 0 && sameLink(last.link, piece.link)) merged[merged.length - 1] = {
246
295
  ...last,
247
296
  text: last.text + piece.text
248
297
  };
@@ -343,6 +392,11 @@ const paragraphXml = (emit, context) => {
343
392
  const stops = tabStops.map((stop) => `<${w}:tab ${w}:val="left" ${w}:pos="${String(stop)}"/>`).join("");
344
393
  properties.push(`<${w}:tabs>${stops}</${w}:tabs>`);
345
394
  }
395
+ const { spacing } = emit.paragraph;
396
+ if (spacing !== null) {
397
+ const sides = ["before", "after"].filter((side) => spacing[side] !== void 0).map((side) => ` ${w}:${side}="${String(spacing[side])}"`).join("");
398
+ properties.push(`<${w}:spacing${sides}/>`);
399
+ }
346
400
  if (indent !== null) {
347
401
  const sides = [
348
402
  "left",
@@ -356,8 +410,22 @@ const paragraphXml = (emit, context) => {
356
410
  if (emit.sectionXml !== null) properties.push(emit.sectionXml);
357
411
  const runs = segmentsRunsXml(emit.paragraph.segments, context, emit.instructionOf);
358
412
  if (Result.isError(runs)) return runs;
359
- const xml = `<${w}:p>${properties.length === 0 ? "" : `<${w}:pPr>${properties.join("")}</${w}:pPr>`}${runs.value}</${w}:p>`;
360
- if (emit.bookmark === void 0) return Result.ok(xml);
413
+ const inserted = insertedMarkOf(emit.paragraph.segments);
414
+ if (inserted !== void 0) {
415
+ const mark = `<${w}:rPr><${w}:ins${revisionAttributesXml(inserted, context)}/></${w}:rPr>`;
416
+ properties.splice(emit.sectionXml === null ? properties.length : properties.length - 1, 0, mark);
417
+ }
418
+ const pPr = properties.length === 0 ? "" : `<${w}:pPr>${properties.join("")}</${w}:pPr>`;
419
+ const [last = "", ...earlier] = runs.value.split(MARK_SPLIT).toReversed();
420
+ const halves = [];
421
+ const parted = earlier.toReversed();
422
+ for (let at = 0; at + 1 < parted.length; at += 2) {
423
+ const style = styleId === null ? "" : `<${w}:pStyle ${w}:val="${escapeXmlAttribute(styleId)}"/>`;
424
+ const list = numbering.kind === "direct" || emit.styleBindsList ? `<${w}:numPr><${w}:numId ${w}:val="${NO_LIST_NUM_ID}"/></${w}:numPr>` : "";
425
+ halves.push(`<${w}:p><${w}:pPr>${style}${list}<${w}:rPr><${w}:del${parted[at + 1] ?? ""}/></${w}:rPr></${w}:pPr>${parted[at] ?? ""}</${w}:p>`);
426
+ }
427
+ const xml = `<${w}:p>${pPr}${last}</${w}:p>`;
428
+ if (emit.bookmark === void 0) return Result.ok(`${halves.join("")}${xml}`);
361
429
  const wrapped = wrapParagraphContentInBookmark({
362
430
  paragraphXml: xml,
363
431
  prefixes: context.prefixes,
@@ -367,7 +435,7 @@ const paragraphXml = (emit, context) => {
367
435
  code: "xml-unreadable",
368
436
  message: "A reference target could not be bookmarked.",
369
437
  blockId: emit.paragraph.parts.at(0)?.block.block.id ?? ""
370
- })) : Result.ok(wrapped);
438
+ })) : Result.ok(`${halves.join("")}${wrapped}`);
371
439
  };
372
440
  const TABLE_LAYOUT_PROPERTIES = ["tblLayout", "tblLook"];
373
441
  const ROW_PROPERTIES = [
@@ -403,6 +471,37 @@ const keptChildrenXml = (properties, names, prefix) => names.map((name) => {
403
471
  const child = wChild(properties, name);
404
472
  return child === null ? "" : wSubtreeXml(child, prefix);
405
473
  }).join("");
474
+ /** The attributes a kept row or mark revision is written with, read off the
475
+ * source's own record. */
476
+ const markAttributesXml = (mark, context) => revisionAttributesXml({
477
+ kind: "del",
478
+ author: wAttr(mark, "author") ?? "",
479
+ date: wAttr(mark, "date")
480
+ }, context);
481
+ /**
482
+ * A row the source records as deleted, written back as one: its cells with
483
+ * their spans, and in each cell its paragraphs' text as deleted text with a
484
+ * deleted paragraph mark. The accepted view has no such row, so no plan
485
+ * places its paragraphs; they take no style of their own.
486
+ */
487
+ const deletedRowXml = (row, keepsBorders, context) => {
488
+ const { w } = context.prefixes;
489
+ const mark = deletedRowMarkOf(row);
490
+ const attributes = () => mark === null ? "" : markAttributesXml(mark, context);
491
+ const deletedParagraphXml = (text) => `<${w}:p><${w}:pPr><${w}:rPr><${w}:del${attributes()}/></${w}:rPr></${w}:pPr>${text === "" ? "" : `<${w}:del${attributes()}><${w}:r>${deletedContentXml(text, w)}</${w}:r></${w}:del>`}</${w}:p>`;
492
+ const cells = [];
493
+ const stack = [...elementChildren(row)].toReversed();
494
+ for (let next = stack.pop(); next !== void 0; next = stack.pop()) if (wName(next) === "tc") {
495
+ const properties = wChild(next, "tcPr");
496
+ const kept = `${keptChildrenXml(properties, CELL_SPAN_PROPERTIES, w)}${keepsBorders ? keptChildrenXml(properties, ["tcBorders"], w) : ""}`;
497
+ const lines = rowTextOf({
498
+ ...row,
499
+ elements: [next]
500
+ }).split("\n");
501
+ cells.push(`<${w}:tc>${kept === "" ? "" : `<${w}:tcPr>${kept}</${w}:tcPr>`}${lines.map(deletedParagraphXml).join("")}</${w}:tc>`);
502
+ } else if (wName(next) !== "trPr") stack.push(...elementChildren(next).toReversed());
503
+ return `<${w}:tr><${w}:trPr><${w}:del${attributes()}/></${w}:trPr>${cells.join("")}</${w}:tr>`;
504
+ };
406
505
  /**
407
506
  * A source table rebuilt: its grid, spans and merges, with every cell
408
507
  * paragraph placed like a body paragraph. Without a template table style the
@@ -459,8 +558,11 @@ const tableXml = ({ table, styleId, paragraphOf }, context) => {
459
558
  const out = [];
460
559
  for (const child of elementChildren(container)) {
461
560
  const name = wName(child);
462
- if (name === "tr") {
463
- const kept = keptChildrenXml(wChild(child, "trPr"), ROW_PROPERTIES, w);
561
+ const deleted = keptDeletedRowOf(child);
562
+ if (deleted !== null) out.push(deletedRowXml(deleted, styleId === null, context));
563
+ else if (name === "tr") {
564
+ const inserted = insertedRowMarkOf(child);
565
+ const kept = `${keptChildrenXml(wChild(child, "trPr"), ROW_PROPERTIES, w)}${inserted === null ? "" : `<${w}:ins${markAttributesXml(inserted, context)}/>`}`;
464
566
  const cells = cellsXml(child);
465
567
  if (Result.isError(cells)) return cells;
466
568
  out.push(`<${w}:tr>${kept === "" ? "" : `<${w}:trPr>${kept}</${w}:trPr>`}${cells.value}</${w}:tr>`);