Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
1c0faf0
feat(viewer): translatable UI texts: strings table, locale and string…
markus-kroemer Nov 14, 2026
5d98742
feat(viewer): replaceable UI components for toolbars and dialogs
markus-kroemer Nov 14, 2026
726bdb1
style(viewer): a space between JSX attributes
markus-kroemer Nov 14, 2026
b7155b9
feat(docx): toolbar, context menu, find bar and dialogs read their te…
markus-kroemer Nov 14, 2026
9b92736
feat(xlsx): toolbar, sheet tabs, grid menu and status read their text…
markus-kroemer Nov 14, 2026
b8fe558
feat(pptx): slides, comments, File menu and collaboration chip read t…
markus-kroemer Nov 14, 2026
9828fad
feat(viewer): headless mode and a controller for host-drawn controls
markus-kroemer Nov 14, 2026
88dde57
feat(viewer): formatting state and commands through the controller
markus-kroemer Nov 14, 2026
755bb6c
feat(docx): toolbar, context menu, find bar and dialogs read their te…
markus-kroemer Nov 14, 2026
1b959be
feat(xlsx): toolbar, sheet tabs, grid menu and status read their text…
markus-kroemer Nov 14, 2026
d92644e
feat(pptx): slides, comments, File menu and collaboration chip read t…
markus-kroemer Nov 14, 2026
5a058ff
Merge remote-tracking branch 'origin/main' into t3/audit-fix-localiza…
mkroemer Nov 17, 2026
c293268
Merge remote-tracking branch 'origin/main' into audit/ui-controller
mkroemer Nov 17, 2026
10f686d
Merge remote-tracking branch 'origin/main' into t3/fix-dialog-primitives
mkroemer Nov 17, 2026
8fa9681
fix(viewer): preserve dialog actions and host toolbar layout
mkroemer Nov 17, 2026
3d8d0af
fix(viewer): complete localization behavior and regression coverage
mkroemer Nov 17, 2026
781c239
fix(viewer): preserve controller ownership and enforce action permiss…
mkroemer Nov 17, 2026
acd8b16
feat(i18n): make German opt-in and localize drawing placeholders
mkroemer Nov 17, 2026
a08ab31
audit: integrate published PR9 with accepted PR8 without format behav…
mkroemer Nov 17, 2026
92f4e0b
Merge commit '8fa968133d049330d8fd32651f828de25c65e1b0' into audit/pr…
mkroemer Nov 17, 2026
a4fceab
audit: integrate accepted PR6 locale changes while retaining PR7 and …
mkroemer Nov 17, 2026
a47091e
audit: adapt PR9 format tests to accepted PR8 opt-in controller fixture
mkroemer Nov 17, 2026
5880873
fix(xlsx): guard async history publication (#20)
mkroemer Nov 17, 2026
81cd557
Fix controller formatting targets, ownership and size validation
mkroemer Nov 17, 2026
ec5e0d5
Merge PR8 async history fix into controller formatting
mkroemer Nov 17, 2026
71db05c
fix(viewer): validate converted font-size units before formatting
mkroemer Nov 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ Also online at [p10node.github.io/office-engine](https://p10node.github.io/offic
- **Comments**: threads with replies, resolve, edit / delete, @mentions; on DOCX text, XLSX cells and PPTX slides, stored in the file the way Word, Excel and PowerPoint store them
- **Real-time collaboration**: live edits, avatars, collaborators' cursors, offline edits sync on reconnect
- **Dark mode and theming**: `theme="dark"` or `"auto"` (follows the OS), or a theme object with design tokens for colors, type and shape ([Theming](docs/theming.md)); documents keep their own colors
- **Translatable UI**: every text of the bars, menus and dialogs from one typed table; only English bundled by default; German available through an optional import with `de-DE` formatting (see [UI texts](docs/api.md#ui-texts)); any text replaceable through `strings`
- **Embed anywhere**: React component, hook, vanilla `mount()`, `<office-viewer>` web component, single `<script>` file

Full list, format coverage and limitations: [Features](docs/features.md).
Expand Down
189 changes: 187 additions & 2 deletions docs/api.md

Large diffs are not rendered by default.

59 changes: 58 additions & 1 deletion docs/theming.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,66 @@ gives the class name and style their root needs:

```tsx
const root = useThemeRoot(theme)
return <div className={root.className} style={root.style}><XlsxView client={client} /></div>
return (
<OfficeUIProvider icons={icons} components={components} locale="de">
<div className={root.className} style={root.style}><XlsxView client={client} /></div>
</OfficeUIProvider>
)
```

`OfficeUIProvider` carries what `DocViewer` takes as `icons`, `components`, `locale` and `strings` to views mounted on
their own.

## Your own components

Where tokens are not enough, the toolbars and dialogs render the host's own components: a design system's buttons,
selects and dialogs instead of the built-in ones. Each one left out keeps the built-in one.

```tsx
import { DocViewer, type ButtonProps, type UIComponents } from '@p10node/office-engine'

// Define component types outside the host's render so toolbar controls stay mounted.
function ViewerButton({ title, icon, label, children, active, expanded, disabled, onClick, onMouseDown }: ButtonProps) {
return (
<MyIconButton tooltip={title} aria-label={title} pressed={active} aria-expanded={expanded}
disabled={disabled} onClick={onClick} onMouseDown={onMouseDown}>
{icon}{label}{children}
</MyIconButton>
)
}

function ViewerSeparator() {
return <MyDivider vertical />
}

const components: Partial<UIComponents> = { Button: ViewerButton, Separator: ViewerSeparator }

<DocViewer
src={file}
editable
components={components}
/>
```

| Component | Used for | Props |
|---|---|---|
| `Button` | every toolbar button, the toggles that open color, table and border pickers, the overflow button | `ButtonProps`: `title`, `icon` (resolved through `icons`), `iconName`, `label`, `children`, `active`, `expanded`, `disabled`, `wide`, `onClick`, `onMouseDown`, `className` (the built-in classes) |
| `Select` | font, size list, style, format and menu dropdowns | `SelectProps`: `title`, `options` (`DropOption`: `value`, `label`, `hint`, `icon`, `disabled`, `sep`, `head`, `style`), `value` (undefined for a command menu), `onChange`, `label`, `placeholder`, `width`, `menuWidth`, `disabled`, `alignRight` |
| `Separator` | between toolbar groups | none |
| `Dialog` | prompts (link, rename, …) and confirmations | `DialogProps`: `title`, `kind` (`'alert'` for a question), `children` (the body), `actions` (`label`, `onClick`, `extra` for an auxiliary action such as Remove link, `primary`, `submit`, `autoFocus`), `onSubmit` (the body is a form), `onClose` (Escape, backdrop) |
| `Toast` | short messages at the bottom | `text` (the viewer removes it after a few seconds) |

The document must keep the focus while a toolbar control is used, or the command loses its selection:

- `Button`: pass `onMouseDown` to the element. It prevents the default, which keeps the focus.
- `Select`: open on mouse down with the default prevented, and handle its keys without moving the focus into the list.
The built-in one captures the keys at the window while open.

The overflow menu measures each toolbar item from a wrapper of its own, so a host component needs no ref.

A host `Select` can render its trigger and option icons with the exported `Icon`: `<Icon name={option.icon} size={16} />`
(when `option.icon` is set). It uses the viewer's `icons` overrides and falls back to the built-in SVGs.

## Tokens

| Group | Tokens |
Expand Down
2 changes: 2 additions & 0 deletions e2e/app/embed.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
<div id="mounted" style="height: 420px"></div>
<script type="module">
import { mount } from '../../src/embed.ts'
import { de } from '../../src/locales/de.ts'
window.__german = de
window.__wcEvents = []
const wc = document.getElementById('wc')
wc.addEventListener('load', (e) => window.__wcEvents.push(e.detail))
Expand Down
70 changes: 68 additions & 2 deletions e2e/app/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,35 @@
* ?src=samples/sample.docx&editable=1&allowSave=0&onSave=1&items=1&close=1&collab=ws://…&room=r
* comments: &me=Ann&meId=u1 (author), &people=1 (mentions: Ann, Bob Stone, Cid), &comments=0 (hidden), &cmOpen=1
* &icons=1: every icon from a host resolver, as `<svg data-host-icon={name}>`
* texts: &locale=de-DE, &fileLabel=… (a partial `strings` override of the File menu's label)
* &components=1: the host's own Button, Separator, Dialog and Toast (`data-host-*` markers)
* &headless=1: the document alone; the viewer is driven through window.__ctl (its controller) either way
*/
import { useState } from 'react'
import { createRoot } from 'react-dom/client'
import { DocViewer, type DocViewerProps, type FileMenuItem } from '../../src'
import { createViewerController, DocViewer, type DocViewerProps, type FileMenuItem, type UIComponents, type ViewerController } from '../../src'
import { de } from '../../src/locales/de'

type Ev = { type: string; [k: string]: unknown }
declare global {
interface Window {
__events: Ev[]
__setProps: (p: Partial<DocViewerProps>) => void
__ctl: ViewerController
__overlap: (phase: number) => void
__setLanguage: (language: 'en' | 'de-DE') => void
__german: typeof de
}
}
window.__events = []
window.__ctl = createViewerController()
// a host reading the state, as the tests do through snapshot(): views read slide titles only for one
window.__ctl.subscribe(() => {})
const log = (e: Ev) => window.__events.push(e)

const q = new URLSearchParams(location.search)
const flag = (k: string) => (q.has(k) ? q.get(k) !== '0' : undefined)
const texts = q.get('locale') === 'de-DE' || q.get('locale') === 'de' ? de : undefined

async function b64(blob: Blob) {
const bytes = new Uint8Array(await blob.arrayBuffer())
Expand All @@ -33,6 +45,49 @@ const items: FileMenuItem[] = [
{ label: 'Version history', hint: 'beta', onClick: () => log({ type: 'item', label: 'Version history' }) },
]

// plain host components: no engine classes, so nothing of the engine's CSS styles them
const components: Partial<UIComponents> = {
Button: (p) => (
<button type="button" data-host-button="" data-active={p.active || undefined} title={p.title} aria-label={p.title} aria-expanded={p.expanded} disabled={p.disabled} onMouseDown={p.onMouseDown} onClick={p.onClick} style={p.iconName === 'more' ? { width: 140 } : undefined}>
{p.icon}
{p.label}
{p.children}
</button>
),
Separator: () => <i data-host-sep="" />,
Dialog: (p) => {
const actions = p.actions.map((a, i) => (
<button key={i} type={a.submit ? 'submit' : 'button'} data-primary={a.primary || undefined} autoFocus={a.autoFocus} onClick={a.onClick}>
{a.label}
</button>
))
const body = (
<>
<h2>{p.title}</h2>
{p.children}
{actions}
</>
)
return (
<div data-host-dialog="" role={p.kind === 'alert' ? 'alertdialog' : 'dialog'} aria-label={p.title} onKeyDown={(e) => e.key === 'Escape' && p.onClose()}>
{p.onSubmit ? (
<form
onSubmit={(e) => {
e.preventDefault()
p.onSubmit!()
}}
>
{body}
</form>
) : (
body
)}
</div>
)
},
Toast: ({ text }) => <output data-host-toast="">{text}</output>,
}

const initial: DocViewerProps = {
src: q.get('src'),
name: q.get('name') ?? undefined,
Expand All @@ -48,6 +103,10 @@ const initial: DocViewerProps = {
captureSelectAll: flag('captureSelectAll'),
theme: (q.get('theme') as DocViewerProps['theme']) ?? undefined,
injectStyles: flag('injectStyles'),
locale: (texts ? undefined : q.get('locale') as DocViewerProps['locale']) ?? undefined,
strings: q.has('fileLabel') ? { ...texts, file: { ...(texts?.file ?? {}), menu: q.get('fileLabel')! } } : texts,
headless: flag('headless'),
controller: flag('controller') ? window.__ctl : undefined,
onSave: q.has('onSave') ? async (blob, name) => void log({ type: 'save', name, b64: await b64(blob) }) : undefined,
onDirtyChange: (dirty) => log({ type: 'dirty', dirty }),
onRename: (name) => log({ type: 'rename', name }),
Expand All @@ -64,6 +123,7 @@ const initial: DocViewerProps = {
open: flag('cmOpen'),
onEvent: (e) => log({ type: 'comment', action: e.type, id: e.comment.id, text: e.comment.text, thread: e.thread.id, quote: e.quote, mentioned: e.mentioned.map((m) => m.id ?? m.name), participants: e.participants.map((m) => m.id ?? m.name) }),
},
components: q.has('components') ? components : undefined,
icons: q.has('icons')
? (name) => (
<svg data-host-icon={name} viewBox="0 0 24 24">
Expand All @@ -76,8 +136,14 @@ const initial: DocViewerProps = {

function App() {
const [props, setProps] = useState(initial)
const [phase, setPhase] = useState(0)
window.__overlap = setPhase
window.__setProps = (p) => setProps((cur) => ({ ...cur, ...p }))
return <DocViewer {...props} />
window.__setLanguage = (language) => setProps((cur) => ({ ...cur, strings: language === 'de-DE' ? de : undefined }))
return <>
{phase < 2 && <DocViewer key="old" {...props} />}
{phase > 0 && <DocViewer key="new" {...props} />}
</>
}

createRoot(document.getElementById('root')!).render(<App />)
92 changes: 92 additions & 0 deletions e2e/components.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { describe, expect, test } from 'bun:test'
import { docxParas, paraText, runsOf, useBrowser, viewer } from './harness'

useBrowser()

const open = async (viewport?: { width: number; height: number }) => {
const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true, components: true }, { viewport })
await v.page.locator('.de-ebar').waitFor()
return v
}

describe('host UI components', () => {
test('docx: every toolbar button is the host Button, and it keeps the selection for formatting', async () => {
const v = await open()
const counts = await v.page.evaluate(() => {
const bar = document.querySelector('.de-ebar')!
return {
host: bar.querySelectorAll('button[data-host-button]').length,
engine: bar.querySelectorAll('button.de-tb').length,
seps: bar.querySelectorAll('[data-host-sep]').length,
engineSeps: bar.querySelectorAll('.de-tb-sep').length,
}
})
expect(counts.host).toBeGreaterThan(10)
expect(counts.engine).toBe(0)
expect(counts.seps).toBeGreaterThan(0)
expect(counts.engineSeps).toBe(0)

await v.selectText('document')
await v.btn('Bold').click()
await v.page.waitForFunction(() => document.querySelector('button[data-host-button][aria-label^="Bold"]')?.hasAttribute('data-active'))
const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))!
expect(runsOf(p).find((r) => r.text.includes('document'))!.s.b).toBe(true)
expect(v.errors).toEqual([])
})

test('docx: a narrow toolbar still moves what does not fit under the host More button', async () => {
const v = await open({ width: 640, height: 900 })
const more = v.page.locator('.de-ebar button[data-host-button][aria-label="More tools"]')
await more.waitFor()
// Hosts can use a wide text button: reserve its actual width, not the engine's icon width.
await v.page.waitForFunction(() => {
const bar = document.querySelector('.de-ebar')!
const right = bar.getBoundingClientRect().right
return [...bar.querySelectorAll(':scope > span')].every((el) => el.getBoundingClientRect().right <= right)
}, null, { timeout: 5000 })
await more.click()
expect(await v.page.locator('.de-ebar-more button[data-host-button]').count()).toBeGreaterThan(0)
expect(v.errors).toEqual([])
})

test('docx: the link prompt is the host Dialog and submits', async () => {
const v = await open()
await v.selectText('document')
await v.page.keyboard.press('Control+k')
const dialog = v.page.locator('[data-host-dialog][role="dialog"]')
await dialog.waitFor()
expect(await v.page.locator('.de-dialog').count()).toBe(0)
await dialog.locator('input').fill('https://example.org/docs')
await v.page.keyboard.press('Enter')
await dialog.waitFor({ state: 'detached' })
const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))!
expect(runsOf(p).find((r) => r.text.includes('document'))!.href).toBe('https://example.org/docs')
expect(v.errors).toEqual([])
})

test('docx: the built-in edit-link prompt keeps Remove link on the left and removes the link', async () => {
const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true })
await v.selectText('document')
await v.page.keyboard.press('Control+k')
const dialog = v.page.locator('.de-dialog')
await dialog.locator('input').fill('https://example.org/docs')
await v.page.keyboard.press('Enter')
await dialog.waitFor({ state: 'detached' })
await v.selectText('document')
await v.page.keyboard.press('Control+k')
const extra = dialog.locator('button.de-dialog-extra')
await extra.waitFor()
expect(await extra.innerText()).toBe('Remove')
const bounds = await dialog.locator('.de-dialog-btns').evaluate((row) => {
const [extra, cancel] = row.querySelectorAll('button')
return { left: row.getBoundingClientRect().left, extra: extra.getBoundingClientRect().left, gap: cancel.getBoundingClientRect().left - extra.getBoundingClientRect().right }
})
expect(bounds.extra).toBe(bounds.left)
expect(bounds.gap).toBeGreaterThan(20)
await extra.click()
await dialog.waitFor({ state: 'detached' })
const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))!
expect(runsOf(p).find((r) => r.text.includes('document'))!.href).toBeUndefined()
expect(v.errors).toEqual([])
})
})
Loading
Loading