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; 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
85 changes: 84 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` | `'en'` | `'en'` | Built-in English base; supply other languages explicitly through `strings`. See [UI texts](#ui-texts) |
| `strings` | `StringsOverride` | – | Texts merged over English, key by key; `strings.locale` selects number/date formatting |
| `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 Down Expand Up @@ -184,6 +187,86 @@ 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 US English (`en-US`) is 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. Setting `locale="de-DE"` alone does not load German: only `en` is built in, and unsupported base locale values fall back to English.

`strings` merges over English 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. 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'

<DocViewer
src={file}
strings={{
...de,
file: { ...de.file, menu: 'Ablage' },
docx: { ...de.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'
import { de } from '@p10node/office-engine/locales/de'

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

For a regional variant, override only the texts that differ. `strings.locale` is the BCP 47 tag used by `Intl` for numbers and dates. Every omitted text falls back to English. For example, a host can use US English as the base and supply British formatting and selected British spellings:

```tsx
<DocViewer
src={file}
locale="en"
strings={{
locale: 'en-GB',
edit: { textColor: 'Text colour' },
format: { borderColor: 'Border colour' },
}}
/>
```

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 parsing-worker messages are not translated by the table.

## Without a React build

```html
Expand All @@ -199,7 +282,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"`, `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
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 @@ -45,4 +45,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([])
})
})
23 changes: 23 additions & 0 deletions e2e/locale-docx.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { describe, expect, test } from 'bun:test'
import { de } from '../src/locales/de'
import { useBrowser, viewer } from './harness'

useBrowser()

describe('locale: DOCX', () => {
test('status, toolbar and page setup in German', async () => {
const v = await viewer({ src: 'samples/sample.docx', locale: 'de-DE', editable: true })
await v.page.locator('.de-ebar').first().waitFor()
expect(await v.status()).toMatch(/Seite 1 von \d+/)
expect(await v.btn('Fett').count()).toBe(1)
expect(await v.btn('Rückgängig').count()).toBe(1)

await v.btn(de.docx.pageSetup).click()
const ps = v.page.locator('[role=dialog][aria-label="Seite einrichten"]')
await ps.waitFor()
expect(await ps.innerText()).toContain('Querformat')
await ps.locator('button', { hasText: 'Abbrechen' }).click()
await ps.waitFor({ state: 'detached' })
expect(v.errors).toEqual([])
})
})
21 changes: 21 additions & 0 deletions e2e/locale-xlsx.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, expect, test } from 'bun:test'
import { useBrowser, viewer } from './harness'

useBrowser()

describe('locale: XLSX', () => {
test('status, toolbar and sheet tab menu in German', async () => {
const v = await viewer({ src: 'samples/sample.xlsx', locale: 'de-DE', editable: true })
await v.page.locator('.de-ebar').first().waitFor()
expect(await v.status()).toMatch(/Zeilen × \d+ Spalten/)
expect(await v.btn('Fett').count()).toBe(1)
expect(await v.btn('Rahmenlinien').count()).toBe(1)

await v.page.locator('.de-tab[role=tab]').first().click({ button: 'right' })
const menu = v.page.locator('.de-ctx')
await menu.waitFor()
expect(await menu.innerText()).toContain('Blatt löschen')
await v.page.keyboard.press('Escape')
expect(v.errors).toEqual([])
})
})
85 changes: 85 additions & 0 deletions e2e/locale.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { describe, expect, test } from 'bun:test'
import { en } from '../src/react/strings'
import { de } from '../src/locales/de'
import { useBrowser, viewer } from './harness'

useBrowser()

describe('locale', () => {
test('bar, File menu and details dialog in German', async () => {
const v = await viewer({ src: 'samples/sample.docx', locale: 'de-DE' })
expect(await v.page.locator('.de-bar .de-file').innerText()).toContain('Datei')
expect(await v.barButton('Bearbeiten').count()).toBe(1)

const labels = await v.menuLabels()
expect(labels).toContain('Öffnen…')
expect(labels).toContain('PDF-Dokument')
expect(labels).toContain('Dokumenteigenschaften')

await v.menu('Dokumenteigenschaften')
const dlg = v.page.locator('[role=dialog][aria-label="Dokumenteigenschaften"]')
await dlg.waitFor()
expect(await dlg.innerText()).toContain('Dateigröße')
await dlg.locator('button', { hasText: 'Schließen' }).click()
await dlg.waitFor({ state: 'detached' })

await v.barButton('Bearbeiten').click()
expect(await v.barButton('Ansicht').count()).toBe(1)
expect(v.errors).toEqual([])
})

test('PPTX in German: status, zoom, present', async () => {
const v = await viewer({ src: 'samples/sample.pptx', locale: 'de-DE' })
expect(await v.status()).toMatch(/Folie 1 von \d+/)
expect(await v.page.locator('.de-zoom[aria-label="Zoom"] button[aria-label="Vergrößern"]').count()).toBe(1)
expect(await v.page.locator('.de-present-btn').innerText()).toContain('Bildschirmpräsentation')
expect(v.errors).toEqual([])
})

test('a partial override keeps the other texts', async () => {
const v = await viewer({ src: 'samples/sample.docx', locale: 'de-DE', fileLabel: 'Ablage' })
expect(await v.page.locator('.de-bar .de-file').innerText()).toContain('Ablage')
expect(await v.barButton('Bearbeiten').count()).toBe(1)
})

test('English stays the default', async () => {
const v = await viewer({ src: 'samples/sample.pptx' })
expect(await v.page.locator('.de-bar .de-file').innerText()).toContain('File')
expect(await v.status()).toMatch(/Slide 1 of \d+/)
})

for (const kind of ['docx', 'xlsx', 'pptx'] as const) {
test(`${kind}: switching locale updates comment hints without reopening the document`, async () => {
const v = await viewer({ src: `samples/sample.${kind}`, editable: true, cmOpen: true })
const empty = v.page.locator('.de-cm-empty')
await empty.filter({ hasText: en[kind].commentHint }).waitFor()
await v.page.evaluate(() => window.__setLanguage('de-DE'))
await empty.filter({ hasText: de[kind].commentHint }).waitFor()
expect(await v.page.locator('.de-cm-panel').getAttribute('aria-label')).toBe('Kommentare')
expect((await v.events('load')).length).toBe(1)
expect(v.errors).toEqual([])
})
}

test('PPTX comment locations follow the UI language', async () => {
const v = await viewer({ src: 'samples/sample.pptx', locale: 'de-DE', editable: true, cmOpen: true })
await v.page.locator('.de-cm-new').click()
const draft = v.page.locator('.de-cm-draft')
await draft.waitFor()
expect(await draft.locator('.de-cm-quote').innerText()).toBe('Folie 1')
await draft.locator('textarea').fill('Kommentar')
await draft.locator('button', { hasText: 'Kommentieren' }).click()
const quote = v.page.locator('.de-cm-card .de-cm-quote')
await quote.filter({ hasText: 'Folie 1' }).waitFor()
await v.page.evaluate(() => window.__setLanguage('en'))
await quote.filter({ hasText: 'Slide 1' }).waitFor()
expect(v.errors).toEqual([])
})

test('unknown locales fall back to English, including prototype property names', async () => {
const v = await viewer({ src: 'samples/sample.docx', locale: 'constructor' })
expect(await v.page.locator('.de-file').innerText()).toContain('File')
expect(await v.status()).toMatch(/Page 1 of /)
expect(v.errors).toEqual([])
})
})
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
"types": "./dist/types/embed.d.ts",
"import": "./dist/embed.js"
},
"./locales/de": {
"types": "./dist/types/locales/de.d.ts",
"import": "./dist/locales/de.js"
},
"./worker": "./dist/office-engine.worker.js",
"./embed.js": "./dist/office-engine.embed.js",
"./collab": {
Expand Down
Loading
Loading