Skip to content

feat(viewer): headless mode and a controller for host-drawn controls - #8

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

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

Conversation

@mkroemer

Copy link
Copy Markdown
Contributor

Builds on #7 (components), #6 (UI texts), #5 (icons) and #4 (theming). It also carries three commits that move the document, sheet and slide views onto the strings table from #6 (feat(docx|xlsx|pptx): … read their texts from the strings table), because the controller's outline and status use those texts. I can open those three as PRs of their own if you would rather review them apart. The headless part is the last commit.

This lets a host draw its own controls around the document: zoom, page, outline, Edit/Save, undo, in its own toolbar and side panel.

const ctl = createViewerController()

<MyToolbar controller={ctl} />
<DocViewer src={file} controller={ctl} headless />

function MyToolbar({ controller }) {
  const s = useViewerState(controller)
  return <>
    <button disabled={!s.canUndo} onClick={() => controller.undo()}>Undo</button>
    <button onClick={() => controller.zoomIn()}>{s.zoom && Math.round(s.zoom.effective * 100)} %</button>
  </>
}

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, no React inside) holds the state: kind, loading, editing, canEdit, dirty, saving, canUndo/canRedo, zoom, page, outline (headings, sheets or slides) and status. It runs the commands: setEditing, save, undo, redo, zoomIn/zoomOut/setZoom, goto, gotoPage, present, print, fileAction, toggleComments. The viewer and its view publish to it and register their commands. Without a controller from the host the viewer keeps its own, so nothing changes for existing users. When the viewer unmounts its part of the state is cleared, so a controller that outlives it shows no document.

Per kind:

  • DOCX: the headings are read for the controller whether or not the outline panel is open, with the current one. The heading jumped to stays current while its page is in view. Undo and redo are offered only while editing.
  • XLSX: the visible sheets are the outline. Undo and redo are counted per edit and cleared when a sheet is added, deleted, moved, renamed or imported, as the worker's history is. Switching sheets through the controller keeps a formula being typed open, for cross-sheet references, as the built-in tabs do.
  • PPTX: slides are titled by their title placeholder, read by a new title-only worker call (pptx.titles, no layout), and only while a host subscribes (observed, watchObserved), so the plain viewer does no extra work. Titles follow edits. Symbol-font characters in titles become their Unicode look-alikes.

Also: onLoad fires once per opened document, also with an inline callback; mount() returns the controller and <office-viewer headless> has .controller; the e2e harness takes PLAYWRIGHT_CHANNEL to use an installed browser.

Two follow-ups would build on this one: formatting state and commands through the controller (ViewerState.format, ctl.format(...), for a host's own formatting toolbar), and ready-made controls (ZoomBar, StatusText, OutlineList, SheetTabs, FormatBar) for hosts that want the engine's controls in their own layout.

test/controller.test.ts covers the state, commands, zoom steps and clearing; e2e/controller.spec.ts drives DOCX, XLSX and PPTX through the controller with no chrome mounted, including editing, saving and undo only while editing. bun run typecheck and bun test pass; the e2e suite runs in CI.

🤖 Generated with Claude Code

markus-kroemer and others added 7 commits November 14, 2026 21:59
…s props

The viewer's texts come from one typed table, `Strings` (src/react/strings/en.ts),
with a complete German table next to it (de.ts, Swiss spelling, Word / Excel /
PowerPoint terms). `DocViewer`, `mount()` and `<office-viewer>` take `locale`
('en' | 'de', default 'en') and `strings`, a partial table merged over the
locale key by key; `StringsProvider` / `useStrings()` give standalone views the
same texts. Numbers and dates in the UI go through Intl with the table's locale;
the English output is unchanged.

This change converts the top bar, the details rows, the common dialogs, the
zoom control, the shared toolbar controls, the source pane and the picture view.
The shared groups (`edit`, `find`, `table`, `format`) are in the table already,
so the document, sheet and slide views can be converted in separate changes.

A unit test checks that every locale has all keys of `en`, no empty text and no
sharp s in German.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
…xts from the strings table

The document view's status line, toolbar, context menu, outline, find bar, page setup and header / footer dialogs and the tracked-change tooltips take their texts from the docx, pageSetup and headerFooter groups. The Page 1 of 5 footer preset inserts its text in the UI's language. e2e/locale-docx.spec.ts checks the German texts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s from the strings table

The sheet view's status line, document details, sheet tabs, context menu, find options, print notice and the toolbar (number formats, borders, merge, alignment, rotation, rows, functions, sort, view) take their texts from the xlsx group. Number format previews stay as they are. e2e/locale-xlsx.spec.ts checks the German texts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…heir texts from the strings table

The slide view's toolbar, shape and slide menus, status line and present button, the comments panel and its notices, the File menu, the details dialog, the unsupported-file message and the collaboration chip take their texts from the pptx, comments, file and collab groups. The empty text box placeholder is a data-placeholder attribute shown through attr(), so it follows the locale. e2e/locale.spec.ts checks the German bar, File menu, details dialog and slide view, a partial override and the English default.

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>

@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, the controller is well shaped (no React inside, stable snapshot, StrictMode traced fine), and the three strings commits keep the English output identical.

Two things to fix before I merge:

  1. Detach is unconditional (src/react/controller.ts:199-208, the cleanup in useViewCommands, and src/react/DocViewer.tsx:554). Two viewers on one controller, for example a route change with an exit animation: when the old one unmounts it calls attachView(null) / attachViewer(null), which drops the new viewer's commands and resets the state. The new viewer never registers again, so the host's controls stay dead. Detaching only when the registered object is your own fixes it; a unit test for the two-viewer case would be good.
  2. XLSX undo / redo and canUndo are not gated on editing (src/react/xlsx/XlsxView.tsx:1176): edit a cell, setEditing(false), then ctl.undo() changes the workbook in view mode. #9 already gates it, so please move that part here.

Also, as written in #6, I'd rather have the three strings commits there.

Non-blocking:

  • fileAction gating is uneven: with fileMenu={false}, print() and fileAction('pdf') do nothing, while 'open', 'new:*' and 'import' run even with allowOpen={false} or on a read-only file.
  • update, attachView, attachViewer and watchObserved are public on the exported class. A narrower exported interface would keep them changeable.
  • The e2e app now always passes a controller, so the path without one has no e2e coverage any more.

@mkroemer

mkroemer commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Made controller cleanup ownership-safe: an old viewer unmounting no longer detaches the newer viewer or clears its state, with regression coverage.
  • Gated XLSX undo/redo and canUndo/canRedo on editing, so controller commands cannot change the workbook in view mode.

Also addressed all three non-blocking points:

  • File actions now enforce permissions independently of menu visibility. New/Open remain available for read-only files when allowOpen permits them; Import additionally requires editing permission. This behavior is documented.
  • Narrowed the exported ViewerController type to host-facing methods, hiding publishing and attachment internals.
  • Restored browser coverage without a host-supplied controller; controller-specific tests explicitly opt in.

I also fixed subscription lifecycle handling and mount().update({ controller }), which previously ignored a replacement controller.

Verification: 561 unit tests, typecheck, library/SDK builds, package checks, and the full CI browser suite pass. Current main is merged.

The three strings commits are now included in #6.

Follow-up in 5880873: fixed #20 so delayed XLSX edit responses publish history through the current mounted viewer/document and current editability. They no longer revive detached-controller history or re-enable undo/redo after leaving edit mode. Model/history processing still completes. Verification: 29 controller/XLSX browser tests (including five regressions), 86 focused unit tests and typecheck passed; current CI is green. This follow-up also passed independent review.

@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. Undo gating, the narrower exported type and the e2e path without a controller are done, and the async history guard does what it says for a detached or replaced view.

Still open (line numbers are at 5880873):

  1. Ownership, src/react/controller.ts:200 and :186. Release is owner-checked now, so "the new viewer attaches last, the old one unmounts" works. But attach is still last-wins, and update() is not owner-scoped. Both cases below are reproduced with a probe test:
    • V1 is still loading, V2 mounts on the same controller and loads first, then V1's document finishes and its view attaches, then V1 unmounts. The release sees its own view, sets view = null and clears zoom, page and outline. V2 never attaches again, so setZoom, goto and undo do nothing.
    • An overlapped switch from a docx (V1) to an xlsx (V2): V1 published zoom and page, the sheet never publishes those, and V1's release is a no-op because it is no longer the owner. The controller keeps zoom and page {3, 7} for a spreadsheet.
  2. src/react/DocViewer.tsx:376: docEditable now requires allowEdit. <DocViewer editable allowEdit={false}>, edit mode without the toggle, is an editor on main and view-only here, while editing stays true and Save still shows. allowEdit is documented as "Show Edit/View button", and that row is unchanged. Please keep the old meaning.
  3. DocViewer.tsx:476: canImport went from fileMenu && allowEdit && canEdit to allowOpen && allowEdit && canEdit, so allowOpen={false} now removes "Import CSV into new sheet" from the built-in File menu, although an import does not replace the document. Is that intended?
  4. controller.ts:128: the commands are prototype methods, while subscribe and snapshot are bound. <button onClick={ctl.undo}> or const { zoomIn } = ctl throws on this.view (reproduced). Bound properties match how hosts will write it.

Non-blocking:

  • src/react/xlsx/XlsxView.tsx:978: the guard covers the canUndo / canRedo publish, but viewer.setDirty(true) in the same continuation still goes through the old closure, so a late response marks the next document dirty. The spec "an unmounted view cannot publish its delayed history" asserts the history flags only. It may be simpler if run only changes store.history and one effect publishes from the current ctl.
  • controller.ts:136: setZoom forwards anything, so 0, NaN or 150 (a percent) reach the view. A clamp to the built-in 0.25-3 range would do.
  • src/react/file/FileMenu.tsx:134: rename and details lack the kind gate that save got. Called with no document open they latch, and the dialog opens by itself when a document loads.
  • ViewerController is a structural Pick<> now, and internalController() casts it blindly. A host mock or wrapper compiles and then fails at mount with ctl.update is not a function. A brand check with a clear error would help.
  • XLSX canUndo / canRedo are a count kept in the view. In a collab session undo goes through the session's own stack, so after a sheet rename the host's Undo button is disabled while Ctrl+Z still undoes.
  • XlsxView.tsx:388: goto keeps an open formula only if the host prevents mousedown, as the built-in tabs do. A plain button blurs the editor first, which commits =SUM(). The docs example should show it.
  • src/react/docx/DocxView.tsx:780: controller headings are recomputed 150 ms after every version bump whether or not anyone observes them; PPTX gates on ctl.observed.
  • src/core/pptx/parser.ts:165: a title with <a:br/> loses the break without a separator, so the outline shows Annual ReportQ3 Results.
  • The branch still carries the older copies of the three strings commits, which are in #6 now. See my note on #9 about the order of the stack.

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