Skip to content

feat(page-reference): resolve PAGEREF fields to live target page numbers (SD-3007)#3632

Merged
harbournick merged 20 commits into
mainfrom
luccas/sd-3007-feature-page-references
Jun 5, 2026
Merged

feat(page-reference): resolve PAGEREF fields to live target page numbers (SD-3007)#3632
harbournick merged 20 commits into
mainfrom
luccas/sd-3007-feature-page-references

Conversation

@luccas-harbour
Copy link
Copy Markdown
Contributor

Summary

Wires PAGEREF cross-reference fields through to dynamic resolution against the paginated layout. Previously a PAGEREF rendered only its baked field-result text; now it displays the target bookmark's actual page number, honoring the field's formatting switches and relative-position behavior, and updates as pagination changes.

This builds on top of luccas/sd-3029-feature-section-page-numbering and reuses its page-number formatting primitives.

What changed

Instruction parsing (super-converter)

  • New shared parsePageRefInstruction parser (field-references/shared/pageref-instruction.js)
    tokenizes a PAGEREF instruction into typed switches:
    • \h — hyperlink
    • \p — relative position ("above"/"below"/"on page N")
    • \* — general format (roman, alphabetic, CHARFORMAT/MERGEFORMAT, …)
    • \# — numeric picture
    • bookmark id
  • Results are stored as typed node attrs on the PageReference node (instructionTokens, bookmarkId, hasHyperlinkSwitch, hasRelativePositionSwitch, pageNumberFieldFormat, numericPictureFormat, fieldResultFormat, fieldRunProperties).
  • The first instrText run's rPr is captured to support CHARFORMAT field run properties.

Anchor resolution (contracts)

  • New buildPageRefAnchorMap locates each bookmark target within the resolved layout, mapping a bookmark name → PageRefLocation (page + display metadata). It resolves via fragment PM ranges with paragraph/table run-range fallbacks, and tolerates bookmark start/end marker lead distance (MAX_BOOKMARK_MARKER_LEAD_DISTANCE). Handles list items, table cells, and split rows/lines.

Resolve-time text (layout-resolved)

  • resolveLayout now resolves PAGEREF run text: formats the target display number (numeric picture / general format), emits relative-position text, and bumps the paint cache version when the resolved page changes so repaints stay correct.
  • New resolvePageRefText helper centralizes the run-text resolution.
  • Body page-token resolution is gated behind the SD_BODY_PAGE_TOKENS flag.

Numeric picture formatting (contracts)

  • New formatIntegerWithNumericPicture implements the Word \# picture subset: 0/# placeholders, grouping (,), sign slots (+/-), fractional digits, and multi-section selection (positive;negative;zero). Unsupported ECMA features (backtick numbered-item refs, localized separators, fractional rounding) are explicitly documented as out of scope.

Export fidelity (translator)

  • pageReference-translator preserves instruction tokens for lossless export and applies captured fieldRunProperties for CHARFORMAT fields via the w:rPr translator.

Presentation bridge

  • PresentationEditor exposes bookmark/anchor data needed for resolution.

Testing

  • New/updated unit tests across page-ref-anchor, page-number-formatting, resolveLayout, pageref-instruction, pageReference-translator, page-reference converter, layout-adapter, and PresentationEditor (≈2,600 lines added, heavily test-weighted).

@luccas-harbour luccas-harbour requested a review from a team as a code owner June 4, 2026 01:31
@linear-code
Copy link
Copy Markdown

linear-code Bot commented Jun 4, 2026

SD-3007

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 596be63d13

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Base automatically changed from luccas/sd-3349-bug-numbering-issues to main June 4, 2026 03:41
@luccas-harbour luccas-harbour force-pushed the luccas/sd-3007-feature-page-references branch from 596be63 to 4cec711 Compare June 4, 2026 12:53
@codecov-commenter
Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Wire PAGEREF field references through to dynamic resolution against the
paginated layout, so cross-references display the target's actual page
number, format, and relative position.

- Parse PAGEREF instructions into typed switches (\h, \p, \* general
  format, \# numeric picture, CHARFORMAT/MERGEFORMAT) in a shared
  pageref-instruction parser; store results as typed node attrs.
- Add buildPageRefAnchorMap to locate bookmark targets within the
  resolved layout (fragment PM ranges, with paragraph/table run-range
  fallbacks) and expose target display page metadata.
- Resolve PAGEREF run text in resolveLayout: format the target display
  number via numeric picture / general format, emit relative-position
  text ("on page N", "above"/"below"), and bump the paint cache version
  when the resolved page changes.
- Add formatIntegerWithNumericPicture for the Word \# picture subset
  (placeholders, grouping, sign slots, fractional, section selection).
- Preserve instruction tokens for lossless export and capture the first
  instrText run rPr for CHARFORMAT field run properties.
- Gate body page-token resolution behind SD_BODY_PAGE_TOKENS.
@luccas-harbour luccas-harbour force-pushed the luccas/sd-3007-feature-page-references branch from cb47b0b to 3bf5fa6 Compare June 5, 2026 13:46
…-3018) (#3636)

* feat(seq-fields): add shared SEQ instruction parser

Add a shared SEQ instruction parser for later import, layout, API, rebuild, and F9 paths. The parser preserves raw instruction text, normalizes only field dispatch, handles quoted and unquoted arguments, parses SEQ-specific switches, records unknown switches, and reuses the existing page-number general-format mapping instead of copying format tables.

Parser tests cover the Phase 1 required cases plus pair-reviewer fixes for raw instruction preservation, shared keyword dispatch, and quoted-only unescaping.

* feat(seq-fields): import SEQ fields case-insensitively

Route SEQ field preprocessing case-insensitively and add a v2 sequenceField importer before passthrough so synthetic sd:sequenceField nodes become PM sequenceField nodes instead of being dropped.

Reuse the shared SEQ instruction parser in the sequence field translator, carry parsed import attrs onto the PM node, mark imported cached results stale, and keep raw instruction export behavior unchanged.

Add focused preprocessing/import/translator tests covering uppercase and lowercase complex and fldSimple SEQ fields plus cached result preservation.

* feat(seq-fields): add shared SEQ evaluator

Add a pure SequenceFieldEvaluator next to the shared SEQ parser so layout, API, and update paths can share counter semantics without importing editor or rendering internals.

The evaluator owns per-identifier counters, heading serial tracking for \s resets, explicit \r reset precedence, conservative field-argument fallback behavior, hidden-result handling, and shared contract-based number formatting. Add focused coverage for the required Phase 3 numbering, reset, repeat-current, hidden, formatting, empty-identifier, field-argument, and initial-counter cases.

* feat(seq-fields): resolve SEQ display during layout

Add SEQ token metadata to TextRun and emit sequence-field layout tokens without relying on a fake zero placeholder.

Resolve SEQ display in a post-assembly toFlowBlocks pass using the shared SequenceFieldEvaluator so paragraph, table, list-compatible, and cache-hit blocks are renumbered in document order before layout measurement.

Cover numbering modes, formatting, heading-level restarts, story isolation, table traversal, and FlowBlockCache renumbering with focused layout-adapter tests.

* feat(seq-fields): recompute SEQ fields for API updates

Add a shared transaction helper that recomputes body SEQ fields in ProseMirror state using the shared parser/evaluator and style-aware heading resolution from the layout adapter when converter style data is available.

Wire raw field insertion, field rebuild, caption insertion/configuration, and F9 updates through the helper while preserving existing TOC and document-stat dispatch behavior. Field discovery now reads sequenceField.resolvedNumber as the resolved display text.

Cover updater scopes, caption/field wrapper recomputation, field resolver readback, and F9 SEQ refresh behavior with focused tests.

* fix(seq-fields): export current SEQ results

Update sequenceField export so current evaluated resolvedNumber values are authoritative, including empty current results for hidden fields. Preserve imported cached child content when results are not current, with a fallback to non-current resolvedNumber only when no cached child content exists.

Add export-routing tests for current result runs, hidden empty output, cached-content preservation, resolvedNumber fallback, and raw instructionTokens preservation. Add PM-updater coverage documenting Phase 7 conservative field-argument behavior: cached text wins, no-cache references repeat the previous counter, and counters do not advance.

* fix(seq-fields): parse attached restart switches

Handle Word-emitted SEQ switches such as \r0 and \s1 by normalizing attached numeric values through the existing restart parser path.

This fixes the NDA browser-test case where hidden level reset fields imported with restartNumber null, causing the first visible level2 SEQ field to render as 2 instead of 1.

Adds parser coverage for attached restart switches and a layout regression for hidden restart-zero fields seeding the next visible value.

* fix(seq-fields): recompute F9 after TOC state changes

Build the stat/SEQ update transaction from the current editor state after TOC updates dispatch their own transactions. This preserves TOC edits and shifted SEQ positions when F9 updates both TOC and SEQ fields.

* fix(seq-fields): detect lowercase caption SEQ fallback

Use the shared case-insensitive SEQ instruction check when caption discovery falls back to sequenceField nodes. This keeps imported lowercase seq captions discoverable by the API.

* fix(seq-fields): restore legacy format default

Keep the sequenceField schema default at ARABIC for backward compatibility while the shared parser continues to default parsed instructions to Arabic.

* fix(seq-fields): preserve F9 SEQ selection across TOC edits

Remember whether the original F9 selection contained a SEQ field before TOC updates dispatch their own transactions. This lets the fresh post-TOC transaction recompute SEQ fields even when TOC edits shift the selected field position.

* refactor(seq-fields): share parsed attr projection

Add sequenceFieldAttrsFromParsed beside the SEQ parser and use it from import, raw field insertion, caption insertion/configuration, and PM recompute. This keeps parsed instruction attrs and null/default normalization in one place.

* fix(converter): parse attached SEQ format switches

* fix(measuring): skip empty text runs during paragraph measurement

Empty text runs were flowing into the segment/space accounting, where a
trailing run boundary could be counted as a justification space and an
oversized empty run's font size could inflate the visible line height.
Short-circuit empty runs after recording font state so they no longer
produce phantom spaces, segments, or height.

* feat(numpages): apply field-switch formatting to total page count fields (SD-3327) (#3637)

* feat(numpages): add numeric picture field metadata

Extend the shared page-number field format contract with ordinal and numericPicture metadata for later NUMPAGES parser/formatter steps.

Add the hidden total-page-number PM attr, expose it on the typed node attrs, and thread it through the layout adapter format mapper with focused coverage.

Widen the layout engine page-number state annotation to the shared PageNumberFormat type so the expanded contract remains compile-compatible.

* feat(numpages): preserve numeric picture switches

Extend parsePageNumberFieldSwitches so Ordinal general switches map to the new ordinal page-number format and non-empty non-zero numeric pictures are retained in pageNumberNumericPicture instead of being discarded.

Keep all-zero numeric pictures on the existing zero-padding path for backwards compatibility, and parse switch arguments from the uncollapsed instruction text so quoted picture literals keep their internal whitespace.

* feat(numpages): format ordinal and picture counts

Extend the shared page-number formatter with English ordinal output and numeric-picture dispatch for preserved NUMPAGES switches.

Numeric pictures now take precedence over enum formats and zero padding, while ordinal and existing page-number formats continue through the shared enum formatter. Focused contracts tests cover ordinal suffix rules, numeric-picture dispatch, and page-number normalization.

* fix(numpages): format rebuild and shape results

Route shape/textbox NUMPAGES through the existing simple pageNumberFormat enum path, matching the SECTIONPAGES branch without adding shape numeric-picture or zero-padding support.

Format fields.rebuild total-page-number output with formatPageNumberFieldValue using preserved pageNumberFormat, pageNumberZeroPadding, and pageNumberNumericPicture attrs, and cover rebuilt resolvedText/text content for enum and numeric-picture cases.

* fix(numpages): preserve inserted field switches

Parse raw NUMPAGES instructions during fields.insert and pass the resulting page-number attrs into total-page-number creation.

This preserves numeric picture and general format switches for header/footer NUMPAGES insertion without changing the existing body-insertion restriction.

* test(numpages): cover switched field evaluation

Add focused coverage for complex and fldSimple NUMPAGES imports, numeric-picture PM/export round-trip, live total-page-count formatting, and shape NUMPAGES formatting. Also thread numeric-picture attrs through the existing export formatter and align the single-block totalPageCount resolver with the formatted runtime path so the new tests exercise the intended behavior.

* fix(numpages): preserve F9 field formatting

Format total-page-number refreshes in FieldUpdate with the same preserved page-number metadata used by rebuild/export paths. Adds regression coverage for numeric-picture NUMPAGES updates.

* fix(numpages): expose preserved field instructions

Prefer stored total-page-number instructions during field discovery so fields.list/get report switched NUMPAGES instructions preserved by insert/import.

* fix(numpages): format legacy SVG shape totals

Apply simple pageNumberFormat handling to NUMPAGES in the legacy SVG text helper, matching the DomPainter shape path and existing PAGE/SECTIONPAGES behavior.

* fix(numpages): preserve inserted picture whitespace

Parse NUMPAGES insert instructions from the original raw instruction so quoted numeric-picture literals keep significant internal whitespace.

* fix(numpages): format edit-mode total pages

Apply preserved NUMPAGES formatting in header/footer edit-mode NodeViews and cached DOM refreshes so switched totals match layout/export behavior.

* fix(numpages): preserve split header field pictures

Join header/footer instrText fragments verbatim so split quoted NUMPAGES numeric pictures do not gain synthetic spaces before parsing.

* fix(numpages): preserve quoted picture instructions

Keep significant whitespace inside quoted NUMPAGES numeric-picture instructions while still normalizing field-code whitespace outside quotes.

* refactor(numpages): share field format attrs mapper

Route NUMPAGES formatting call sites through the existing getPageNumberFieldFormat helper and make zeroPadding handling consistent.

* test(numpages): cover ordinal and split switch edges

Add regression coverage for no-space split instrText switches, ordinal shape NUMPAGES rendering, and three-digit teen ordinal suffixes.

* fix(converter): preserve split page field switch args
…olver

Validate the raw numbering format against the supported
SectionPageNumberingFormat values before mapping a section range to a
section domain, falling back to undefined for unrecognized formats.
Return undefined when no page numbering fields are present so empty
numbering objects don't shadow the parsed page numbering.
@luccas-harbour luccas-harbour enabled auto-merge (squash) June 5, 2026 15:02
@harbournick harbournick self-assigned this Jun 5, 2026
Copy link
Copy Markdown
Collaborator

@harbournick harbournick left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@harbournick harbournick disabled auto-merge June 5, 2026 17:50
@harbournick harbournick merged commit d97ada7 into main Jun 5, 2026
67 of 69 checks passed
@harbournick harbournick deleted the luccas/sd-3007-feature-page-references branch June 5, 2026 17:50
@superdoc-bot
Copy link
Copy Markdown
Contributor

superdoc-bot Bot commented Jun 5, 2026

🎉 This PR is included in superdoc-cli v0.16.0

The release is available on GitHub release

@superdoc-bot
Copy link
Copy Markdown
Contributor

superdoc-bot Bot commented Jun 5, 2026

🎉 This PR is included in superdoc-sdk v1.15.0

@superdoc-bot
Copy link
Copy Markdown
Contributor

superdoc-bot Bot commented Jun 5, 2026

🎉 This PR is included in @superdoc-dev/mcp v0.11.0

The release is available on GitHub release

@superdoc-bot
Copy link
Copy Markdown
Contributor

superdoc-bot Bot commented Jun 5, 2026

🎉 This PR is included in superdoc v1.39.0

The release is available on GitHub release

@superdoc-bot
Copy link
Copy Markdown
Contributor

superdoc-bot Bot commented Jun 5, 2026

🎉 This PR is included in @superdoc-dev/react v1.10.0

The release is available on GitHub release

@superdoc-bot
Copy link
Copy Markdown
Contributor

superdoc-bot Bot commented Jun 6, 2026

🎉 This PR is included in vscode-ext v2.11.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants