@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
@@ -1,7 +1,7 @@
1
1
  import { spliceXml } from "../../selectiveXmlPatch.js";
2
2
  import { loadPackage } from "./package.js";
3
3
  import { TemplatePlanError } from "./types.js";
4
- import { elementChildren, innerRangeOf, rangeOf, readRawPart, wAttr, wChild, wName } from "./xml.js";
4
+ import { elementChildren, escapeXmlAttribute, innerRangeOf, rangeOf, readRawPart, wAttr, wChild, wName } from "./xml.js";
5
5
  import { Result } from "better-result";
6
6
  import { ZipArchive } from "@stll/docx-core/zip";
7
7
  // src/docx/server/templatePlan/revisions.ts
@@ -312,6 +312,280 @@ const summaryOf = (tally) => ({
312
312
  first: tally.first,
313
313
  last: tally.last
314
314
  });
315
+ /**
316
+ * The text a deleted paragraph mark is carried as, inside a deletion of
317
+ * its own, by a reading that keeps tracked changes: a private-use character
318
+ * no document's text holds.
319
+ */
320
+ const DELETED_PARAGRAPH_MARK = "";
321
+ /**
322
+ * The element a deleted table row is kept in by a reading that keeps
323
+ * tracked changes. The accepted view has no such row, so it may be no row
324
+ * of the table to the readers of blocks; in a namespace of its own it is
325
+ * none, and the writer and verification find it by this name.
326
+ */
327
+ const KEPT_DELETED_ROW_NAMESPACE = "urn:stll:folio:kept-deleted-row";
328
+ const KEPT_DELETED_ROW = "keptDeletedRow";
329
+ /** The row a kept-deleted-row element holds, or null for any other element. */
330
+ const keptDeletedRowOf = (element) => element.namespaceUri === "urn:stll:folio:kept-deleted-row" ? elementChildren(element).find((child) => wName(child) === "tr") ?? null : null;
331
+ /** The deletion a row's properties record, or null. */
332
+ const deletedRowMarkOf = (row) => wChild(wChild(row, "trPr"), "del");
333
+ /** The insertion a row's properties record, or null. */
334
+ const insertedRowMarkOf = (row) => wChild(wChild(row, "trPr"), "ins");
335
+ /** What a deleted row held: its cells' text, deleted text included, a tab
336
+ * between cells and a line break between paragraphs. */
337
+ const rowTextOf = (row) => {
338
+ const paragraphText = (paragraph) => {
339
+ let text = "";
340
+ const stack = [...elementChildren(paragraph)].toReversed();
341
+ for (let next = stack.pop(); next !== void 0; next = stack.pop()) {
342
+ const name = wName(next);
343
+ if (name === "t" || name === "delText") text += (next.elements ?? []).map((node) => node.type === "text" ? String(node.text ?? "") : "").join("");
344
+ else stack.push(...elementChildren(next).toReversed());
345
+ }
346
+ return text;
347
+ };
348
+ const cellText = (cell) => {
349
+ const lines = [];
350
+ const stack = [...elementChildren(cell)].toReversed();
351
+ for (let next = stack.pop(); next !== void 0; next = stack.pop()) if (wName(next) === "p") lines.push(paragraphText(next));
352
+ else stack.push(...elementChildren(next).toReversed());
353
+ return lines.join("\n");
354
+ };
355
+ const cells = [];
356
+ const stack = [...elementChildren(row)].toReversed();
357
+ for (let next = stack.pop(); next !== void 0; next = stack.pop()) if (wName(next) === "tc") cells.push(cellText(next));
358
+ else if (wName(next) !== "trPr") stack.push(...elementChildren(next).toReversed());
359
+ return cells.join(" ");
360
+ };
361
+ /**
362
+ * The row revisions a table carries in the kept form, in order: an inserted
363
+ * row by the place it has among the table's rows, a deleted one by the
364
+ * place it was taken from and by its text; each with who made the change.
365
+ * Rows of a table nested in a cell are that table's.
366
+ */
367
+ const tableRowRevisions = (table) => {
368
+ const out = [];
369
+ let rows = 0;
370
+ const by = (mark) => `${wAttr(mark, "author") ?? ""}:${wAttr(mark, "date") ?? ""}`;
371
+ const visit = (container) => {
372
+ for (const child of elementChildren(container)) {
373
+ const deleted = keptDeletedRowOf(child);
374
+ if (deleted !== null) out.push(`${String(rows)}:del:${by(deletedRowMarkOf(deleted))}:${rowTextOf(deleted)}`);
375
+ else if (wName(child) === "tr") {
376
+ const inserted = insertedRowMarkOf(child);
377
+ if (inserted !== null) out.push(`${String(rows)}:ins:${by(inserted)}`);
378
+ rows += 1;
379
+ } else if (wName(child) === "sdt") {
380
+ const content = wChild(child, "sdtContent");
381
+ if (content !== null) visit(content);
382
+ } else if (wName(child) === "customXml") visit(child);
383
+ }
384
+ };
385
+ visit(table);
386
+ return out;
387
+ };
388
+ const deletedMarkOf = (paragraph) => wChild(wChild(wChild(paragraph, "pPr"), "rPr"), "del");
389
+ /** Whether `xml` may hold a paragraph mark recorded as deleted: an empty
390
+ * deletion, in either spelling of an empty element. */
391
+ const mayHoldDeletedMark = (xml) => /<[A-Za-z0-9]+:del\b[^>]*(?:\/>|><\/)/u.test(xml);
392
+ /** Whether the opening tag of an element declares a namespace of its own. */
393
+ const declaresNamespace = (source) => /^<[^>]*\sxmlns[:=]/u.test(source);
394
+ /**
395
+ * The deletion that stands for a deleted paragraph mark, by who deleted it.
396
+ * It is written with the prefix of the paragraph it came from, which is
397
+ * bound wherever that paragraph's content may stand.
398
+ */
399
+ const markDeletionXml = (paragraph, mark) => {
400
+ const prefix = (paragraph.name ?? "w:p").split(":").at(0) ?? "w";
401
+ const attribute = (name) => {
402
+ const value = wAttr(mark, name);
403
+ return value === null ? "" : ` ${prefix}:${name}="${escapeXmlAttribute(value)}"`;
404
+ };
405
+ return `<${prefix}:del ${prefix}:id="0"${attribute("author")}${attribute("date")}><${prefix}:r><${prefix}:delText></${prefix}:delText></${prefix}:r></${prefix}:del>`;
406
+ };
407
+ /**
408
+ * The children of `container` with every paragraph whose mark is deleted
409
+ * joined to the paragraph after it: its content, then a deletion that
410
+ * stands for the mark, then that paragraph's own content under that
411
+ * paragraph's properties. This is what the document reads with its changes
412
+ * accepted, with the deleted mark still on record. A paragraph that has no
413
+ * paragraph after it in its container keeps its mark, and so does one whose
414
+ * own tag declares a namespace: its content would lose the binding in
415
+ * another paragraph.
416
+ */
417
+ const joinChildren = (walk, container) => {
418
+ const inner = innerRangeOf(walk.xml, container);
419
+ if (inner === null) return "";
420
+ let out = "";
421
+ let cursor = inner.start;
422
+ /** A paragraph whose mark is deleted, waiting for the next paragraph. */
423
+ let held = null;
424
+ const release = () => {
425
+ if (held !== null) {
426
+ out += held.xml;
427
+ held = null;
428
+ }
429
+ };
430
+ for (const child of elementChildren(container)) {
431
+ const range = rangeOf(child);
432
+ if (range === null) {
433
+ walk.sound = false;
434
+ return "";
435
+ }
436
+ const between = walk.xml.slice(cursor, range.start);
437
+ cursor = range.end;
438
+ const source = walk.xml.slice(range.start, range.end);
439
+ if (wName(child) === "tr" && deletedRowMarkOf(child) !== null) {
440
+ release();
441
+ out += `${between}<kept:${KEPT_DELETED_ROW} xmlns:kept="${KEPT_DELETED_ROW_NAMESPACE}">${source}</kept:${KEPT_DELETED_ROW}>`;
442
+ continue;
443
+ }
444
+ if (wName(child) !== "p") {
445
+ release();
446
+ out += between + joinElement(walk, child, source);
447
+ continue;
448
+ }
449
+ const carried = held === null ? "" : held.content;
450
+ const joined = withLeadingContent(source, carried);
451
+ const mark = declaresNamespace(source) ? null : deletedMarkOf(child);
452
+ if (mark === null) {
453
+ out += between + joined;
454
+ held = null;
455
+ continue;
456
+ }
457
+ held = {
458
+ xml: between + joined,
459
+ content: contentOf(joined) + markDeletionXml(child, mark)
460
+ };
461
+ }
462
+ release();
463
+ return out + walk.xml.slice(cursor, inner.end);
464
+ };
465
+ const joinElement = (walk, element, source) => {
466
+ const outer = rangeOf(element);
467
+ const inner = innerRangeOf(walk.xml, element);
468
+ if (!mayHoldDeletedMark(source) || outer === null || inner === null) return source;
469
+ return `${walk.xml.slice(outer.start, inner.start)}${joinChildren(walk, element)}${walk.xml.slice(inner.end, outer.end)}`;
470
+ };
471
+ /** One part with its deleted paragraph marks carried as deletions; null
472
+ * when it cannot be read whole. */
473
+ const joinDeletedMarksInPart = (path, xml) => {
474
+ if (!mayHoldDeletedMark(xml)) return xml;
475
+ const part = readRawPart(path, xml);
476
+ const outer = part === null ? null : rangeOf(part.root);
477
+ if (part === null || outer === null) return null;
478
+ const walk = {
479
+ xml,
480
+ sound: true
481
+ };
482
+ const joined = joinElement(walk, part.root, xml.slice(outer.start, outer.end));
483
+ return walk.sound ? spliceXml(xml, [{
484
+ ...outer,
485
+ newXml: joined
486
+ }]) : null;
487
+ };
488
+ /**
489
+ * A package in the form a reading that keeps tracked changes takes it in:
490
+ * the main document and the notes with their deleted paragraph marks
491
+ * carried as deletions. The bytes are the document's own when it has none.
492
+ */
493
+ const withDeletedMarksJoined = async (docx) => {
494
+ const loaded = await loadPackage(docx);
495
+ if (loaded.isErr()) return Result.err(loaded.error);
496
+ const pkg = loaded.value;
497
+ const paths = [
498
+ pkg.documentPath,
499
+ pkg.partPath("footnotes"),
500
+ pkg.partPath("endnotes")
501
+ ].filter((path) => path !== null);
502
+ const rewritten = /* @__PURE__ */ new Map();
503
+ for (const path of paths) {
504
+ const xml = path === pkg.documentPath ? pkg.documentXml : await pkg.readText(path);
505
+ if (xml === null) continue;
506
+ const joined = joinDeletedMarksInPart(path, xml);
507
+ if (joined === null) return Result.err(new TemplatePlanError({
508
+ code: "xml-unreadable",
509
+ message: `The deleted paragraph marks of ${path} could not be read.`
510
+ }));
511
+ if (joined !== xml) rewritten.set(path, joined);
512
+ }
513
+ if (rewritten.size === 0) return Result.ok(docx);
514
+ return await Result.tryPromise({
515
+ try: async () => {
516
+ const zip = await ZipArchive.read(docx);
517
+ for (const [path, content] of rewritten) {
518
+ const current = zip.entry(path);
519
+ zip.set(path, content, current === void 0 ? {} : { modified: current.modified });
520
+ }
521
+ return await zip.generate();
522
+ },
523
+ catch: (cause) => new TemplatePlanError({
524
+ code: "archive-unreadable",
525
+ message: "The package could not be rewritten with its marks joined.",
526
+ cause
527
+ })
528
+ });
529
+ };
530
+ const REVISION_WRAPPERS = /* @__PURE__ */ new Set([
531
+ "ins",
532
+ "del",
533
+ "moveFrom",
534
+ "moveTo"
535
+ ]);
536
+ const countObstacles = (root, into) => {
537
+ const visit = (element, parent, grandparent) => {
538
+ const name = wName(element);
539
+ if (name !== null && REVISION_WRAPPERS.has(name)) {
540
+ if (parent === "rPr" && grandparent === "pPr") {
541
+ into.paragraphMarks += 1;
542
+ into.moves += name === "moveFrom" || name === "moveTo" ? 1 : 0;
543
+ } else if (parent === "trPr") into.tableRows += 1;
544
+ else if (name === "moveFrom" || name === "moveTo") into.moves += 1;
545
+ } else if (name !== null && CELL_MARKS.has(name)) into.tableCells += 1;
546
+ for (const child of elementChildren(element)) visit(child, name, parent);
547
+ };
548
+ visit(root, null, null);
549
+ };
550
+ /**
551
+ * What a document tracks, and which of it a plan that keeps tracked changes
552
+ * cannot carry: a change that makes the paragraphs of the accepted and the
553
+ * rejected view differ.
554
+ */
555
+ const keptRevisionObstacles = async (docx) => {
556
+ const loaded = await loadPackage(docx);
557
+ if (loaded.isErr()) return Result.err(loaded.error);
558
+ const pkg = loaded.value;
559
+ const tally = newTally();
560
+ const obstacles = {
561
+ paragraphMarks: 0,
562
+ tableRows: 0,
563
+ tableCells: 0,
564
+ moves: 0
565
+ };
566
+ const paths = [
567
+ pkg.documentPath,
568
+ pkg.partPath("footnotes"),
569
+ pkg.partPath("endnotes")
570
+ ].filter((path) => path !== null);
571
+ for (const path of paths) {
572
+ const xml = path === pkg.documentPath ? pkg.documentXml : await pkg.readText(path);
573
+ if (xml === null || !mayHoldRevision(xml)) continue;
574
+ const part = readRawPart(path, xml);
575
+ if (part !== null) {
576
+ tallyPart(part.root, tally);
577
+ countObstacles(part.root, obstacles);
578
+ }
579
+ }
580
+ return Result.ok({
581
+ tracked: {
582
+ ...summaryOf(tally),
583
+ paragraphMarks: obstacles.paragraphMarks,
584
+ tableRows: obstacles.tableRows
585
+ },
586
+ obstacles
587
+ });
588
+ };
315
589
  /** One part in the chosen view, or null when it cannot be read whole. */
316
590
  const resolvePartRevisions = (path, xml, view) => {
317
591
  const part = readRawPart(path, xml);
@@ -404,4 +678,4 @@ const resolveTrackedChanges = async (docx, view) => {
404
678
  })
405
679
  });
406
680
  };
407
- export { resolvePartRevisions, resolveTrackedChanges };
681
+ export { DELETED_PARAGRAPH_MARK, KEPT_DELETED_ROW_NAMESPACE, deletedRowMarkOf, insertedRowMarkOf, joinDeletedMarksInPart, keptDeletedRowOf, keptRevisionObstacles, resolvePartRevisions, resolveTrackedChanges, rowTextOf, tableRowRevisions, withDeletedMarksJoined };
@@ -37,6 +37,33 @@ export type InlineAtom = {
37
37
  fields: readonly number[];
38
38
  /** The code of the field a `selfNumber` atom stands for. */
39
39
  instruction?: string;
40
+ /** The tracked change the atom is part of, in a reading that keeps them. */
41
+ revision?: AtomRevision;
42
+ };
43
+ /**
44
+ * A tracked change an atom is part of, as a reading that keeps revisions
45
+ * reports it. An inserted atom is content like any other with this tag. A
46
+ * deleted one is a text atom without text: it takes no place in the text
47
+ * the document reads with its changes accepted, and holds what was deleted
48
+ * in `deleted` (a tab as `\t`, a line break as `\n`, a paragraph mark as
49
+ * the private character a keeping reading carries it as). An inserted
50
+ * paragraph mark is a text atom without text at the end of its paragraph,
51
+ * tagged `mark`.
52
+ */
53
+ export type AtomRevision = {
54
+ kind: "ins" | "del";
55
+ author: string;
56
+ date: string | null;
57
+ deleted?: string;
58
+ mark?: true;
59
+ /**
60
+ * The insertion a deletion sits in: text one hand inserted and another
61
+ * deleted again. It reads in neither view and is on record in both.
62
+ */
63
+ within?: {
64
+ author: string;
65
+ date: string | null;
66
+ };
40
67
  };
41
68
  /** Whether a field kind prints a number of its own and caches no text. */
42
69
  export declare const isSelfNumberingField: (kind: string) => boolean;
@@ -71,8 +98,20 @@ export type StoryState = {
71
98
  formattingRevisions: number;
72
99
  /** Field separators and ends met with no field open to take them. */
73
100
  strayFieldEnds: number;
101
+ /**
102
+ * Whether inline insertions and deletions are read as tagged atoms. Left
103
+ * out, an insertion reads as plain content and a deletion is skipped.
104
+ */
105
+ keepsRevisions: boolean;
106
+ /**
107
+ * Revisions a keeping reading could not tag: one inside another, deleted
108
+ * content that is no text, a change inside a drawing or an equation.
109
+ */
110
+ untaggedRevisions: number;
74
111
  };
75
- export declare const createStoryState: () => StoryState;
112
+ export declare const createStoryState: (options?: {
113
+ keepsRevisions?: boolean;
114
+ }) => StoryState;
76
115
  /** A bookmark start, with how many atoms of its paragraph come before it. */
77
116
  /**
78
117
  * Close a story at its end: a field still open there never closes, and must
@@ -114,6 +153,12 @@ export type ParagraphRead = {
114
153
  pageBreakBefore: boolean | null;
115
154
  /** `w:jc` as the paragraph itself states it, or null. */
116
155
  alignment: string | null;
156
+ /** The space in front and behind (`w:spacing`) the paragraph itself
157
+ * states, in twentieths of a point; null for a side it does not state. */
158
+ spacing: {
159
+ before: number | null;
160
+ after: number | null;
161
+ };
117
162
  /** The sides of `w:ind` the paragraph itself states, in twentieths of a
118
163
  * point: where its lines start, and what its first line adds to that
119
164
  * (negative for a hanging indent). Null for a side it does not state. */
@@ -18,14 +18,16 @@ const SELF_NUMBERING_FIELDS = /* @__PURE__ */ new Set([
18
18
  ]);
19
19
  /** Whether a field kind prints a number of its own and caches no text. */
20
20
  const isSelfNumberingField = (kind) => SELF_NUMBERING_FIELDS.has(kind);
21
- const createStoryState = () => ({
21
+ const createStoryState = (options = {}) => ({
22
22
  fields: [],
23
23
  open: [],
24
24
  paragraphOrdinal: 0,
25
25
  comments: 0,
26
26
  trackedChanges: 0,
27
27
  formattingRevisions: 0,
28
- strayFieldEnds: 0
28
+ strayFieldEnds: 0,
29
+ keepsRevisions: options.keepsRevisions === true,
30
+ untaggedRevisions: 0
29
31
  });
30
32
  /** A bookmark start, with how many atoms of its paragraph come before it. */
31
33
  /**
@@ -51,6 +53,24 @@ const ownIndent = (indent) => {
51
53
  firstLine: hanging === null ? twipsOrNull(wAttr(indent, "firstLine")) : -hanging
52
54
  };
53
55
  };
56
+ const SWITCHED_ON = /* @__PURE__ */ new Set([
57
+ "1",
58
+ "true",
59
+ "on"
60
+ ]);
61
+ /**
62
+ * The space in front of a paragraph and behind it as its own `w:spacing`
63
+ * states it in twentieths of a point. A side set to follow the application
64
+ * (`beforeAutospacing`) or counted in lines (`beforeLines`) is not such a
65
+ * measure and reads as not stated.
66
+ */
67
+ const ownSpacing = (spacing) => {
68
+ const side = (name) => SWITCHED_ON.has(wAttr(spacing, `${name}Autospacing`) ?? "") || wAttr(spacing, `${name}Lines`) !== null ? null : twipsOrNull(wAttr(spacing, name));
69
+ return {
70
+ before: side("before"),
71
+ after: side("after")
72
+ };
73
+ };
54
74
  const TOGGLE_OFF = /* @__PURE__ */ new Set([
55
75
  "0",
56
76
  "false",
@@ -186,23 +206,65 @@ const beginField = (walk, instruction) => {
186
206
  read.fieldIndices.push(field.index);
187
207
  return field;
188
208
  };
189
- const readRun = (run, walk, { link }) => {
209
+ /** What a deleted run holds as text; null for content that is none. */
210
+ const deletedTextOf = (child) => {
211
+ switch (wName(child)) {
212
+ case "delText": return textOf(child);
213
+ case "tab": return " ";
214
+ case "cr": return "\n";
215
+ case "br": return wAttr(child, "type") === null ? "\n" : null;
216
+ default: return null;
217
+ }
218
+ };
219
+ /** A deleted run, read as one atom that holds what was deleted. */
220
+ const readDeletedRun = (run, walk, { link, revision }) => {
221
+ let deleted = "";
222
+ for (const child of elementChildren(run)) {
223
+ const name = wName(child);
224
+ const text = deletedTextOf(child);
225
+ if (text !== null) deleted += text;
226
+ else if (name !== "rPr" && name !== "lastRenderedPageBreak") walk.state.untaggedRevisions += 1;
227
+ }
228
+ if (deleted !== "") pushAtom(walk, {
229
+ kind: "text",
230
+ text: "",
231
+ runProperties: wChild(run, "rPr"),
232
+ link,
233
+ element: null,
234
+ revision: {
235
+ ...revision,
236
+ deleted
237
+ }
238
+ });
239
+ };
240
+ const readRun = (run, walk, context) => {
241
+ const { link, revision } = context;
190
242
  const { state, read } = walk;
191
243
  const runProperties = wChild(run, "rPr");
192
244
  if (wChild(runProperties, "rPrChange") !== null) state.formattingRevisions += 1;
245
+ if (revision?.kind === "del") {
246
+ readDeletedRun(run, walk, {
247
+ link,
248
+ revision
249
+ });
250
+ return;
251
+ }
193
252
  const atom = (kind, text, element) => {
194
253
  pushAtom(walk, {
195
254
  kind,
196
255
  text,
197
256
  runProperties,
198
257
  link,
199
- element
258
+ element,
259
+ ...revision === void 0 ? {} : { revision }
200
260
  });
201
261
  };
202
262
  const object = (element) => {
203
263
  if (inCode(state)) return;
204
264
  read.inlineObjects += 1;
205
- state.trackedChanges += countContentRevisions(element);
265
+ const inside = countContentRevisions(element);
266
+ state.trackedChanges += inside;
267
+ state.untaggedRevisions += state.keepsRevisions ? inside : 0;
206
268
  atom("object", "", element);
207
269
  };
208
270
  for (const child of elementChildren(run)) {
@@ -290,6 +352,15 @@ const readRun = (run, walk, { link }) => {
290
352
  }
291
353
  }
292
354
  };
355
+ /** The tag of an inline insertion or deletion; null for a move. */
356
+ const revisionOf = (element, name) => {
357
+ if (name !== "ins" && name !== "del") return null;
358
+ return {
359
+ kind: name,
360
+ author: wAttr(element, "author") ?? "",
361
+ date: wAttr(element, "date")
362
+ };
363
+ };
293
364
  const readInline = (container, walk, context) => {
294
365
  const { state, read } = walk;
295
366
  for (const child of elementChildren(container)) {
@@ -297,13 +368,16 @@ const readInline = (container, walk, context) => {
297
368
  if (name === null) {
298
369
  if (child.namespaceUri === MATH_NAMESPACE && !inCode(state) && (getLocalName(child.name) === "oMath" || getLocalName(child.name) === "oMathPara")) {
299
370
  read.inlineObjects += 1;
300
- state.trackedChanges += countContentRevisions(child);
371
+ const inside = countContentRevisions(child);
372
+ state.trackedChanges += inside;
373
+ state.untaggedRevisions += state.keepsRevisions ? inside : 0;
301
374
  pushAtom(walk, {
302
375
  kind: "object",
303
376
  text: "",
304
377
  runProperties: null,
305
378
  link: context.link,
306
- element: child
379
+ element: child,
380
+ ...context.revision === void 0 ? {} : { revision: context.revision }
307
381
  });
308
382
  } else if (!inCode(state)) read.unsupported.push(child.name ?? "");
309
383
  continue;
@@ -341,11 +415,27 @@ const readInline = (container, walk, context) => {
341
415
  element: null,
342
416
  instruction: field.instruction.trim()
343
417
  });
344
- } else if (REVISION_INCLUDED.has(name)) {
418
+ } else if (REVISION_INCLUDED.has(name) || REVISION_EXCLUDED.has(name)) {
345
419
  state.trackedChanges += 1;
346
- readInline(child, walk, context);
347
- } else if (REVISION_EXCLUDED.has(name)) state.trackedChanges += 1;
348
- else if (name === "sdt") {
420
+ const kept = state.keepsRevisions ? revisionOf(child, name) : null;
421
+ const outer = context.revision;
422
+ if (kept !== null && outer !== void 0) {
423
+ if (kept.kind === "del" && outer.kind === "ins" && !outer.within) kept.within = {
424
+ author: outer.author,
425
+ date: outer.date
426
+ };
427
+ else state.untaggedRevisions += 1;
428
+ }
429
+ if (kept !== null) {
430
+ readInline(child, walk, {
431
+ ...context,
432
+ revision: kept
433
+ });
434
+ continue;
435
+ }
436
+ state.untaggedRevisions += state.keepsRevisions ? 1 : 0;
437
+ if (REVISION_INCLUDED.has(name)) readInline(child, walk, context);
438
+ } else if (name === "sdt") {
349
439
  const content = wChild(child, "sdtContent");
350
440
  if (content !== null) readInline(content, walk, context);
351
441
  } else if (TRANSPARENT_WRAPPERS.has(name)) readInline(child, walk, context);
@@ -361,6 +451,28 @@ const readInline = (container, walk, context) => {
361
451
  else if (!IGNORED_INLINE_CHILDREN.has(name) && !inCode(state)) read.unsupported.push(name);
362
452
  }
363
453
  };
454
+ /**
455
+ * The paragraph mark's own revision, in a reading that keeps them. An
456
+ * inserted mark is an atom at the paragraph's end. A deleted one was joined
457
+ * to the next paragraph before the reading; one still here had none to join.
458
+ */
459
+ const readTrackedMark = (mark, walk) => {
460
+ const inserted = wChild(mark, "ins");
461
+ if (wChild(mark, "del") !== null) walk.state.untaggedRevisions += 1;
462
+ else if (inserted !== null) pushAtom(walk, {
463
+ kind: "text",
464
+ text: "",
465
+ runProperties: null,
466
+ link: null,
467
+ element: null,
468
+ revision: {
469
+ kind: "ins",
470
+ author: wAttr(inserted, "author") ?? "",
471
+ date: wAttr(inserted, "date"),
472
+ mark: true
473
+ }
474
+ });
475
+ };
364
476
  /** Read one `w:p`, advancing the story's field and revision state. */
365
477
  const readParagraph = (element, state) => {
366
478
  const properties = wChild(element, "pPr");
@@ -388,6 +500,7 @@ const readParagraph = (element, state) => {
388
500
  hasSectionBreak: wChild(properties, "sectPr") !== null,
389
501
  pageBreakBefore: toggleOf(wChild(properties, "pageBreakBefore")),
390
502
  alignment: wChildVal(properties, "jc"),
503
+ spacing: ownSpacing(wChild(properties, "spacing")),
391
504
  indent: ownIndent(wChild(properties, "ind")),
392
505
  indentInCharacters: CHARACTER_INDENTS.some((name) => {
393
506
  const value = wAttr(wChild(properties, "ind"), name);
@@ -403,6 +516,7 @@ const readParagraph = (element, state) => {
403
516
  };
404
517
  for (const open of state.open) if (open.phase === "result" && open.field.result !== "") open.field.result += "\n";
405
518
  readInline(element, walk, { link: null });
519
+ if (state.keepsRevisions) readTrackedMark(mark, walk);
406
520
  read.text = read.atoms.map(({ text }) => text).join("");
407
521
  return read;
408
522
  };