@beyondwork/docx-react-component 1.0.18 → 1.0.20

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 (105) hide show
  1. package/README.md +8 -2
  2. package/package.json +24 -34
  3. package/src/api/README.md +5 -1
  4. package/src/api/public-types.ts +710 -4
  5. package/src/api/session-state.ts +60 -0
  6. package/src/core/commands/formatting-commands.ts +2 -1
  7. package/src/core/commands/image-commands.ts +147 -0
  8. package/src/core/commands/index.ts +19 -3
  9. package/src/core/commands/list-commands.ts +231 -36
  10. package/src/core/commands/paragraph-layout-commands.ts +339 -0
  11. package/src/core/commands/section-layout-commands.ts +680 -0
  12. package/src/core/commands/style-commands.ts +262 -0
  13. package/src/core/search/search-text.ts +357 -0
  14. package/src/core/selection/mapping.ts +41 -0
  15. package/src/core/state/editor-state.ts +4 -1
  16. package/src/index.ts +51 -0
  17. package/src/io/docx-session.ts +623 -56
  18. package/src/io/export/serialize-comments.ts +104 -34
  19. package/src/io/export/serialize-footnotes.ts +198 -1
  20. package/src/io/export/serialize-headers-footers.ts +203 -10
  21. package/src/io/export/serialize-main-document.ts +285 -8
  22. package/src/io/export/serialize-numbering.ts +28 -7
  23. package/src/io/export/split-review-boundaries.ts +181 -19
  24. package/src/io/normalize/normalize-text.ts +144 -32
  25. package/src/io/ooxml/highlight-colors.ts +39 -0
  26. package/src/io/ooxml/numbering-sentinels.ts +44 -0
  27. package/src/io/ooxml/parse-comments.ts +85 -19
  28. package/src/io/ooxml/parse-fields.ts +396 -0
  29. package/src/io/ooxml/parse-footnotes.ts +452 -22
  30. package/src/io/ooxml/parse-headers-footers.ts +657 -29
  31. package/src/io/ooxml/parse-inline-media.ts +30 -0
  32. package/src/io/ooxml/parse-main-document.ts +807 -20
  33. package/src/io/ooxml/parse-numbering.ts +7 -0
  34. package/src/io/ooxml/parse-revisions.ts +317 -38
  35. package/src/io/ooxml/parse-settings.ts +184 -0
  36. package/src/io/ooxml/parse-shapes.ts +25 -0
  37. package/src/io/ooxml/parse-styles.ts +463 -0
  38. package/src/io/ooxml/parse-theme.ts +32 -0
  39. package/src/legal/bookmarks.ts +44 -0
  40. package/src/legal/cross-references.ts +59 -1
  41. package/src/model/canonical-document.ts +250 -4
  42. package/src/model/cds-1.0.0.ts +13 -0
  43. package/src/model/snapshot.ts +87 -2
  44. package/src/review/store/revision-store.ts +6 -0
  45. package/src/review/store/revision-types.ts +1 -0
  46. package/src/runtime/document-layout.ts +332 -0
  47. package/src/runtime/document-navigation.ts +603 -0
  48. package/src/runtime/document-runtime.ts +1754 -78
  49. package/src/runtime/document-search.ts +145 -0
  50. package/src/runtime/numbering-prefix.ts +47 -26
  51. package/src/runtime/page-layout-estimation.ts +212 -0
  52. package/src/runtime/read-only-diagnostics-runtime.ts +9 -0
  53. package/src/runtime/session-capabilities.ts +35 -3
  54. package/src/runtime/story-context.ts +164 -0
  55. package/src/runtime/story-targeting.ts +162 -0
  56. package/src/runtime/surface-projection.ts +324 -36
  57. package/src/runtime/table-schema.ts +89 -7
  58. package/src/runtime/view-state.ts +477 -0
  59. package/src/runtime/workflow-markup.ts +349 -0
  60. package/src/ui/WordReviewEditor.tsx +2469 -1344
  61. package/src/ui/browser-export.ts +52 -0
  62. package/src/ui/editor-command-bag.ts +120 -0
  63. package/src/ui/editor-runtime-boundary.ts +1422 -0
  64. package/src/ui/editor-shell-view.tsx +134 -0
  65. package/src/ui/editor-surface-controller.tsx +51 -0
  66. package/src/ui/headless/preserve-editor-selection.ts +5 -0
  67. package/src/ui/headless/revision-decoration-model.ts +4 -4
  68. package/src/ui/headless/selection-helpers.ts +20 -0
  69. package/src/ui/headless/selection-toolbar-model.ts +22 -0
  70. package/src/ui/headless/use-editor-keyboard.ts +6 -1
  71. package/src/ui/runtime-snapshot-selectors.ts +197 -0
  72. package/src/ui-tailwind/chrome/tw-alert-banner.tsx +18 -2
  73. package/src/ui-tailwind/chrome/tw-image-context-toolbar.tsx +129 -0
  74. package/src/ui-tailwind/chrome/tw-layout-panel.tsx +114 -0
  75. package/src/ui-tailwind/chrome/tw-object-context-toolbar.tsx +34 -0
  76. package/src/ui-tailwind/chrome/tw-page-ruler.tsx +386 -0
  77. package/src/ui-tailwind/chrome/tw-selection-toolbar.tsx +150 -14
  78. package/src/ui-tailwind/chrome/tw-table-context-toolbar.tsx +128 -0
  79. package/src/ui-tailwind/editor-surface/perf-probe.ts +179 -0
  80. package/src/ui-tailwind/editor-surface/pm-command-bridge.ts +46 -7
  81. package/src/ui-tailwind/editor-surface/pm-contextual-ui.ts +31 -0
  82. package/src/ui-tailwind/editor-surface/pm-decorations.ts +35 -0
  83. package/src/ui-tailwind/editor-surface/pm-position-map.ts +3 -3
  84. package/src/ui-tailwind/editor-surface/pm-schema.ts +186 -13
  85. package/src/ui-tailwind/editor-surface/pm-state-from-snapshot.ts +191 -68
  86. package/src/ui-tailwind/editor-surface/search-plugin.ts +19 -68
  87. package/src/ui-tailwind/editor-surface/surface-build-keys.ts +51 -0
  88. package/src/ui-tailwind/editor-surface/tw-inline-token.tsx +11 -0
  89. package/src/ui-tailwind/editor-surface/tw-opaque-block.tsx +7 -1
  90. package/src/ui-tailwind/editor-surface/tw-prosemirror-surface.tsx +528 -85
  91. package/src/ui-tailwind/editor-surface/tw-table-node-view.tsx +0 -1
  92. package/src/ui-tailwind/index.ts +2 -1
  93. package/src/ui-tailwind/page-chrome-model.ts +27 -0
  94. package/src/ui-tailwind/review/tw-comment-sidebar.tsx +277 -147
  95. package/src/ui-tailwind/review/tw-health-panel.tsx +31 -2
  96. package/src/ui-tailwind/review/tw-review-rail.tsx +8 -8
  97. package/src/ui-tailwind/review/tw-revision-sidebar.tsx +15 -15
  98. package/src/ui-tailwind/theme/editor-theme.css +127 -0
  99. package/src/ui-tailwind/toolbar/tw-toolbar-icon-button.tsx +4 -0
  100. package/src/ui-tailwind/toolbar/tw-toolbar.tsx +829 -12
  101. package/src/ui-tailwind/tw-review-workspace.tsx +1238 -42
  102. package/src/validation/compatibility-engine.ts +119 -24
  103. package/src/validation/compatibility-report.ts +1 -0
  104. package/src/validation/diagnostics.ts +1 -0
  105. package/src/validation/docx-comment-proof.ts +707 -0
@@ -65,6 +65,8 @@ export interface CommentImportDiagnostic {
65
65
  | "preserve_only_revision_overlap";
66
66
  message: string;
67
67
  featureClass: "preserve-only";
68
+ detachedReason?: "incomplete-markers" | "multi-paragraph" | "opaque-region" | "revision-overlap";
69
+ actionabilityNote?: string;
68
70
  }
69
71
 
70
72
  export interface ParsedCommentsResult {
@@ -143,8 +145,10 @@ export function parseCommentsFromOoxml(
143
145
  diagnostics.push({
144
146
  commentId: rootCommentId,
145
147
  code: "missing_anchor_reference",
146
- message: "Comment anchor markers are incomplete and remain preserve-only.",
148
+ message: "Comment anchor markers are incomplete (missing start, end, or reference). Thread is visible but detached and not actionable.",
147
149
  featureClass: "preserve-only",
150
+ detachedReason: "incomplete-markers",
151
+ actionabilityNote: "Re-anchoring requires the host to supply a valid range. The comment body and thread are preserved for display.",
148
152
  });
149
153
  threads.push(
150
154
  createImportedCommentThread({
@@ -171,8 +175,10 @@ export function parseCommentsFromOoxml(
171
175
  commentId: rootCommentId,
172
176
  code: "multi_paragraph_anchor_preserve_only",
173
177
  message:
174
- "Comment anchor spans multiple paragraphs and remains preserve-only for Wave 5.",
178
+ "Comment anchor spans multiple paragraphs. Thread is visible but detached; cross-paragraph anchoring is not yet supported for live editing.",
175
179
  featureClass: "preserve-only",
180
+ detachedReason: "multi-paragraph",
181
+ actionabilityNote: "The comment thread and body are preserved. Operators see the thread in the sidebar but cannot navigate to an inline highlight.",
176
182
  });
177
183
  threads.push(
178
184
  createImportedCommentThread({
@@ -470,32 +476,92 @@ function parseCommentAnchors(documentXml: string): Map<string, CommentAnchorBoun
470
476
  const documentElement = findChildElement(root, "document");
471
477
  const bodyElement = findChildElement(documentElement, "body");
472
478
  const anchors = new Map<string, CommentAnchorBounds>();
473
- let cursor = 0;
474
- let paragraphIndex = -1;
475
- let previousWasParagraph = false;
479
+ walkCommentAnchorBlocks(bodyElement.children, anchors, 0, -1, true);
476
480
 
477
- for (const child of bodyElement.children) {
478
- if (child.type !== "element") {
481
+ return anchors;
482
+ }
483
+
484
+ function walkCommentAnchorBlocks(
485
+ nodes: readonly XmlNode[],
486
+ anchors: Map<string, CommentAnchorBounds>,
487
+ cursor: number,
488
+ paragraphIndex: number,
489
+ useSurfaceParagraphSeparators: boolean,
490
+ ): {
491
+ cursor: number;
492
+ paragraphIndex: number;
493
+ } {
494
+ let nextCursor = cursor;
495
+ let nextParagraphIndex = paragraphIndex;
496
+ let elementIndex = -1;
497
+
498
+ for (const node of nodes) {
499
+ if (node.type !== "element") {
479
500
  continue;
480
501
  }
502
+ elementIndex += 1;
481
503
 
482
- if (localName(child.name) !== "p") {
483
- cursor += 1;
484
- previousWasParagraph = false;
504
+ const name = localName(node.name);
505
+ if (name === "p") {
506
+ if (useSurfaceParagraphSeparators && elementIndex > 0) {
507
+ nextCursor += 1;
508
+ }
509
+ nextParagraphIndex += 1;
510
+ walkParagraph(node, nextParagraphIndex, anchors, () => nextCursor, (next) => {
511
+ nextCursor = next;
512
+ });
485
513
  continue;
486
514
  }
487
515
 
488
- if (previousWasParagraph) {
489
- cursor += 1;
516
+ if (name === "tbl") {
517
+ for (const child of node.children) {
518
+ if (child.type !== "element" || localName(child.name) !== "tr") {
519
+ continue;
520
+ }
521
+ for (const rowChild of child.children) {
522
+ if (rowChild.type !== "element" || localName(rowChild.name) !== "tc") {
523
+ continue;
524
+ }
525
+ const result = walkCommentAnchorBlocks(
526
+ rowChild.children,
527
+ anchors,
528
+ nextCursor,
529
+ nextParagraphIndex,
530
+ false,
531
+ );
532
+ nextCursor = result.cursor;
533
+ nextParagraphIndex = result.paragraphIndex;
534
+ }
535
+ }
536
+ continue;
490
537
  }
491
- paragraphIndex += 1;
492
- walkParagraph(child, paragraphIndex, anchors, () => cursor, (next) => {
493
- cursor = next;
494
- });
495
- previousWasParagraph = true;
538
+
539
+ if (name === "sdt") {
540
+ const sdtContent = findChildElement(node, "sdtContent");
541
+ const result = walkCommentAnchorBlocks(
542
+ sdtContent.children,
543
+ anchors,
544
+ nextCursor,
545
+ nextParagraphIndex,
546
+ false,
547
+ );
548
+ nextCursor = result.cursor;
549
+ nextParagraphIndex = result.paragraphIndex;
550
+ continue;
551
+ }
552
+
553
+ if (name === "customXml") {
554
+ nextCursor += 1;
555
+ continue;
556
+ }
557
+
558
+ nextCursor += 0;
496
559
  }
497
560
 
498
- return anchors;
561
+ return {
562
+ cursor: nextCursor,
563
+ paragraphIndex: nextParagraphIndex,
564
+ };
499
565
  }
500
566
 
501
567
  function walkParagraph(
@@ -554,7 +620,7 @@ function walkInlineNode(
554
620
  .filter((child): child is XmlTextNode => child.type === "text")
555
621
  .map((child) => child.text)
556
622
  .join("");
557
- setCursor(getCursor() + text.length);
623
+ setCursor(getCursor() + Array.from(text).length);
558
624
  return;
559
625
  }
560
626
  case "tab":
@@ -194,6 +194,402 @@ export function parseBookmarkEnd(
194
194
  };
195
195
  }
196
196
 
197
+ // ─── Field family classification ─────────────────────────────────────────────
198
+
199
+ import type {
200
+ CanonicalDocument,
201
+ DocumentNode,
202
+ FieldFamily,
203
+ FieldNode,
204
+ FieldRegistry,
205
+ FieldRegistryEntry,
206
+ FieldRefreshStatus,
207
+ InlineNode,
208
+ ParagraphNode,
209
+ SubPartsCatalog,
210
+ SupportedFieldFamily,
211
+ TocEntry,
212
+ TocStructure,
213
+ } from "../../model/canonical-document.ts";
214
+
215
+ const FIELD_FAMILY_PATTERN =
216
+ /^\s*(REF|PAGEREF|NOTEREF|TOC|PAGE|NUMPAGES|DATE|TIME|AUTHOR|FILENAME|MERGEFIELD|IF|SEQ|INDEX|TC|STYLEREF)\b/i;
217
+
218
+ const SUPPORTED_FAMILIES = new Set<string>(["REF", "PAGEREF", "NOTEREF", "TOC"]);
219
+
220
+ /**
221
+ * Classify a field instruction into its field family.
222
+ * Returns the family enum value and whether it is in the supported slice.
223
+ */
224
+ export function classifyFieldInstruction(instruction: string): {
225
+ family: FieldFamily;
226
+ supported: boolean;
227
+ target?: string;
228
+ } {
229
+ const trimmed = instruction.trim();
230
+ const match = FIELD_FAMILY_PATTERN.exec(trimmed);
231
+ if (!match) {
232
+ return { family: "UNKNOWN", supported: false };
233
+ }
234
+
235
+ const family = match[1].toUpperCase() as FieldFamily;
236
+ const supported = SUPPORTED_FAMILIES.has(family);
237
+
238
+ let target: string | undefined;
239
+ if (family === "REF" || family === "PAGEREF" || family === "NOTEREF") {
240
+ const targetMatch = /^\s*(?:REF|PAGEREF|NOTEREF)\s+(?:"([^"]+)"|(\S+))/i.exec(trimmed);
241
+ target = (targetMatch?.[1] ?? targetMatch?.[2])?.trim();
242
+ }
243
+
244
+ return { family, supported, target };
245
+ }
246
+
247
+ /**
248
+ * Returns true if the given field family is in the supported refresh slice.
249
+ */
250
+ export function isSupportedFieldFamily(family: FieldFamily): family is SupportedFieldFamily {
251
+ return SUPPORTED_FAMILIES.has(family);
252
+ }
253
+
254
+ // ─── Field registry builder ─────────────────────────────────────────────────
255
+
256
+ /**
257
+ * Build a field registry from a canonical document, cataloging every field
258
+ * instance with its classification, dependency metadata, and refresh status.
259
+ *
260
+ * The registry partitions fields into `supported` (REF, PAGEREF, NOTEREF, TOC)
261
+ * and `preserveOnly` (all others) slices.
262
+ */
263
+ export function buildFieldRegistry(
264
+ document: Pick<CanonicalDocument, "content" | "styles"> & {
265
+ subParts?: SubPartsCatalog;
266
+ },
267
+ ): FieldRegistry {
268
+ const root = document.content;
269
+ const supported: FieldRegistryEntry[] = [];
270
+ const preserveOnly: FieldRegistryEntry[] = [];
271
+ let fieldIndex = 0;
272
+ let paragraphIndex = -1;
273
+ let tocInstruction: string | undefined;
274
+
275
+ walkFieldDocument(root, (node, pIdx) => {
276
+ paragraphIndex = pIdx;
277
+ if (node.type === "field") {
278
+ const classification = node.fieldFamily
279
+ ? { family: node.fieldFamily, supported: isSupportedFieldFamily(node.fieldFamily), target: node.fieldTarget }
280
+ : classifyFieldInstruction(node.instruction);
281
+ const displayText = flattenFieldText(node.children);
282
+ const entry: FieldRegistryEntry = {
283
+ fieldIndex,
284
+ fieldFamily: classification.family,
285
+ supported: classification.supported,
286
+ instruction: node.instruction,
287
+ ...(classification.target ? { fieldTarget: classification.target } : {}),
288
+ displayText,
289
+ paragraphIndex,
290
+ refreshStatus: node.refreshStatus ?? (classification.supported ? "stale" : "preserve-only"),
291
+ };
292
+ if (classification.supported) {
293
+ supported.push(entry);
294
+ if (classification.family === "TOC" && !tocInstruction) {
295
+ tocInstruction = node.instruction;
296
+ }
297
+ } else {
298
+ preserveOnly.push(entry);
299
+ }
300
+ fieldIndex += 1;
301
+ }
302
+ });
303
+ if (document.subParts) {
304
+ walkSubPartFields(document.subParts, (node, pIdx) => {
305
+ paragraphIndex = pIdx;
306
+ if (node.type === "field") {
307
+ const classification = node.fieldFamily
308
+ ? { family: node.fieldFamily, supported: isSupportedFieldFamily(node.fieldFamily), target: node.fieldTarget }
309
+ : classifyFieldInstruction(node.instruction);
310
+ const displayText = flattenFieldText(node.children);
311
+ const entry: FieldRegistryEntry = {
312
+ fieldIndex,
313
+ fieldFamily: classification.family,
314
+ supported: classification.supported,
315
+ instruction: node.instruction,
316
+ ...(classification.target ? { fieldTarget: classification.target } : {}),
317
+ displayText,
318
+ paragraphIndex,
319
+ refreshStatus: node.refreshStatus ?? (classification.supported ? "stale" : "preserve-only"),
320
+ };
321
+ if (classification.supported) {
322
+ supported.push(entry);
323
+ } else {
324
+ preserveOnly.push(entry);
325
+ }
326
+ fieldIndex += 1;
327
+ }
328
+ });
329
+ }
330
+
331
+ const tocStructure = tocInstruction
332
+ ? buildTocStructure(document, tocInstruction)
333
+ : undefined;
334
+
335
+ return {
336
+ supported,
337
+ preserveOnly,
338
+ ...(tocStructure ? { tocStructure } : {}),
339
+ };
340
+ }
341
+
342
+ /**
343
+ * Parse the heading level range from a TOC field instruction.
344
+ * The \\o switch specifies the outline level range (e.g. \\o "1-3").
345
+ * Defaults to 1-9 if no \\o switch is present.
346
+ */
347
+ export function parseTocLevelRange(instruction: string): { from: number; to: number } {
348
+ const match = /\\o\s+"(\d+)-(\d+)"/.exec(instruction);
349
+ if (match) {
350
+ return { from: Number.parseInt(match[1], 10), to: Number.parseInt(match[2], 10) };
351
+ }
352
+ return { from: 1, to: 9 };
353
+ }
354
+
355
+ /**
356
+ * Build a TocStructure from the document's heading paragraphs and the
357
+ * TOC field instruction. This produces a deterministic, package-backed
358
+ * TOC model that the runtime can use for refresh without DOM recomputation.
359
+ */
360
+ export function buildTocStructure(
361
+ document: Pick<CanonicalDocument, "content" | "styles">,
362
+ instruction: string,
363
+ ): TocStructure {
364
+ const levelRange = parseTocLevelRange(instruction);
365
+ const entries: TocEntry[] = [];
366
+ let paragraphIndex = -1;
367
+
368
+ walkFieldDocument(document.content, (node, pIdx) => {
369
+ paragraphIndex = pIdx;
370
+ if (node.type !== "paragraph") return;
371
+ const paragraph = node as ParagraphNode;
372
+
373
+ // Determine heading level from outlineLevel or style
374
+ let level: number | undefined = paragraph.outlineLevel;
375
+ if (level === undefined && paragraph.styleId) {
376
+ const style = document.styles.paragraphs[paragraph.styleId];
377
+ if (style?.outlineLevel !== undefined) {
378
+ level = style.outlineLevel;
379
+ }
380
+ }
381
+
382
+ if (level === undefined) return;
383
+ // TOC outline levels are 0-based internally, 1-based in TOC notation
384
+ const tocLevel = level + 1;
385
+ if (tocLevel < levelRange.from || tocLevel > levelRange.to) return;
386
+
387
+ const text = flattenParagraphInlineText(paragraph.children);
388
+ if (text.trim().length === 0) return;
389
+
390
+ // Find bookmark anchoring this heading
391
+ let bookmarkName: string | undefined;
392
+ for (const child of paragraph.children) {
393
+ if (child.type === "bookmark_start" && child.name) {
394
+ bookmarkName = child.name;
395
+ break;
396
+ }
397
+ }
398
+
399
+ entries.push({
400
+ text: text.trim(),
401
+ level: tocLevel,
402
+ paragraphIndex,
403
+ ...(paragraph.styleId ? { styleId: paragraph.styleId } : {}),
404
+ ...(bookmarkName ? { bookmarkName } : {}),
405
+ });
406
+ });
407
+
408
+ return {
409
+ instruction,
410
+ levelRange,
411
+ entries,
412
+ status: "stale",
413
+ };
414
+ }
415
+
416
+ /**
417
+ * Deterministic refresh helper for REF fields.
418
+ * Given a bookmark name map and the document content, resolves the display
419
+ * text for a REF field by extracting text from the bookmarked paragraph.
420
+ *
421
+ * Returns the resolved text, or undefined if the bookmark is not found.
422
+ */
423
+ export function resolveRefFieldText(
424
+ document: Pick<CanonicalDocument, "content">,
425
+ bookmarkNameMap: Map<string, { bookmarkId: string; paragraphIndex: number }>,
426
+ fieldTarget: string,
427
+ ): { text: string; refreshStatus: "current" | "unresolvable" } | undefined {
428
+ const bookmark = bookmarkNameMap.get(fieldTarget);
429
+ if (!bookmark) {
430
+ return { text: "", refreshStatus: "unresolvable" };
431
+ }
432
+
433
+ // Find the paragraph at bookmarkIndex and extract its text content
434
+ let paragraphIndex = -1;
435
+ let resolvedText: string | undefined;
436
+
437
+ walkFieldDocument(document.content, (node, pIdx) => {
438
+ if (node.type !== "paragraph") return;
439
+ paragraphIndex = pIdx;
440
+ if (paragraphIndex === bookmark.paragraphIndex) {
441
+ resolvedText = flattenBookmarkContent(node as ParagraphNode, bookmark.bookmarkId);
442
+ }
443
+ });
444
+
445
+ if (resolvedText !== undefined) {
446
+ return { text: resolvedText, refreshStatus: "current" };
447
+ }
448
+ return { text: "", refreshStatus: "unresolvable" };
449
+ }
450
+
451
+ /**
452
+ * Deterministic refresh helper that updates all supported field entries
453
+ * in a registry with their current resolved status.
454
+ *
455
+ * This does NOT mutate the document nodes — it returns a new registry
456
+ * with updated refresh statuses. A3 owns the runtime wiring that
457
+ * applies these to the live document.
458
+ */
459
+ export function refreshFieldRegistry(
460
+ registry: FieldRegistry,
461
+ bookmarkNameMap: Map<string, { bookmarkId: string; paragraphIndex: number }>,
462
+ ): FieldRegistry {
463
+ const refreshed: FieldRegistryEntry[] = registry.supported.map((entry) => {
464
+ if (entry.fieldFamily === "TOC") {
465
+ // TOC refresh is handled through tocStructure, not individual entries
466
+ return { ...entry, refreshStatus: registry.tocStructure ? "current" : "stale" as FieldRefreshStatus };
467
+ }
468
+ if (!entry.fieldTarget) {
469
+ return { ...entry, refreshStatus: "unresolvable" as FieldRefreshStatus };
470
+ }
471
+ const bookmark = bookmarkNameMap.get(entry.fieldTarget);
472
+ if (!bookmark) {
473
+ return { ...entry, refreshStatus: "unresolvable" as FieldRefreshStatus };
474
+ }
475
+ return { ...entry, refreshStatus: "current" as FieldRefreshStatus };
476
+ });
477
+
478
+ return {
479
+ supported: refreshed,
480
+ preserveOnly: registry.preserveOnly,
481
+ ...(registry.tocStructure ? { tocStructure: registry.tocStructure } : {}),
482
+ };
483
+ }
484
+
485
+ // ─── Field registry internal helpers ────────────────────────────────────────
486
+
487
+ function walkFieldDocument(
488
+ node: DocumentNode,
489
+ visit: (node: DocumentNode, paragraphIndex: number) => void,
490
+ paragraphIndex = -1,
491
+ ): number {
492
+ if (node.type === "paragraph") {
493
+ paragraphIndex += 1;
494
+ }
495
+ visit(node, paragraphIndex);
496
+
497
+ if ("children" in node && Array.isArray(node.children)) {
498
+ for (const child of node.children) {
499
+ paragraphIndex = walkFieldDocument(child as DocumentNode, visit, paragraphIndex);
500
+ }
501
+ }
502
+ if (node.type === "table") {
503
+ for (const row of node.rows) {
504
+ paragraphIndex = walkFieldDocument(row, visit, paragraphIndex);
505
+ }
506
+ } else if (node.type === "table_row") {
507
+ for (const cell of node.cells) {
508
+ paragraphIndex = walkFieldDocument(cell, visit, paragraphIndex);
509
+ }
510
+ }
511
+ return paragraphIndex;
512
+ }
513
+
514
+ function walkSubPartFields(
515
+ subParts: SubPartsCatalog,
516
+ visit: (node: DocumentNode, paragraphIndex: number) => void,
517
+ ): void {
518
+ for (const header of subParts.headers) {
519
+ for (const block of header.blocks) {
520
+ walkFieldDocument(block, visit);
521
+ }
522
+ }
523
+ for (const footer of subParts.footers) {
524
+ for (const block of footer.blocks) {
525
+ walkFieldDocument(block, visit);
526
+ }
527
+ }
528
+ if (subParts.footnoteCollection) {
529
+ for (const note of Object.values(subParts.footnoteCollection.footnotes)) {
530
+ for (const block of note.blocks) {
531
+ walkFieldDocument(block, visit);
532
+ }
533
+ }
534
+ for (const note of Object.values(subParts.footnoteCollection.endnotes)) {
535
+ for (const block of note.blocks) {
536
+ walkFieldDocument(block, visit);
537
+ }
538
+ }
539
+ }
540
+ }
541
+
542
+ function flattenFieldText(children: InlineNode[]): string {
543
+ return children
544
+ .map((child) => {
545
+ if (child.type === "text") return child.text;
546
+ if (child.type === "tab") return "\t";
547
+ if (child.type === "hard_break" || child.type === "column_break") return "\n";
548
+ return "";
549
+ })
550
+ .join("");
551
+ }
552
+
553
+ function flattenParagraphInlineText(children: InlineNode[]): string {
554
+ return children
555
+ .map((child) => {
556
+ if (child.type === "text") return child.text;
557
+ if (child.type === "tab") return "\t";
558
+ if (child.type === "hard_break" || child.type === "column_break") return "\n";
559
+ if (child.type === "hyperlink") return flattenFieldText(child.children);
560
+ if (child.type === "field") return flattenFieldText(child.children);
561
+ return "";
562
+ })
563
+ .join("");
564
+ }
565
+
566
+ function flattenBookmarkContent(
567
+ paragraph: ParagraphNode,
568
+ bookmarkId: string,
569
+ ): string {
570
+ let inside = false;
571
+ const parts: string[] = [];
572
+ for (const child of paragraph.children) {
573
+ if (child.type === "bookmark_start" && child.bookmarkId === bookmarkId) {
574
+ inside = true;
575
+ continue;
576
+ }
577
+ if (child.type === "bookmark_end" && child.bookmarkId === bookmarkId) {
578
+ break;
579
+ }
580
+ if (inside) {
581
+ if (child.type === "text") parts.push(child.text);
582
+ else if (child.type === "tab") parts.push("\t");
583
+ else if (child.type === "hard_break") parts.push("\n");
584
+ }
585
+ }
586
+ // If no bookmark boundaries found in this paragraph, return full paragraph text
587
+ if (!inside) {
588
+ return flattenParagraphInlineText(paragraph.children);
589
+ }
590
+ return parts.join("");
591
+ }
592
+
197
593
  // ─── Internal helpers ─────────────────────────────────────────────────────────
198
594
 
199
595
  function extractComplexFieldsFromParagraph(