Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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; English by default, German shipped (`locale="de"`), 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
46 changes: 45 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { DocViewer } from '@p10node/office-engine'
<DocViewer src={file} allowSave={false} allowDownload={false} /> // no Save/Download, no image download
<DocViewer src={file} fileMenu={false} /> // no File menu
<DocViewer src={file} theme="dark" /> // dark chrome; "auto" follows the OS setting
<DocViewer src={file} locale="de" /> // German texts
```

### File menu
Expand Down Expand Up @@ -62,6 +63,8 @@ CSS is auto-injected, no import needed (or import `@p10node/office-engine/styles
| `styleTarget` | `Document \| ShadowRoot` | document | Where CSS is injected |
| `injectStyles` | `boolean` | `true` | Inject the stylesheet; false when the page loads `@p10node/office-engine/styles.css` itself |
| `theme` | `'light' \| 'dark' \| 'auto' \| ThemeOptions` | `'light'` | Color scheme of the chrome; `'auto'` follows `prefers-color-scheme`; an object adds token overrides ([Theming](theming.md)). Documents keep their own colors |
| `locale` | `'en' \| 'de'` | `'en'` | Language of the texts (bars, menus, dialogs, messages); numbers and dates follow it. See [UI texts](#ui-texts) |
| `strings` | `StringsOverride` | – | Texts replacing the locale's, key by key (a group may be given in part) |
| `editable` | `boolean` | `false` | Open in edit mode (Pages, Keynote and Numbers files stay view only) |
| `allowEdit` | `boolean` | `true` | Show Edit/View button |
| `allowSave` | `boolean` | `true` | Show Save/Download button, enable Ctrl+S |
Expand All @@ -71,6 +74,7 @@ CSS is auto-injected, no import needed (or import `@p10node/office-engine/styles
| `captureSelectAll` | `boolean` | `true` | Ctrl/⌘+A from anywhere on the page selects the document; `false`: from the viewer only |
| `fileMenuItems` | `FileMenuItem[]` | – | Extra File menu entries (`label`, `onClick`, `icon`, `hint`) |
| `icons` | `Icons` | built-in | Your own icons: a map by `IconName` or a resolver `(name, { size }) => node`; see [Icons](#icons) |
| `components` | `Partial<UIComponents>` | built-in | Your own `Button`, `Select`, `Separator`, `Dialog`, `Toast` in the toolbars and dialogs; see [Theming](theming.md#your-own-components) |
| `onRename` | `(name) => void` | – | File → Rename result (extension included) |
| `onClose` | `() => void` | – | Adds File → Close |
| `onSave` | `(blob, name) => void` | download | Receives saved file (downloads by default): the Office file, or a Markdown / HTML / SVG file as itself |
Expand Down Expand Up @@ -184,6 +188,46 @@ import { IconsProvider, XlsxView } from '@p10node/office-engine'
</IconsProvider>
```

### UI texts

Every text the viewer shows (titles, labels, menu entries, placeholders, dialogs, toasts, status lines such as "Page 1 of 5") comes from one typed table, `Strings`. English (`en`) is the default and German (`de`) ships with the package; `locale` picks one, and numbers and dates in the UI (zoom, counts, file sizes, comment times) are formatted with its `Intl` locale (`en-US`, `de-CH`).

`strings` replaces single texts and is merged over the locale key by key, so a group can be given in part. A value is a string, or a function where the text takes numbers or names:

```tsx
<DocViewer
src={file}
locale="de"
strings={{
file: { menu: 'Ablage' },
docx: { status: (page, pages, words) => `${page}/${pages} · ${words} Wörter` },
}}
/>
```

Views used on their own get their texts from a `StringsProvider` (English without one); `useStrings()` reads them in your own components:

```tsx
import { StringsProvider, useStrings, XlsxView } from '@p10node/office-engine'

<StringsProvider locale="de" strings={{ xlsx: { addSheet: 'Neues Blatt' } }}>
<div className="de-root"><XlsxView client={client} /></div>
</StringsProvider>
```

A locale of your own is a complete table: start from a copy of `en` (or `de`) and type it as `Strings`, so the compiler names every missing key, then pass it whole as `strings` (with `locale` set to the closest shipped one for number formats, or with its own `locale` value inside the table, a BCP 47 tag such as `'fr-CH'`):

```ts
import { en, type Strings } from '@p10node/office-engine'

export const fr: Strings = { ...en, locale: 'fr-CH', common: { ...en.common, cancel: 'Annuler' /* … */ } }
// <DocViewer src={file} strings={fr} />
```

To ship a locale with the engine, add `src/react/strings/<code>.ts` with a `Strings` table, list it in `LOCALES` and the `Locale` type (`src/react/strings/index.tsx`) and in `LOCALE_NAMES` (`src/embed.ts`); `test/strings.test.ts` checks that it has every key and no empty text.

Not translated: texts that end up in the saved document (a new sheet's name, the author "Me", the text of a new text box), font names, number format previews, and messages from the parsing worker that the UI shows as they are.

## Without a React build

```html
Expand All @@ -199,7 +243,7 @@ import { IconsProvider, XlsxView } from '@p10node/office-engine'
</script>
```

`<office-viewer>`: attributes `src`, `name`, `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`; properties `.file = File` and `.icons` (map or resolver, as `icons` above); events `load`, `error`, `comment` (`detail`: a `CommentEvent`).
`<office-viewer>`: attributes `src`, `name`, `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `locale="de"`, `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`; properties `.file = File`, `.icons` (map or resolver, as `icons` above) and `.strings = { … }` (see [UI texts](#ui-texts)); events `load`, `error`, `comment` (`detail`: a `CommentEvent`).

## Core API (no React)

Expand Down
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
50 changes: 49 additions & 1 deletion e2e/app/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
* ?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, &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)
*/
import { useState } from 'react'
import { createRoot } from 'react-dom/client'
import { DocViewer, type DocViewerProps, type FileMenuItem } from '../../src'
import { DocViewer, type DocViewerProps, type FileMenuItem, type UIComponents } from '../../src'

type Ev = { type: string; [k: string]: unknown }
declare global {
Expand All @@ -33,6 +35,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 +93,8 @@ const initial: DocViewerProps = {
captureSelectAll: flag('captureSelectAll'),
theme: (q.get('theme') as DocViewerProps['theme']) ?? undefined,
injectStyles: flag('injectStyles'),
locale: (q.get('locale') as DocViewerProps['locale']) ?? undefined,
strings: q.has('fileLabel') ? { file: { menu: q.get('fileLabel')! } } : 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 +111,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 Down
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