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 .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,5 @@ jobs:
pip install python-pptx Pillow
python scripts/fixtures.py --large-deck

- run: bun run build
- run: bun run test:e2e
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,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
93 changes: 92 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} strings={{ file: { menu: 'Files' } }} /> // override individual UI 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` | `string` | inherited | BCP 47 number/date formatting tag; does not select UI texts. See [UI texts](#ui-texts) |
| `strings` | `StringsOverride` | – | Texts merged over the enclosing provider or English, key by key; may include a formatting `locale` |
| `editable` | `boolean` | `false` | Open in edit mode (Pages, Keynote, Numbers and Visio 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 @@ -190,6 +194,93 @@ import { IconsProvider, XlsxView } from '@p10node/office-engine'
</IconsProvider>
```

### UI texts

Viewer UI texts (titles, labels, menu entries, placeholders, dialogs, toasts, status lines such as "Page 1 of 5") come from one typed table, `Strings`, with the exceptions listed below. Only English UI texts with US spelling are included in the default viewer and standalone embed bundle. German is a separate optional import with standard German spelling and `de-DE` number/date formatting (for example `1.234.567,89`):

```tsx
import { DocViewer } from '@p10node/office-engine'
import { de } from '@p10node/office-engine/locales/de'

<DocViewer src={file} strings={de} />
```

The locale module is included only when your app imports it. The German table uses standard German spelling and `de-DE` formatting. `locale="de-DE"` alone changes number/date formatting while keeping English UI texts; it does not load German. With no table or formatting override, dates and grouped counts retain the browser's locale. Page/slide numbers, measurements, file sizes and zoom labels retain ASCII digits and a decimal point, as before. An explicit formatting tag applies to all of these displays.

`strings` merges over the enclosing `StringsProvider` (or English) key by key, so a group can be given in part. Nested providers and `DocViewer` inherit the outer texts and formatting. Undefined values do not replace inherited values: `strings={en}` changes the texts while retaining an enclosing formatting tag; also pass `locale="en-US"` to select US formatting explicitly. A value is a string, or a function where the text takes numbers or names. Count callbacks receive raw numbers for pluralization; callbacks that format grouped counts also receive the active formatting tag as their final optional argument. Hoist override objects outside render, or memoize them when they depend on props, to keep the provider value stable. To customize an imported language, spread that table and any groups you change:

```tsx
import { DocViewer } from '@p10node/office-engine'
import { de } from '@p10node/office-engine/locales/de'

const germanTexts = {
...de,
file: { ...de.file, menu: 'Ablage' },
docx: {
...de.docx,
status: (page: number, pages: number, words: number, locale?: string) =>
`${page.toLocaleString(locale)}/${pages.toLocaleString(locale)} · ${words.toLocaleString(locale)} ${words === 1 ? 'Wort' : 'Wörter'}`,
},
}

<DocViewer src={file} strings={germanTexts} />
```

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'
import { de } from '@p10node/office-engine/locales/de'

const sheetTexts = { ...de, xlsx: { ...de.xlsx, addSheet: 'Neues Blatt' } }

<StringsProvider strings={sheetTexts}>
<div className="de-root"><XlsxView client={client} /></div>
</StringsProvider>
```

For a regional variant, override only the texts that differ. The `locale` prop is a BCP 47 formatting tag and takes precedence over `strings.locale`; otherwise the table or enclosing provider supplies the tag, then the browser default. Malformed tags (for example `de_DE`) are ignored: a valid table or inherited tag still applies, otherwise the default formatting above is used. Well-formed but unsupported tags follow `Intl` fallback. For example, a host can use US English as the base and supply British formatting and selected British spellings:

```tsx
import { DocViewer, StringsProvider, en, type StringsOverride } from '@p10node/office-engine'

const usEnglish = { ...en, locale: 'en-US' }
const britishOverrides: StringsOverride = {
edit: { textColor: 'Text colour' },
format: { borderColor: 'Border colour' },
}

<StringsProvider strings={usEnglish}>
<DocViewer src={file} locale="en-GB" strings={britishOverrides} />
</StringsProvider>
```

The same overrides work with `StringsProvider`, `mount()` and the web component's `strings` property. The example changes only those two labels; other text keeps the US English defaults. Override any other regional differences you need.

For a complete language of your own, pass a `Strings` table as `strings`. Starting from `en` (or `de`) keeps untranslated entries as fallbacks; the following example only translates Cancel. Replace the remaining entries to complete the translation:

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

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

A host can keep its own language tables in its app and pass them through `strings`; no engine registration is needed. A new optional package locale follows the German entry: add its typed table, a `src/locales/<code>.ts` entry and the corresponding build/package export. Locale parity tests check complete keys and nonempty texts.

For vanilla embeds, pass the same optional table to `mount(el, { src, strings: de })` or assign it to the web component:

```html
<script src="office-engine.embed.js"></script>
<office-viewer id="viewer" src="/file.xlsx"></office-viewer>
<script type="module">
import { de } from './locales/de.js' // optional module next to the distributed embed bundle
document.getElementById('viewer').strings = de
</script>
```

Document content stays in its original language. Default new sheet names, the author "Me" and new text box content also stay unchanged; the “Page 1 of 5” header/footer preset inserts text in the UI language. Font names, formula names and help, number format previews, host-provided labels and engine/transport errors (including main-thread fetch errors such as `HTTP 404 while fetching …`, collaboration errors such as `Document is still syncing`, and parsing-worker messages) are not translated by the table. Print, PDF and HTML export inherit the active UI table for viewer-generated labels; document content remains unchanged.

## Without a React build

```html
Expand All @@ -205,7 +296,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="en-GB"` (number/date formatting), `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
74 changes: 73 additions & 1 deletion docs/theming.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,81 @@ 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-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. Nested providers inherit the outer texts, icons and components. Local `strings` merge key by key;
an explicit `locale` changes number/date formatting while preserving the inherited texts. Omitted or `undefined`
components and string entries preserve the outer values.

## 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, 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` (`null` hides the label for an icon-only trigger), `icon` (an `IconName`, not a resolved node), `className` (extra trigger class), `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 font-size input and its list (`SizeBox`), Page setup, Header / footer and Details dialogs, and the buttons
inside border pickers retain the built-in markup. `components` replaces the controls listed above.

A host Dialog can put its footer outside the form: call the action's `onClick` from a regular button. Inside
a form, render `submit` actions as submit buttons and let `onSubmit` run them; do not also call their `onClick`,
which would submit twice. Keep `onClick` for the other actions.

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.
It measures the More button in the same pass and remeasures when Button, Select or Separator is replaced.

Host Select lists rendered with React's `createPortal` remain inside their surrounding overflow menu or popover
for outside-click handling. The portal must belong to the same React tree as the Select. An independently
mounted React root or a non-React overlay has no such ownership path; render that list inside the Select's DOM
subtree instead.

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
10 changes: 10 additions & 0 deletions e2e/app/built-locale.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!doctype html>
<html><head><meta charset="utf-8"></head><body style="margin:0">
<div id="built" style="height:100vh"></div>
<script type="module">
import * as React from 'react'
import { createRoot } from 'react-dom/client'
window.__events = []
window.__builtRuntime = { React, createRoot }
</script>
</body></html>
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
Loading
Loading