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
92 changes: 91 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 Down Expand Up @@ -190,6 +193,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 +295,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
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
8 changes: 8 additions & 0 deletions e2e/app/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,28 @@
* ?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 opts into the explicitly imported German table, &fileLabel=… overrides the File label
*/
import { useState } from 'react'
import { createRoot } from 'react-dom/client'
import { DocViewer, type DocViewerProps, type FileMenuItem } 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
__setLanguage: (language: 'en' | 'de-DE') => void
__german: typeof de
}
}
window.__events = []
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 Down Expand Up @@ -48,6 +53,8 @@ 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,
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 Down Expand Up @@ -77,6 +84,7 @@ const initial: DocViewerProps = {
function App() {
const [props, setProps] = useState(initial)
window.__setProps = (p) => setProps((cur) => ({ ...cur, ...p }))
window.__setLanguage = (language) => setProps((cur) => ({ ...cur, strings: language === 'de-DE' ? de : undefined }))
return <DocViewer {...props} />
}

Expand Down
30 changes: 30 additions & 0 deletions e2e/embed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,34 @@ describe('embedding without React', () => {
await v.page.evaluate(() => (window as any).__mounted.destroy())
expect(await host.innerHTML()).toBe('')
})

test('locale and strings update live through mount() and the web component', async () => {
const v = await viewer({}, { page: 'embed.html' })
const wc = v.page.locator('#wc')
const host = v.page.locator('#mounted')
await wc.locator('.de-page-inner').first().waitFor()
await host.locator('.de-grid').waitFor()
await v.page.evaluate(() => {
const el = document.getElementById('wc') as HTMLElement & { strings?: { file?: { menu?: string } } }
el.setAttribute('file-menu', 'true')
const de = window.__german
el.strings = { ...de, file: { ...de.file, menu: 'Ablage' } }
;(window as any).__mounted.update({ toolbar: true, strings: { ...de, file: { ...de.file, menu: 'Dateien' } } })
})
await wc.getByRole('button', { name: 'Ablage', exact: true }).waitFor()
await host.getByRole('button', { name: 'Dateien', exact: true }).waitFor()
await wc.getByRole('button', { name: 'Ablage', exact: true }).click()
expect(await wc.locator('.de-dd-pop').innerText()).toContain('Öffnen…')
await v.page.keyboard.press('Escape')
await v.page.evaluate(() => {
const el = document.getElementById('wc') as HTMLElement & { strings?: object }
el.strings = undefined
el.setAttribute('locale', 'fr-FR')
;(window as any).__mounted.update({ locale: 'en', strings: undefined })
})
await wc.getByRole('button', { name: 'File', exact: true }).waitFor()
await host.getByRole('button', { name: 'File', exact: true }).waitFor()
expect((await v.page.evaluate(() => (window as any).__wcEvents)).length).toBe(1)
expect(v.errors).toEqual([])
})
})
4 changes: 2 additions & 2 deletions e2e/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ export function useBrowser() {
export type Params = Record<string, string | number | boolean>

/** Opens the fixture with DocViewer props from `params` and waits for the document. */
export async function viewer(params: Params, opts: { wait?: boolean; page?: string; viewport?: { width: number; height: number } } = {}) {
export async function viewer(params: Params, opts: { wait?: boolean; page?: string; viewport?: { width: number; height: number }; locale?: string } = {}) {
if (!shared) throw new Error('useBrowser() missing')
const ctx = await shared.browser.newContext({ viewport: opts.viewport ?? { width: 1600, height: 1000 }, acceptDownloads: true })
const ctx = await shared.browser.newContext({ viewport: opts.viewport ?? { width: 1600, height: 1000 }, acceptDownloads: true, locale: opts.locale })
open.add(ctx)
const page = await ctx.newPage()
const v = new Viewer(page, ctx)
Expand Down
Loading