From 125c80463aee1987beee82b257cd8c09fe0090c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 13:20:25 +0000 Subject: [PATCH] fix(read): read inline content controls (checkboxes, text fields) as paragraph text A run-level was skipped by the reader, so a Word form's checkbox glyph and any Plain Text / Dropdown field value vanished from read, find and wc (#58). Inline is now a run-bearing wrapper: the reader and every XML offset walker descend its , a split half keeps the control (sdtPr minus w:id), and the --text diff rebuilds kept text inside the control. A checkbox toggled under tracking stays one checkboxToggle revision. The transparent-wrappers fixture gains a checkbox + text field. Fixes #58 Triage-Routine: true Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LkctEPkr8mq92sCK3ERfG3 --- REFERENCE.md | 7 +- src/cli/track-changes/CLAUDE.md | 2 +- src/cli/track-changes/list-view.ts | 6 +- src/core/CLAUDE.md | 2 +- src/core/ast/CLAUDE.md | 2 +- src/core/ast/read.ts | 94 +++++++-- src/core/parser/run-ops.ts | 39 +++- src/core/task-list/CLAUDE.md | 10 +- .../track-changes/preserve-formatting.tsx | 19 +- tests/cli/edit.test.ts | 19 +- tests/cli/invariants.test.ts | 196 ++++++++++++++---- tests/fixtures/setup/transparent-wrappers.ts | 31 +++ tests/fixtures/transparent-wrappers.docx | Bin 6295 -> 6476 bytes 13 files changed, 345 insertions(+), 82 deletions(-) diff --git a/REFERENCE.md b/REFERENCE.md index abad4e6..48dabb7 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -127,7 +127,12 @@ size="…in" margins="…in" text-width="…in" -->` note when the page deviates data-bound regions) are transparent: the paragraphs and tables inside one read as ordinary `pN`/`tN` blocks and edits land inside the control, with a `content-control="Governing Law"` pair on the block's note so you know Word may - have locked it. + have locked it. An INLINE control (a form's checkbox, a Plain Text or Dropdown + field inside a paragraph) reads as its text in that paragraph — a checkbox as its + `☐`/`☒` glyph — so `find`/`replace`/`comments add` reach it, and a `--text` + rewrite that restates the text keeps it inside the control. `docx tasks + check`/`uncheck` toggle a task-list item's box; a checkbox elsewhere has no + toggle verb yet, and replacing its glyph changes only what is displayed. - **Images** trail a `` note: `size` always (the `![](hash)` alone doesn't say "6in wide"), and `float`/`wrap`/`align`/`overflow` only when they deviate (an inline, in-bounds diff --git a/src/cli/track-changes/CLAUDE.md b/src/cli/track-changes/CLAUDE.md index f4f8cb0..f39c801 100644 --- a/src/cli/track-changes/CLAUDE.md +++ b/src/cli/track-changes/CLAUDE.md @@ -33,7 +33,7 @@ Footnote/endnote trackings span two parts. **Empirically validated against Micro **Header/footer revisions** (a reviewer's edit inside `word/header{N}.xml`/`footer{N}.xml` — Word keeps it in that part) register after the notes (`readMarginalTrackedChanges`): run-level ``/``/``/`` only, with `blockId` = the marginal's `hdrN`/`ftrN` (the first reference, when one part serves several sections — registered once). The walk reaches every paragraph in the part — inside block-level `` (Word's page-number gallery), tables, and text boxes — and descends an `` through its chosen branch only, so a text box's Choice/Fallback twin isn't listed twice. Paragraph-mark and property revisions (`pPrChange`/`rPrChange`) in a marginal aren't registered. Accept/reject mutate the part tree in place and `MarginalsView.writeTo` saves it. Registration goes through the same `registerTrackedChange` as the body (one id-minting site), and an equation through `registerMathRevisions`, so Word's per-math-run markers in a note or marginal are ONE revision, exactly as in the body. `list` reads a note or marginal wrapper's text off its own runs (`wrapperRecordText` in [list-view.ts](list-view.ts) — text, plus the `[line break]`/`[tab]`/`[drawing]`/`$…$` tokens `recordText` uses for AST runs, so a deleted header break doesn't read as "¶ paragraph mark"), and `Marginal.text` (`headers list`) reads the accepted view. Each `Marginal` also lists its part's pending revisions (`Marginal.trackedChanges`, collected through the walk's `RevisionScope.registered` sink), which the `docx:header`/`docx:footer` hint names as `pending="tcN …"` in every view; under `--baseline`/`--current` the hint's text comes from `Marginals.text(marginal, view, mark)` (core/marginals), which reads the part in that view and lets `read` wrap each revision in CriticMarkup. Because a note's `""` and a marginal's `hdrN`/`ftrN` name a whole part, not a paragraph, `revisionGroups` pairs a del with an ins there only when they share a container — edits in two header lines stay two decisions. -**Checkbox toggles** in `` content controls surface as the `checkboxToggle` kind. **Empirically validated against Microsoft Word for Mac**: when the user clicks a checkbox under tracking, Word emits an `` (new glyph ☒ or ☐) and `` (old glyph) pair INSIDE ``, and flips the `w14:checked` attribute in place — no `` element exists. The detection + accept/reject live in [src/core/task-list/](../../core/task-list/); the AST reader's `detectTaskListState` calls `findCheckboxToggle` and registers the `checkboxToggle` `tcN` into `document.trackedChangeReferences` (the single source apply reads back). Accept (`applyToggle`) keeps the ins glyph and drops the del; reject (`revertToggle`) drops the ins, unwraps the del, AND flips `w14:checked` back, inferring the prior value from the kept glyph (☐ → "0", ☒ → "1"). Structural inserts/deletes of whole checkboxes (Word wraps the SDT in ``) survive in the XmlNode tree on round-trip but aren't enumerated as a dedicated kind yet; `track-changes accept --all` won't honor them. +**Checkbox toggles** in `` content controls surface as the `checkboxToggle` kind. **Empirically validated against Microsoft Word for Mac**: when the user clicks a checkbox under tracking, Word emits an `` (new glyph ☒ or ☐) and `` (old glyph) pair INSIDE ``, and flips the `w14:checked` attribute in place — no `` element exists. The detection + accept/reject live in [src/core/task-list/](../../core/task-list/); the AST reader calls `findCheckboxToggle` — `detectTaskListState` for a task item's leading box, `walkInlineContentControl` for any other inline checkbox (#58) — and registers the `checkboxToggle` `tcN` into `document.trackedChangeReferences` (the single source apply reads back; `list` takes the kind from there, since the inline box's glyph runs carry the id in the `ins`/`del` roles). Accept (`applyToggle`) keeps the ins glyph and drops the del; reject (`revertToggle`) drops the ins, unwraps the del, AND flips `w14:checked` back, inferring the prior value from the kept glyph (☐ → "0", ☒ → "1"). Structural inserts/deletes of whole checkboxes (Word wraps the SDT in ``) survive in the XmlNode tree on round-trip but aren't enumerated as a dedicated kind yet; `track-changes accept --all` won't honor them. `` IS modeled (the paragraph analog of `sectPrChange`): every PARAGRAPH-property edit — `edit … --style/--alignment/--space-*/--line-spacing/--indent-*/--first-line/--hanging/--tabs`, on `insert` too — snapshots the prior `` into a `` (its last child) under tracking, so accept drops the marker (keeping the new props) and reject restores the prior pPr. This holds whether the props are set ALONE (`Edit.paragraphProperties` → `wrapPprChange` before `applyParagraphOptionsInPlace`) OR ride along with a content edit: the preserve path (`applyFormattingPreservingEdit` in `core/track-changes/replace.tsx`) `wrapPprChange`s the live pPr before mutating it; the non-preserve path (`Edit.paragraph`, fresh-built paragraph) `injectPprChange`s the OLD pPr snapshot onto the new pPr (since `wrapPprChange` snapshots a node's CURRENT children, already the new props there). `wrapPprChange` (in `core/blocks.tsx`) mirrors `wrapSectPrChange`. **Empirically validated against Microsoft Word for Mac** — Word emits one `` per paragraph snapshotting the prior pPr for ANY property change, and Word's accept of our output matches our own. **The snapshot EXCLUDES an inline ``**: CT_PPrChange's inner pPr is CT_PPrBase, which forbids sectPr (cloning it = Word "unreadable content" + a duplicated section break); a section change is tracked separately via ``. Reject reuses the generic `restorePropertySnapshot(node, parent, "w:pPr", ["w:sectPr"])` — the snapshot's inner `` is the prior pPr (sans sectPr) and `parent` is `pPr.children`, so the replace is wholesale EXCEPT the live `` is carried forward (else reject would drop the section break). `list` enriches it with `prior`/`current` paragraph-property summaries like `sectPrChange`. diff --git a/src/cli/track-changes/list-view.ts b/src/cli/track-changes/list-view.ts index dfc4e4a..d581c1b 100644 --- a/src/cli/track-changes/list-view.ts +++ b/src/cli/track-changes/list-view.ts @@ -58,9 +58,13 @@ export function collectTrackedChangeRecords( // Explicit fields, not a spread: `TrackedChange.within` (the enclosing // wrapper chain of a nested revision) is an AST/view concern and stays // off the `list` record so its shape is the same for every change. + // A checkbox toggle's glyph runs ride its id in the ins/del ROLES (so + // every view shows the right glyph); the revision's own kind is the + // reader's `checkboxToggle` entry. byId.set(change.id, { id: change.id, - kind: change.kind, + kind: + document.trackedChangeReferences.get(change.id)?.kind ?? change.kind, author: change.author, date: change.date, revisionId: change.revisionId, diff --git a/src/core/CLAUDE.md b/src/core/CLAUDE.md index 0877d2c..864e932 100644 --- a/src/core/CLAUDE.md +++ b/src/core/CLAUDE.md @@ -16,7 +16,7 @@ The typed AST from `read` is a *view* over the parsed XML tree. Mutations operat ## RUN_BEARING_WRAPPER_TAGS — the AST↔XML offset bridge -Defined in [parser/run-ops.ts](parser/run-ops.ts). AST text and `find`'s offsets descend into every tag in this set; the XML-side walkers in [comments/markers.tsx](comments/markers.tsx), [find/replace-span.tsx](find/replace-span.tsx), and [hyperlinks/wrap.tsx](hyperlinks/wrap.tsx) all do the same via `isRunBearingWrapper(tag)` / `sumRunBearingTextLength(children)`. They must stay in sync — if the AST descends into a wrapper the XML walkers don't (or vice versa), `find → replace` / `find → comments add` misaligns by the wrapper's inner-text length. Current set: ``, ``, ``, ``, ``, ``, ``, ``. **A walker reaches a wrapper's runs through `wrapperContent(node)` / `wrapperContentNode(node)`, never `node.children`** — for `` that is the chosen branch (first Choice, else Fallback; the SAME node the reader walked), for everything else the node itself. A split-off half goes back through `rewrapSplitHalf(wrapper, inner)`: a plain wrapper keeps its tag on both halves, an AlternateContent can't be halved into two Choice/Fallback pairs so its runs come back BARE (the content Word rendered anyway). Any tag NOT in the set is preserved by the catchall `push(child)` in every walker (see `tests/cli/invariants.test.ts`). +Defined in [parser/run-ops.ts](parser/run-ops.ts). AST text and `find`'s offsets descend into every tag in this set; the XML-side walkers in [comments/markers.tsx](comments/markers.tsx), [find/replace-span.tsx](find/replace-span.tsx), and [hyperlinks/wrap.tsx](hyperlinks/wrap.tsx) all do the same via `isRunBearingWrapper(tag)` / `sumRunBearingTextLength(children)`. They must stay in sync — if the AST descends into a wrapper the XML walkers don't (or vice versa), `find → replace` / `find → comments add` misaligns by the wrapper's inner-text length. Current set: ``, ``, ``, ``, ``, ``, ``, ``, and an inline `` content control. **A walker reaches a wrapper's runs through `wrapperContent(node)` / `wrapperContentNode(node)`, never `node.children`** — for `` that is the chosen branch (first Choice, else Fallback; the SAME node the reader walked), for `` its ``, for everything else the node itself. A split-off half goes back through `rewrapSplitHalf(wrapper, inner)`: a plain wrapper keeps its tag on both halves, an `` half keeps its `` (minus the must-be-unique ``) around a fresh ``, an AlternateContent can't be halved into two Choice/Fallback pairs so its runs come back BARE (the content Word rendered anyway). Any tag NOT in the set is preserved by the catchall `push(child)` in every walker (see `tests/cli/invariants.test.ts`). ## Markup compatibility (`mc:AlternateContent`) and text boxes diff --git a/src/core/ast/CLAUDE.md b/src/core/ast/CLAUDE.md index 15438fa..befa88c 100644 --- a/src/core/ast/CLAUDE.md +++ b/src/core/ast/CLAUDE.md @@ -23,7 +23,7 @@ 2. **Build the AST and Body's maps** — `walkRunContainer` descends ``, building `Paragraph.runs` (TextRun / ImageRun / EquationRun / …) and writing `blockReferences` / `imageById` / `hyperlinkById` / `equationReferences` as it goes. 3. **Register every tracked change into `Document.trackedChangeReferences`** — run-level wrappers (``/``/``/``), paragraph-mark wrappers in `` (both top-level AND cell paragraphs), ``, table-structural revisions (`rowIns`/`rowDel`/`cellIns`/`cellDel`/`tblGridChange`/`tblPrChange`/`tcPrChange`), and `checkboxToggle` SDTs. After the body walk, `readNoteTrackedChanges` appends standalone footnote/endnote edits (paired notes — those with a reference-side wrapper in the body — are hidden so the change surfaces as one tcN). -**Block-level `` (Word content controls) are TRANSPARENT to the block walk.** `collectBlocks` descends into `` and reads the ``/`` inside as ordinary blocks — same shared `pN`/`tN`/`sN` counters (so ids stay sequential in document order across the boundary), and each `BlockReference.parent` is the sdtContent's own child array, so an `edit`/`insert`/`delete` splices INSIDE the control. Without this an entire control — a clause, a form field, a data-bound region — is absent from the AST: `read` can't show it, `wc` can't count it, and a `read → create` rebuild silently drops it, while the bytes sit happily on disk. (Our raw gate already refuses to WRITE a block-level `` for exactly that reason; inbound Word files carry them regardless.) Each such block carries `contentControl` (`alias`/`tag`) so `read` can still say "you're editing inside a control" — Word may LOCK one against edit or deletion, so a change that succeeds here can be refused in the UI. **RUN-level `` stays skipped** by `walkRunContainer`: descending there would surface nested ``/`` as run-level `tcN` ids with no sensible accept/reject scope, and the checkbox shape has its own recognizer ([core/task-list](../task-list/CLAUDE.md)). +**Block-level `` (Word content controls) are TRANSPARENT to the block walk.** `collectBlocks` descends into `` and reads the ``/`` inside as ordinary blocks — same shared `pN`/`tN`/`sN` counters (so ids stay sequential in document order across the boundary), and each `BlockReference.parent` is the sdtContent's own child array, so an `edit`/`insert`/`delete` splices INSIDE the control. Without this an entire control — a clause, a form field, a data-bound region — is absent from the AST: `read` can't show it, `wc` can't count it, and a `read → create` rebuild silently drops it, while the bytes sit happily on disk. (Our raw gate already refuses to WRITE a block-level `` for exactly that reason; inbound Word files carry them regardless.) Each such block carries `contentControl` (`alias`/`tag`) so `read` can still say "you're editing inside a control" — Word may LOCK one against edit or deletion, so a change that succeeds here can be refused in the UI. **RUN-level `` is a transparent run-bearing wrapper too** (#58 — skipping it hid every form checkbox and Plain Text field value from `read`/`find`/`wc`): `walkInlineContentControl` descends its `` (the node `wrapperContent` hands the XML offset walkers), so a revision inside registers a `tcN` whose `parent` is the sdtContent's child list and accept/reject splice there. One exception keeps a checkbox honest: a box Word clicked under tracking (`findCheckboxToggle` — ins/del glyph pair + flipped `w14:checked`) registers ONE `checkboxToggle` `tcN`, and its two glyph runs ride that id in the `ins`/`del` roles so every view shows the right glyph (`track-changes list` reads the kind off the reference). A task-list item's LEADING checkbox never reaches the walk — `detectTaskListState` skips it and `read` prints `- [ ]`/`- [x]` ([core/task-list](../task-list/CLAUDE.md)). A split half of a control (`rewrapSplitHalf`) keeps its `` minus ``, and the `--text` diff rebuilds kept text inside the control (`keptWrapper` in `track-changes/preserve-formatting.tsx`). **`` is transparent at every level too** (see [core/CLAUDE.md](../CLAUDE.md#markup-compatibility-mcalternatecontent-and-text-boxes)): block-level wrappers walk their chosen branch with the branch's child list as `parent` (like ``); paragraph-level ones re-enter `walkRunContainer` with the branch as the container; run-level ones (Word's shape/text-box shape) are flattened inside `readRun`. **Text boxes** — any `` under a ``/`` — become a `TextBoxRun` on the anchor paragraph (`readTextBoxes`): each story is walked by `collectScopedBlocks` under a fresh `tbxN` prefix (global document order, `WalkState.textBoxIndex`), its paragraphs land in `blockReferences` with the `` child list as parent, and `Body.textBoxReferences` records the story node + `anchorBlockId` (`WalkState.currentBlockId`, saved/restored around the nested walk). Tracked changes inside a story register `tcN` ids in the same single walk. diff --git a/src/core/ast/read.ts b/src/core/ast/read.ts index 926b87c..67e253d 100644 --- a/src/core/ast/read.ts +++ b/src/core/ast/read.ts @@ -19,7 +19,7 @@ import { type NoteKind, noteConfig } from "../notes"; import { XmlNode } from "../parser"; import { RAW_MARKER_ATTRIBUTE } from "../raw/namespaces"; import { readSectionProperties } from "../sections"; -import { detectTaskListState } from "../task-list"; +import { detectTaskListState, findCheckboxToggle } from "../task-list"; import { readCellMargins } from "./cell-margins"; import type { Document } from "./document"; import { @@ -501,7 +501,8 @@ const MARGINAL_BLOCK_CONTAINERS = new Set([ * inside a standalone note or header/footer paragraph. blockId is "" for a * note (note bodies have no pN) and the `hdrN`/`ftrN` for a marginal. Skips `` (paragraph-mark trackings on a * standalone note don't occur — those only arise on paired deletes, which are - * hidden) and ``, mirroring the body's `walkRunContainer`. An + * hidden). An inline `` is descended like any container — its + * `` runs are the text `read` shows, as in the body. An * `` (a text box's shape) descends into its chosen branch * only: Choice and Fallback carry the same story, so walking both listed every * revision in it twice, and the save-time Choice→Fallback mirror would undo a @@ -514,7 +515,6 @@ function registerStandaloneRunChanges( ): void { for (const child of container.children) { if (child.tag === "w:pPr") continue; - if (child.tag === "w:sdt") continue; if ( child.tag === "w:ins" || child.tag === "w:del" || @@ -588,16 +588,7 @@ function readParagraph( paragraph, node, (sdt, parent) => { - // Register a checkboxToggle reference at the current walk position. - // This is the only walk: `apply`/`list` read it back from - // `document.trackedChangeReferences`, so a toggle's tcN is fixed here. - const tcId = `tc${state.trackedChangeIndex++}`; - document.trackedChangeReferences.set(tcId, { - node: sdt, - parent, - blockId: id, - kind: "checkboxToggle", - }); + registerCheckboxToggle({ document, state, blockId: id }, sdt, parent); }, ); @@ -649,15 +640,21 @@ function walkRunContainer( for (const child of container.children) { if (child.tag === "w:pPr") continue; if (context.skipNodes.has(child)) continue; - // Skip ALL `` content control bodies, not just leading checkbox - // SDTs (which `detectTaskListState` already pushed into `skipNodes`). - // Recursing into a Plain Text / Dropdown / Rich Text content control - // here would surface its nested ``/`` as run-level tcNs - // — and since this walk is the sole source of tcN ids, those phantom - // ids would then be addressable by `accept`/`reject` with no sensible - // scope. The structural-ins/del gap for SDTs is documented in - // `core/task-list/CLAUDE.md`. - if (child.tag === "w:sdt") continue; + // An INLINE content control (a form's checkbox, a Plain Text / Dropdown + // field) is a transparent wrapper: its `` runs are the + // paragraph's text, exactly as Word shows them. A task-list item's + // leading checkbox never gets here — `detectTaskListState` put it in + // `skipNodes` and `read` shows it as `- [ ]`/`- [x]`. + if (child.tag === "w:sdt") { + walkInlineContentControl( + context, + child, + container, + trackedChange, + hyperlink, + ); + continue; + } if (child.tag === "w:commentRangeStart") { const commentId = child.getAttribute("w:id"); @@ -803,6 +800,59 @@ function walkRunContainer( } } +/** Descend an inline ``'s `` (the node `wrapperContent` + * hands every XML offset walker, so the two sides count the same runs). A + * checkbox Word clicked under tracking holds an ``(new glyph) + + * ``(old glyph) pair AND a flipped `w14:checked`: that is ONE + * `checkboxToggle` revision (accept/reject keep glyph and attribute in step), + * so it registers once and its two glyph runs ride that id in the ins/del + * view roles instead of minting a stray `tcN` per half. */ +function walkInlineContentControl( + context: WalkContext, + control: XmlNode, + container: XmlNode, + trackedChange: TrackedChange | undefined, + hyperlink: Hyperlink | undefined, +): void { + const content = control.findChild("w:sdtContent"); + if (!content) return; + const toggle = findCheckboxToggle(control); + if (!toggle) { + walkRunContainer(context, content, trackedChange, hyperlink); + return; + } + const id = registerCheckboxToggle(context, control, container.children); + // Word stamps the toggle's author/date on the glyph pair, not the control. + const change: TrackedChange = { + id, + kind: "checkboxToggle", + author: toggle.ins.getAttribute("w:author") ?? "", + date: toggle.ins.getAttribute("w:date") ?? "", + revisionId: toggle.ins.getAttribute("w:id") ?? "", + }; + walkRunContainer(context, toggle.ins, { ...change, kind: "ins" }, hyperlink); + walkRunContainer(context, toggle.del, { ...change, kind: "del" }, hyperlink); +} + +/** Register a `checkboxToggle` revision for a checkbox `` at the + * current walk position — from a task item's leading box or any other inline + * one. This is the only walk: `apply`/`list` read it back from + * `document.trackedChangeReferences`, so a toggle's tcN is fixed here. */ +function registerCheckboxToggle( + scope: RevisionScope, + sdt: XmlNode, + parent: XmlNode[], +): string { + const id = `tc${scope.state.trackedChangeIndex++}`; + scope.document.trackedChangeReferences.set(id, { + node: sdt, + parent, + blockId: scope.blockId, + kind: "checkboxToggle", + }); + return id; +} + /** Mint the next `tcN` for a revision marker and record where it lives in * `document.trackedChangeReferences` — the one place ids are assigned. A marker * nested inside another wrapper (Word's `…` for a deletion inside diff --git a/src/core/parser/run-ops.ts b/src/core/parser/run-ops.ts index eda357c..bb9a33a 100644 --- a/src/core/parser/run-ops.ts +++ b/src/core/parser/run-ops.ts @@ -167,6 +167,10 @@ export const TRACKED_CHANGE_WRAPPER_TAGS: ReadonlySet = new Set([ * `` — never the union, so every walker reaches a wrapper's * runs through `wrapperContent(node)` rather than `node.children`; that is * what keeps a multi-Choice wrapper counted exactly as the reader reads it. + * - `w:sdt`: an INLINE content control (a form's checkbox, a Plain Text / + * Dropdown / Date field). Its runs live in ``, which is what + * `wrapperContent` returns — `` is the control's identity, never + * text. */ export const RUN_BEARING_WRAPPER_TAGS: ReadonlySet = new Set([ ...TRACKED_CHANGE_WRAPPER_TAGS, @@ -174,6 +178,7 @@ export const RUN_BEARING_WRAPPER_TAGS: ReadonlySet = new Set([ "w:fldSimple", "w:smartTag", "mc:AlternateContent", + "w:sdt", ]); export function isRunBearingWrapper(tag: string): boolean { @@ -181,10 +186,13 @@ export function isRunBearingWrapper(tag: string): boolean { } /** The node whose child list holds a run-bearing wrapper's runs: the wrapper - * itself, or for `` its chosen branch (the SAME - * `XmlNode` the reader walked, so an in-place splice lands where the AST - * looked). Every offset walker descends through this, never `node.children`. */ + * itself, for `` its chosen branch, for an inline + * `` its `` (the SAME `XmlNode` the reader walked, so an + * in-place splice lands where the AST looked). Every offset walker descends + * through this, never `node.children`. */ export function wrapperContentNode(wrapper: XmlNode): XmlNode { + if (wrapper.tag === "w:sdt") + return wrapper.findChild("w:sdtContent") ?? wrapper; if (!isAlternateContent(wrapper)) return wrapper; return alternateContentBranch(wrapper) ?? wrapper; } @@ -197,15 +205,38 @@ export function wrapperContent(wrapper: XmlNode): XmlNode[] { * and attributes on both halves. An `` can't be halved * (each half would need its own Choice/Fallback pair, and only the chosen * branch was ever read) — its runs come back BARE, which is the content Word - * rendered anyway. Empty input yields nothing. */ + * rendered anyway. An inline `` half keeps the control: its properties + * (minus the ``, which must stay unique — Word re-mints a missing one) + * around a fresh ``. Empty input yields nothing. */ export function rewrapSplitHalf(wrapper: XmlNode, inner: XmlNode[]): XmlNode[] { if (inner.length === 0) return []; if (isAlternateContent(wrapper)) return inner; + if (wrapper.tag === "w:sdt") return [contentControlHalf(wrapper, inner)]; const half = new XmlNode(wrapper.tag, { ...wrapper.attributes }); half.children = inner; return [half]; } +function contentControlHalf(control: XmlNode, inner: XmlNode[]): XmlNode { + const half = new XmlNode(control.tag, { ...control.attributes }); + for (const child of control.children) { + if (child.tag === "w:sdtContent") { + const content = new XmlNode(child.tag, { ...child.attributes }); + content.children = inner; + half.children.push(content); + continue; + } + const copy = child.clone(); + if (copy.tag === "w:sdtPr") { + copy.children = copy.children.filter( + (property) => property.tag !== "w:id", + ); + } + half.children.push(copy); + } + return half; +} + /** Sum the offset widths of everything reachable from `children` — each * ``'s text and each equation's `read` token — descending transparently * through every run-bearing wrapper. The `current`-view XML-side counterpart diff --git a/src/core/task-list/CLAUDE.md b/src/core/task-list/CLAUDE.md index ace4043..629114f 100644 --- a/src/core/task-list/CLAUDE.md +++ b/src/core/task-list/CLAUDE.md @@ -38,9 +38,13 @@ When the user toggles a `` under track-changes, Word emits an ``/`` inside an inline control from minting phantom -`tcN` ids. +`Paragraph.contentControl`. A run-level checkbox that is NOT a task item's +leading box (a form's Yes/No box, a box mid-paragraph or in a cell) is read by +`walkRunContainer` as a transparent wrapper: its glyph is paragraph text, and a +tracked click on it still registers one `checkboxToggle` via +`findCheckboxToggle` (see [core/ast](../ast/CLAUDE.md)). No verb toggles one yet +— `flipCheckbox*` target the paragraph's FIRST ``, which only a task item +guarantees is the box. ## Structural inserts/deletes — known gap diff --git a/src/core/track-changes/preserve-formatting.tsx b/src/core/track-changes/preserve-formatting.tsx index 0cbcfc6..f9eab02 100644 --- a/src/core/track-changes/preserve-formatting.tsx +++ b/src/core/track-changes/preserve-formatting.tsx @@ -77,9 +77,10 @@ export type OldToken = { * * Caller (`applyFormattingPreservingEdit`) must strip all run-bearing * wrappers from the rebuild — their content was just flattened into the - * diff. The ONE wrapper that comes back is ``: each token - * remembers the link it sat in, and the run builders re-wrap contiguous - * link-bearing tokens in a clone of it (see `segmentByLink`). */ + * diff. The wrappers that come back are `` and an inline + * content control (`keptWrapper`): each token remembers the one it sat in, + * and the run builders re-wrap contiguous tokens in a clone of it (see + * `segmentByLink`). */ export function extractOldTokens(paragraph: XmlNode): OldToken[] { let fullText = ""; const charToRpr: Array = []; @@ -118,7 +119,7 @@ export function extractOldTokens(paragraph: XmlNode): OldToken[] { // rebuild then dropped that text with no ``, so a tracked // `--text` edit lost it for good on reject. if (isAcceptedViewVisibleWrapper(child.tag)) { - walk(wrapperContent(child), child.tag === "w:hyperlink" ? child : link); + walk(wrapperContent(child), keptWrapper(child, link)); } // else: , bookmarks, comment markers, / // — skipped. Tracked-deleted text is invisible in accepted view. @@ -153,6 +154,16 @@ export function extractOldTokens(paragraph: XmlNode): OldToken[] { return tokens; } +/** The wrapper a token rebuilds INSIDE: a ``, or an inline + * content control (`` — a form's checkbox or text field) not already + * inside a link. Kept text stays in the control, so retyping a checkbox's + * label keeps the box clickable instead of flattening it to a literal glyph. */ +function keptWrapper(child: XmlNode, outer: XmlNode | null): XmlNode | null { + if (child.tag === "w:hyperlink") return child; + if (child.tag === "w:sdt" && outer === null) return child; + return outer; +} + /** The value covering the MOST characters of `values[start, start+length)`, * bucketed by `keyOf` (ties → first seen; insertion order is char order). */ function dominantBy( diff --git a/tests/cli/edit.test.ts b/tests/cli/edit.test.ts index ed2c93f..3a0db69 100644 --- a/tests/cli/edit.test.ts +++ b/tests/cli/edit.test.ts @@ -9,6 +9,7 @@ import { expectValidClean, freshFixture, readDocumentXml, + readMarkdown, trackedKinds, wordTextBoxParagraphXml, } from "./helpers"; @@ -4327,25 +4328,35 @@ describe("whole-paragraph edit over other authors' pending changes (#17)", () => expect(result.stderr).toContain("--at pN:START-END"); }); - test("revisions the edit keeps don't warn: a content control's toggle, a tracked replace's surviving deletion", async () => { + test("a content control's pending toggle is paragraph text: an untracked rewrite resolves it, warns, and keeps the box", async () => { + // Since #58 the box reads as its glyph, so a whole-paragraph rewrite + // covers it like any other pending text (the #17 contract) — and the + // control itself rides the --text diff instead of flattening to a glyph. const checkbox = await buildRawDoc( `☐☒ Buy milk`, "pending-sdt", ); + expect(await readMarkdown(checkbox)).toContain("☒ Buy milk "); const toggled = await runCli( "edit", checkbox, "--at", "p0", "--text", - "Buy bread", + "☒ Buy bread", "--author", "Editor", ); expect(toggled.exitCode).toBe(0); - expect(await readDocumentXml(checkbox)).toContain('w:author="Reviewer A"'); - expect(toggled.stderr).not.toContain("warning"); + expect(toggled.stderr).toContain( + "warning: p0 had pending tracked changes by Reviewer A", + ); + expect(await readDocumentXml(checkbox)).toMatch( + /<\/w14:checkbox><\/w:sdtPr>]*>☒<\/w:t><\/w:r><\/w:sdtContent><\/w:sdt>]*> Buy bread<\/w:t>/, + ); + }); + test("revisions the edit keeps don't warn: a tracked replace's surviving deletion", async () => { const deletion = await buildRawDoc( `Fees any due.`, "pending-kept-del", diff --git a/tests/cli/invariants.test.ts b/tests/cli/invariants.test.ts index b29e294..87549b3 100644 --- a/tests/cli/invariants.test.ts +++ b/tests/cli/invariants.test.ts @@ -8,6 +8,7 @@ import JSZip from "jszip"; import { runCli, tempWorkspace } from "./harness"; import { buildRawDoc, + expectValidClean, freshFixture, readDocumentXml, readMarkdown, @@ -172,58 +173,55 @@ describe("preserve unknown elements — invariant tests", () => { expect(xml).toContain(" { + test("a tracked change inside an inline content control lists, accepts, and leaves the control intact", async () => { // Word emits `` for non-checkbox content controls too — Plain - // Text, Rich Text, Dropdown, etc. — and a tracked edit inside one - // shows up as ``/`` inside ``. The AST - // reader and the apply walker MUST agree on whether to descend; if - // they disagree, `tcN` ids drift between `track-changes list` and - // `accept --at tcN`. Today neither walker descends, so the inner - // revision is invisible to track-changes commands AND survives the - // underlying XmlNode tree untouched. - const docPath = await buildFixture( + // Text, Rich Text, Dropdown, etc. — and a tracked edit inside one shows + // up as ``/`` inside ``. The reader descends + // the control (#58: its text is paragraph text), so the inner revision + // gets a `tcN` whose parent is `` — accept/reject splice + // there, and the control (with its ``) survives. + const control = (inner: string) => `` + - `` + - `` + - `` + - `` + - `` + - `` + + `` + + `` + + `` + + `` + + `` + + `${inner}` + + `` + + ``; + const docPath = await buildFixture( + control( `` + - `secret inside content control` + - `` + - `` + - `` + - ``, + `secret inside content control` + + ``, + ), "sdt-tracked", ); - const list = await runCli("track-changes", "list", docPath); - const changes = list.parsed as Array<{ id: string }>; - // The inner `` MUST NOT surface — neither walker descends into - // non-checkbox SDTs, so `track-changes list` shows zero entries. - expect(changes).toEqual([]); + const changes = (await runCli("track-changes", "list", docPath)) + .parsed as Array<{ id: string; kind: string; text: string }>; + expect(changes).toMatchObject([ + { id: "tc0", kind: "ins", text: "secret inside content control" }, + ]); + expect(await readMarkdown(docPath)).toContain( + "secret inside content control ", + ); - // Round-trip through a save (via `replace` on text in a sibling, but - // there is none here — use `insert` after p0 instead, which is enough - // to force `Document.save`). - await runCli( - "insert", + const accepted = await runCli( + "track-changes", + "accept", docPath, - "--after", - "p0", - "--text", - "unrelated paragraph", + "--at", + "tc0", ); - + expect(accepted.exitCode).toBe(0); const xml = await readDocumentXml(docPath); - // The whole SDT (including the inner ins) survives intact. - expect(xml).toContain(""); expect(xml).toContain(''); - expect(xml).toContain( - '', + expect(xml).toMatch( + /secret inside content control<\/w:t><\/w:r><\/w:sdtContent>/, ); - expect(xml).toContain("secret inside content control"); + expect(xml).not.toContain(" { @@ -1255,3 +1253,121 @@ describe("numeric character references (#12)", () => { expect(numbering).toContain(''); }); }); + +describe("inline content controls () are transparent run-bearing wrappers (#58)", () => { + // A Word form's checkbox: the glyph lives in ``, the label + // follows as an ordinary run. Before #58 the reader skipped every run-level + // ``, so the box (and any Plain Text control's value) vanished from + // `read`/`find` while the XML offset walkers stayed in lockstep with it. + const W14 = `xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"`; + const checkbox = (checked: "0" | "1", glyph: string) => + `` + + `` + + `${glyph}`; + const form = + `${checkbox("0", "☐")} Approved` + + `Name: ` + + `Jane Doe` + + `, Manager`; + + test("read shows the checkbox glyph and a plain-text control's value", async () => { + const docPath = await buildFixture(form, "sdt-inline-read"); + const markdown = await readMarkdown(docPath); + expect(markdown).toContain("☐ Approved "); + expect(markdown).toContain("Name: Jane Doe, Manager "); + }); + + test("find locates the glyph and text after the control at matching offsets", async () => { + const docPath = await buildFixture(form, "sdt-inline-find"); + const glyph = JSON.parse((await runCli("find", docPath, "☐")).stdout) as { + matches: { locator: string }[]; + }; + expect(glyph.matches.map((match) => match.locator)).toEqual(["p0:0-1"]); + const after = JSON.parse( + (await runCli("find", docPath, "Manager")).stdout, + ) as { matches: { locator: string }[] }; + expect(after.matches.map((match) => match.locator)).toEqual(["p1:16-23"]); + }); + + test("replace inside a control lands in ; the control survives", async () => { + const docPath = await buildFixture(form, "sdt-inline-replace"); + expect((await runCli("replace", docPath, "Doe", "Roe")).exitCode).toBe(0); + expect( + (await runCli("replace", docPath, "Manager", "Director")).exitCode, + ).toBe(0); + expect(await readMarkdown(docPath)).toContain( + "Name: Jane Roe, Director ", + ); + expect(await readDocumentXml(docPath)).toMatch( + /(?:(?!<\/w:sdtContent>).)*Roe(?:(?!<\/w:sdtContent>).)*<\/w:sdtContent>/, + ); + }); + + test("a replace straddling the control boundary keeps the control around its remaining text", async () => { + const docPath = await buildFixture(form, "sdt-inline-straddle"); + expect( + (await runCli("replace", docPath, "Name: Jane", "Who: Joan")).exitCode, + ).toBe(0); + expect(await readMarkdown(docPath)).toContain( + "Who: Joan Doe, Manager ", + ); + const xml = await readDocumentXml(docPath); + expect(xml).toMatch( + /<\/w:sdtPr>]*> Doe<\/w:t><\/w:r><\/w:sdtContent><\/w:sdt>/, + ); + }); + + test("comments add after the control anchors at the find offsets", async () => { + const docPath = await buildFixture(form, "sdt-inline-comment"); + const result = await runCli( + "comments", + "add", + docPath, + "--at", + "p1:16-23", + "--text", + "title?", + ); + expect(result.exitCode).toBe(0); + const listed = JSON.parse( + (await runCli("comments", "list", docPath)).stdout, + ) as { + anchor: { text?: string; startOffset: number; endOffset: number }; + }[]; + expect(listed[0]?.anchor).toMatchObject({ startOffset: 16, endOffset: 23 }); + }); + + test("fixture: the form's checkbox and text field read, and a replace in the field stays valid", async () => { + const docPath = await freshCopy("sdt-inline-fixture"); + expect(await readMarkdown(docPath)).toContain( + "☐ Approved by Jane Doe ", + ); + expect( + (await runCli("replace", docPath, "Jane Doe", "John Roe")).exitCode, + ).toBe(0); + expect(await readDocumentXml(docPath)).toMatch( + /.*.*John Roe.*<\/w:sdtContent>/, + ); + await expectValidClean(docPath); + }); + + test("a checkbox Word toggled under tracking is ONE checkboxToggle revision, shown in the accepted view", async () => { + const toggled = + `` + + `☒` + + `☐` + + ` Approved`; + const docPath = await buildFixture(toggled, "sdt-inline-toggle"); + expect(await readMarkdown(docPath)).toContain("☒ Approved "); + const listed = JSON.parse( + (await runCli("track-changes", "list", docPath, "--json")).stdout, + ) as { id: string; kind: string }[]; + expect(listed.map((change) => change.kind)).toEqual(["checkboxToggle"]); + expect( + (await runCli("track-changes", "reject", docPath, "--at", "tc0")) + .exitCode, + ).toBe(0); + expect(await readMarkdown(docPath)).toContain("☐ Approved "); + expect(await readDocumentXml(docPath)).toContain('w14:checked w14:val="0"'); + }); +}); diff --git a/tests/fixtures/setup/transparent-wrappers.ts b/tests/fixtures/setup/transparent-wrappers.ts index 9274340..b5c9d41 100644 --- a/tests/fixtures/setup/transparent-wrappers.ts +++ b/tests/fixtures/setup/transparent-wrappers.ts @@ -25,9 +25,14 @@ import { * historically invisible to the XML-side offset arithmetic in * comments/helpers.tsx, replace/replace-span.tsx, and hyperlinks/wrap.tsx. * + * Also an inline content-control pair (#58): a Word form's checkbox + * (``, glyph in ``) and a Plain Text field — a + * read-only shape we don't author, so it stays hand-rolled. + * * Layout: * p0: "Today is " + "2026-05-05" + "." * p1: "Hello " + "Alice" + "." + * p2: "☐" + " Approved by " + "Jane Doe" */ const root = resolve(import.meta.dir, "../../.."); @@ -48,6 +53,32 @@ const body = ` . + + + + + + + + + + + + ☐ + + + Approved by + + + + + + + + Jane Doe + + + `; const zip = new JSZip(); diff --git a/tests/fixtures/transparent-wrappers.docx b/tests/fixtures/transparent-wrappers.docx index 57cecb5445b672b1a8c437162fa5d7e87f17a26d..42fb4878c6bb50d2a73493e3fe889762b6af7583 100644 GIT binary patch delta 779 zcmV+m1N8itG0ZZs@&XD4-#=M)0ssK+29x{(7=M-9ZW=KVhVT0nmM?k-URDXJwqa9L znjWN7kwWi!V{8Lfe5!2@`xd?I^W{l8dx8a;h6Ew++MfA5^Ly;Qy54Gq*1`vA%?J+D?;S=VQp2gTMvQPF0=~}QTx~LL*-8r&5fDtsHY2=@(Pe}LwiKF% zzJGPXz}(z=O(S&uf^4kk&RZrzfCaQ7X_5?yrqbXB3vs>d8HEaB;%al6f2K zJoX`!CbtR$z(Mj1@O3<`_JGTm0n!t|Fn@@bAubyP356D0j5N!>E{yebrho(~A&3f9 zU{orGb12@K5wOY2wlbe9elN9Cz|5ox z5$YCA#?w#e=Lhum*UHBC1^jxqw>{45KHe{tr%5{OC719&z>*HPW8FVCa%YA9MSmz| zkK+zdr*TRb5cbN;5ng$dH8S^hGM81H)iT!(kuKm&Z8D)mc}7O~4sHx=#am*`AOHM5*@I31WGC|fiU*AyToY?hbyl3z(9s@IC2454sqyob zmWSJy)?-m@BY9S!n17>2pou*#sDC8W)=&@(kTtzN<7EG(%KrjTO9KQ70F%c86tnIG zvk(de-#=M)0ssK+29v85PXdVrll&Do0?G5HUa|&leQK;0&fVD z^%gq;_meRfJ_02RlW`Y70r-=$7e4|$4U_X1Hv(o2lg$hllSLO0lT#QP0yGqpZx|v5 JWfcGb00326RsH|~ delta 600 zcmV-e0;m1VGM6#1@&XE#YE1^g0RRB11e5#%7=M&aZ`&{ohVT0of)2Yma)Krpyx3iV zY}gJR3M{?tqR6x(R9}p=k|6f=ue+OPbR9`bjJD2tG(_ayp--lz!+a@s+l*TtuGo0V2H8cZZeFd=Jmx{uLij0Ld=&BM$(Flei+ z*MB_X($}oDzI5IS2mu3V#TIG0Vwy`sCyc)YW2;IE*h~UOhzG?ZCK2}1g#%50l!nIr zGelfM(cC{YE)iBc)UlIF#%^F8Fs-`;Q+nQ>l;&l@Hly)KoL{|SYAL)8wu&>9GUYa4 z5I9fY0Dg?8)e*3KA7JqcunO=##BxHg(0^%oqC|`AS8c54JB1`niJ&SnfJt95T43|; zY}xg*>j&QtLmy|sae=#>hXDQ&XtA{=?}!X!&CsXl$HBc)kinbaYM^% zl-+ol)5e=@Ds%E&=Dv%wvCQL!$ZI@PZ3YVZGm_IgyfLi#%{82+b)#^{x!6O*HxmjV z;+<#1hw=Zg<1JJC2a~}98ndGXvk(fEYE1^g0RRB11e0JEPXg2gld%>z0{sM&&IKNm z2p1{=CzCT5HUdrtlWP|}0=fs2suw#7LJ0r>cW-iJFLRSI7#ouc7#ad_3X?$#7Lz;} mDgi^2XBa;Mhzygc7&ij343ps)K>~jhlO!1;2Cx(W0000NHV