Skip to content

feat(viewer): formatting state and commands through the controller - #9

Open
mkroemer wants to merge 57 commits into
p10node:mainfrom
mkroemer:ui-controller-format
Open

mkroemer wants to merge 57 commits into
p10node:mainfrom
mkroemer:ui-controller-format

Conversation

@mkroemer

@mkroemer mkroemer commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

ViewerState.format exposes formatting at the active editor target, and ViewerController.format(command) applies a command from host controls across DOCX, XLSX and PPTX. The editor retains the intended target while a host button or input has focus, including through DOCX collaboration edits. Formatting preserves the host control's focus and selection.

The controller validates commands before editing. The font-size range matches the built-in size box. List commands set the requested style and accept null for removal. XLSX formatting uses the same cell-format derivation as its toolbar. The formatting API guide covers supported formats, list behavior and focus examples.

This layer follows #8 and includes v0.17.0. Tests exercise host controls, selection lifetimes and saved formatting, including the same saved selection on both DOCX collaboration peers.

DOCX keeps its input attached during host rerenders, so the selection update can clear the formatting target when focus leaves the editor. If an actual reattachment cancels a pending selection update, the shared input schedules it again. Tests cover both the cancelled frame and a host rerender during the selection event in the built viewer.

@pierreneter pierreneter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you. This one looks good to me: the mapping in src/react/edit/format.ts mirrors the built-in toolbars, and the tests round-trip DOCX and XLSX formatting.

No changes needed here. It sits on #8, so I'll merge it as soon as #8 is fixed.

Worth settling before a release, since they become API:

  • { op: 'list' } toggles although it reads as a setter, and there is no way to remove a list. list === undefined also means "this kind has no lists".
  • state.format goes null as soon as focus leaves the document, including into a host's own <input>, so the documented disabled={!f} pattern disables the field being typed in. The docs should say so, or the format should stay while the selection does.

@mkroemer

Copy link
Copy Markdown
Contributor Author
  • Kept valid DOCX/PPTX formatting targets while native host controls receive focus. Live formatting commands preserve the input's focus and text selection, so typing a font size no longer disables the field or stops after the first digit.
  • Made format publication and cleanup follow the same ownership as command registration. An older viewer, replaced controller or late callback cannot clear or overwrite its successor's formatting state.
  • Rejected non-finite/nonpositive sizes before mutation, including DOCX/PPTX values that overflow, round to zero or exceed safely represented integer units during conversion. Invalid commands leave model, history, dirty state and saved XML unchanged.
  • Documented the existing list toggle behavior: repeating the same kind removes it. The docs also explain mixed-selection behavior, unsupported commands, and null versus undefined.

Integrated the current #6–#8 changes, including the asynchronous XLSX history fix for #20. The inherited PPTX save race and DOCX conversion notification fix remain separate in #21 and #22.

Verification: 578 unit tests, 22 controller/formatting browser tests, typecheck and the full library build pass locally. An independent review and a fresh converted-size boundary recheck approved this candidate. The reviewer also checked model/history/dirty-state preservation and saved XML for the original overflow/underflow repros.

@pierreneter pierreneter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the follow-ups. I went through what this adds on top of #6-#8 at 71db05c. This is from reading the code, I have not run it, so please check me where it does not match what you see.

To fix first:

  1. src/react/xlsx/XlsxView.tsx:1207: the controller's format on a sheet goes through fmt() to fmtAt(), which always calls focusGrid() (:1190). With the docs' own example, <input type="number" onChange={(e) => ctl.format({ op: 'size', pt: e.currentTarget.valueAsNumber })}>: typing 14 applies 1pt on the 1 and moves focus to the grid, the 4 then starts a cell edit and overwrites the active cell, and Backspace clears the selected range. e2e/format-controls.spec.ts loops over docx and pptx only. A controller command should not move focus.
  2. src/react/edit/input.ts:375: detach() now also clears lastSel, formatTarget and formatControl. DocxView detaches and attaches again whenever the viewer context object changes identity (DocxView.tsx:277), which as far as I can tell happens when saving flips and with every new onSave / onError / onDirtyChange reference:
    • a host with an inline onSave and useViewerState(ctl) in one component: selecting text re-renders the host, the context changes, the target is wiped, and clicking the size input gives format: null again, which is the case from my last review;
    • with no controller at all: Ctrl+S, then Ctrl+K, type a URL, OK. setLink has no selection and inserts nothing. lastSel survived a re-attach before this PR.
  3. src/react/edit/format.ts:24: color and highlight take any string (the type says "CSS color"), but the writers only take hex through officeHex. ctl.format({ op: 'color', color: 'red' }) shows red and updates history and dirty, and the save then removes w:color (src/core/docx/writer.ts:127), which also loses the colour that was there before. Same for rgb(...) and for #ff0000ff from a picker with alpha. Either convert CSS colours or reject what cannot be written.
  4. format.ts:28 and :44: both chains end in a bare else ed.clearFormat(), so any op outside the known ones, from a plain-JS host or the web component ({ op: 'bold' }), clears the formatting. The docs say a command with no use does nothing.

API, before a release:

  1. { op: 'list' } still toggles. It is documented now, but there is no explicit removal, and a selection whose first paragraph is bulleted and second is not needs two calls. I'd still like list: null (or 'none'), so "make this a numbered list" can be said once and a repeated command does not flip the result.
  2. format.ts:79: sizes only have to be positive and finite, which is looser than the built-in box (1-400pt in half points, src/react/edit/Toolbar.tsx:490) and than the formats: pt: 0.5 writes sz="50" on a slide, pt: 1000 writes <sz val="1000"/> in a cell, where Excel stops at 409. test/controller.test.ts asserts that 0.25 and 1000 pass. Please use the same range as SizeBox, in one place.
  3. font is not validated at all. An empty name writes <w:rFonts w:ascii="" .../>, and a live text input applies A, Ar, Ari, ... as separate undo steps.

Non-blocking:

  • The command gate and the published state use formatSelection(), while applyDocx / applyPptx act on input.sel(). In a collab session a peer's edit rebases lastSel only, so the two can point at different paragraphs. Passing the published Sel into the command, with a do-not-refocus flag, would remove the focus heuristic in RichInput and fix 1 the same way.
  • XlsxView.tsx:1211 publishes format, canUndo and canRedo straight through viewer.ctl?.update(), without the ownership check that 81cd557 added for docx and pptx.
  • formatControl is cleared only by a selection inside the editor. After one command from a host input, ctl.undo() or ctl.goto() from another host button restores no caret.
  • Merge a4fceab re-adds toolbar.more (en.ts:143, de.ts:139), which #7 removed as unused. I found nothing else dropped or duplicated by the merges.
  • cellFormat repeats what XlsxToolbar.tsx:108-114 and toggle in XlsxView derive. The toolbar should read from it, so the two cannot disagree.
  • docs/api.md:134: the new format row is out of line with the table.

On the stack as a whole: this branch contains the heads of #6, #7 and #8, but those three do not merge one after another. #6 conflicts with #7 in 4 files and with #8 in 16 (#8 still has the older strings commits), and all of them conflict with main since v0.14.0 in docs/api.md, src/react/DocViewer.tsx and src/react/file/importFile.ts. Could you rebase them onto main as a linear stack, 6 → 7 → 8 → 9, so each one merges cleanly after the one before? #10 would then sit on top of this one.

mkroemer and others added 22 commits November 18, 2026 21:04
A host can render its own Button, Select, Separator, Dialog and Toast in the
engine's toolbars and dialogs (`components` prop, UIComponentsProvider), for
a design system's controls where design tokens are not enough. Each one left
out keeps the built-in one, whose markup is unchanged.

- every toolbar button goes through Button: Btn, the color, picker and
  overflow toggles, the font size steps; Dropdown/Select through Select
- PromptDialog and ConfirmDialog build their actions and body and render
  them through Dialog; Toast keeps its timer and renders through Toast
- OfficeUIProvider carries icons, components, locale and strings to views
  mounted without DocViewer
- the overflow button's title is its accessible name ("More tools"), so the
  unused "More" text goes
- docs/theming.md "Your own components"; unit tests for each component and
  nested providers; e2e with host components: toolbar, formatting keeps the
  selection, overflow at a narrow width, the link prompt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One formatting API for documents, cells and slide text, so a host can draw
its own formatting toolbar: `ViewerState.format` (a TextFormat: bold,
italic, underline, strike, font, size, color, highlight, align, list) and
`ViewerController.format(command)`.

- DocxEditor and PptxEditor publish their formatting state to subscribers
  (`subscribeState`) beside the toolbar's `onState`; a subscriber hears the
  current state at once, so a controller attached while text is selected
  reports its format without waiting for the selection to change
- src/react/edit/format.ts maps the editors' states and the active cell's
  CSS to TextFormat and commands to editor calls or cell format patches
- the format is null while viewing, and in a presentation unless text is
  being edited; a command a kind has no use for does nothing
- spreadsheet undo, redo and format commands through the controller run
  only while editing, and canUndo / canRedo follow the editing state
- docs: "Formatting" under headless mode; unit tests for the mappings;
  e2e: bold and size through the controller in a document (saved), bold
  and fill on a cell, and an undo while viewing that leaves the cell as is

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A host that draws its own controls around the document gets
`<DocViewer controller={createViewerController()} headless />`.
`headless` leaves the viewer with the document alone: no top bar, zoom
control, outline panel or button, sheet tabs, slide list or Present
button. While editing, the formatting toolbar keeps its row, and an
explicit `toolbar` brings back the top bar (File menu, comments, Save).

The controller (src/react/controller.ts, framework-free) holds the
state - kind, loading, editing, canEdit, dirty, saving, canUndo/canRedo,
zoom, page, outline (headings, sheets or slides), status - and runs the
commands: setEditing, save, undo, redo, zoomIn/zoomOut/setZoom, goto,
gotoPage, present, print, fileAction, toggleComments. The viewer and its
mounted view publish to it and register their commands; without one from
the host the viewer keeps its own, so nothing else changes. When the
viewer or its view unmounts, its part of the state is cleared, so a
controller that outlives it shows no document.
`useViewerState(ctl)` reads the state in React.

- DOCX: headings are read for the controller whether or not the outline
  panel is open (once edits rest), with the current one, which stays the
  heading jumped to while its page is in view; DocxEditor reports its
  undo/redo history after each step, offered only while editing.
- XLSX: the visible sheets as the outline; undo/redo counted per edit,
  cleared when a sheet is added, deleted, moved, renamed or imported, as
  the worker's history is. A sheet switched to through the controller
  keeps a formula being typed open, for cross-sheet references, as the
  built-in tabs do.
- PPTX: slides titled by their title placeholder, read by a title-only
  worker call (`pptx.titles`, no layout) only while a host subscribes
  (`observed`, `watchObserved`), and kept current as slides are edited;
  symbol-font characters in titles as their Unicode look-alikes. Undo and
  redo through the controller do nothing outside edit mode.
- `onLoad` fires once per opened document, also with an inline callback.
- mount() returns the controller; <office-viewer headless> has .controller.
- e2e harness: PLAYWRIGHT_CHANNEL picks an installed browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Transplants 3d6e879 onto the rebuilt PR8 scope. Retains PR6 public locale keys and main's decimal-comma behavior.
markus-kroemer and others added 7 commits November 19, 2026 11:26
The rich-text input keeps both upstream's pending caret (the caret an edit
asked for, which key presses go by until the view shows it, and the repair
of a caret whose paragraph moved to another page) and this branch's
formatting target for focused host controls: a formatting command's
selection comes first, then select-all, the pending caret and the DOM.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…closed

The column fit runs after the edit's result. When the viewer was given a
new document meanwhile, its worker calls failed with "Document closed",
uncaught. The client now tells that it is closed (`closed`), and the fit
does nothing more once it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ter it

RichInput follows the selection one animation frame after `selectionchange`.
A re-render that runs the editing effect again (detach, then attach of the same
root) before that frame cancelled it, and nothing read the selection again. A
controller update landing between a click on the page around the editor and
that frame left the published format, and the selection host commands apply
to, on the text the user had left: a later host format command edited it.

The next attach now reads the selection when a detach cancelled a pending one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mkroemer

Copy link
Copy Markdown
Contributor Author

Independent review: v0.17.0 integration of #6–#9

The four branches were fast-forwarded to merges of v0.17.0 main (5d0a782). A fix was then added on top of #9.

PR Head CI
#6 69171b3 both jobs green
#7 b66f919 both jobs green (the earlier red Typecheck, test, build is gone)
#8 b50e54d both jobs green
#9 75f13a6 (aeae3a4 + fix) running on 75f13a6 (both jobs were green on aeae3a4)

Verdict: the stack is ready to merge in order #6 → #7 → #8 → #9, once CI on 75f13a6 is green and the maintainer has reviewed it. The one defect found in the stack is fixed in #9 (below). The two other findings come from main and do not block this stack.

Integration checks

Fixed in #9: after clicking the page background, a host format command could still change the old selection

Symptom. The built docx: inline React host formatting… test (e2e/format-built.spec.ts:106) failed intermittently: 3/20 on the earlier #9 head 1086a4f, and 1/12 after the merge. When it got stuck, ctl.format({ op: 'toggle', mark: 'italic' }) with focus on the page background made the document dirty. The format went to text the user had moved away from. This was already in #9 before v0.17.

Cause.

  1. Clicking the page around the editor fires selectionchange, and RichInput schedules a requestAnimationFrame callback to follow it.
  2. A controller update (here, the debounced word count) re-renders the host before that callback runs.
  3. The re-render runs the editing effect again: detach(), then attach() on the same root.
  4. detach() cancels the pending callback, and nothing read the selection again.

Fix: 75f13a6. detach() now notes when it cancelled a pending selection read, and the next attach() reads the selection. Both the DOCX and PPTX editors use RichInput, so both are covered. The browser test is unchanged. A new unit test in test/input-reattach.test.ts fails without the fix.

Verification (Bun 1.4.4, macOS arm64, Chromium).

  • With the fix, the DOCX case passed 40 times out of 40.
  • An instrumented build hit the race in 15 of 40 runs, and recovered every time.
  • Typecheck is clean; unit tests 1248/1248.
  • The xlsx, format-built, collab, controller, format-controls, components, locale, ui and embed browser suites: 136/136.
  • The full test:e2e: 300/304. Of the four failures:

Other checks on the integrated stack

From main, not this stack (for separate follow-up)

@pierreneter pierreneter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, all seven points from my last review are fixed, and so are the non-blocking ones. I checked each at fef4db0: no grid focus from the controller, the target survives re-renders and Ctrl+S then Ctrl+K, hex-only colours, unknown ops are a no-op, setList with null, one fontSize() range, font validation, the published Sel in the command, and the toolbar reading cellFormat. In the VM, bun test (1248), typecheck, and the format-controls, format-built, controller and collab browser suites (57) all pass.

One more to fix before merge, confirmed with a probe browser test:

  1. src/react/edit/input.ts:511: while a host control has focus, formatSelection() returns formatTarget && lastSel and skips override.model. After Ctrl+A (selectAll()), lastSel holds only the DOM part, from the first to the last rendered [data-pa]. The published Sel and the command then cover only the pages that are mounted. Take a 601-paragraph DOCX, press Ctrl+A in the page, click the documented host <input>, run ctl.format({ op: 'size', pt: 30 }) and save: 25 of 600 paragraphs are 30 pt. With focus left in the document, the same command gives 600 of 600. this.formatTarget && (this.override?.model ?? this.lastSel) would fix it. The docs sentence that focused host controls keep the editor's logical target is only true once this is fixed.

Non-blocking:

  • src/react/xlsx/XlsxView.tsx:1642: the controller's format sends rect as it is. The toolbar's fmt (:1619-1620) widens a whole column, row or sheet to MAX_ROW / MAX_COL. In sample.xlsx, Ctrl+Space then size 30: the built-in box sets B2 and B72 to 30 and saves a <col … style>. ctl.format sets B2 but leaves B72 at 11, and saves no column style. The same widening without focusGrid() would make the two match.
  • XlsxView.tsx:1646 publishes format through viewer.ctl?.update(). That has the view-scope check but not the this.view === commands check that docx and pptx get through publishFormat, and format is not cleared when the sheet grid unmounts. I found no failing case, so this is only for consistency.

Once this and the sheet-rename texts on #6 are in, the stack is ready from my side, merged in the order #6 → #7 → #8 → #9.

mkroemer and others added 16 commits November 20, 2026 08:19
The column fit's closed-document guard is now on main (#34); main's wording of its comment stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…o outline in headless mode

- Spreadsheet edit results now carry the worker's own undo / redo count
  (`history`). An edit that changes nothing (sorting sorted rows) records
  no step, so counting results made the controller offer undo where there
  was none and drop a redo that was still there. The count stays as the
  fallback for results without it.
- The heading jumped to in a document stays current only until the caret
  goes somewhere else on that page.
- An outline panel open when the viewer turns headless is no longer shown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g jumps, headless outline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… as the toolbar does

A selection made by a row or column header (or of the whole sheet) is
formatted through the controller over its full extent, as the built-in
toolbar formats it, so cells typed there later have the format; before,
only the cells in use got it. The rows and columns are also fitted after
a wrap or number format, as from the toolbar. The grid does not take the
focus from the host's control.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- After select-all in a long document, a host control formats the whole
  document: the target is the select-all, not the paragraphs shown.
- An edit from a host's control (a list, alignment or clear button) keeps
  the focus there also when its converted paragraphs come back from the
  worker and put the caret back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The outline's slide titles are read once from the file; a title edited while that read runs is newer than its answer, which no longer overwrites it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e scan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…collaborators

- A host's format commands sent faster than the worker answers go by what
  the earlier ones left: two bold toggles cancel out instead of applying
  bold twice, and a toggle right after clear starts from the cleared
  marks.
- A select-all held while a host's control has the focus stays the whole
  document when a collaborator edits it, instead of shrinking to the
  pages that were shown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The format remembered for commands sent faster than the worker answers is dropped for good once the cell's own format has changed, and by undo and redo; an undo that brought back the format it was read from made it count again, so the next toggle did nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…l unanswered

The marks worked out for commands sent faster than the cell shows them are kept while any command is unanswered and until the cell shows those marks, instead of being dropped when the first answer changes the cell; a third quick toggle then starts from the second's result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A formatting command does nothing on a selection that spans a table, and
the sample document has one, so the case could not pass: select-all and
bold left the document as it was. It now replaces the sample with 151
plain paragraphs over several pages, checks that the far pages are not
rendered, and that every paragraph is bold after the host control.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A held select-all was dropped as soon as the DOM selection differed from
the one select-all set. The pages rendered around the caret change as
the view re-renders, which moves the DOM selection without the user, so
formatting with a host control then reached only the rendered pages.
It now holds until a click or a key press other than select-all itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ion"

This reverts commit f7c6096. A trace from CI showed the select-all was
not dropped by a selection change after a re-render, as that commit
assumed, but by restore(); the next commit fixes that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ect-all

An edit the worker reports after a select-all rebuilds its paragraph, and
the view then restores the selection around it. restore() dropped the
held select-all on any call, so a host control formatted only the pages
shown. A trace from CI showed this order. restore() now keeps the
select-all when it is handed the selection the select-all holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants