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
108 changes: 106 additions & 2 deletions 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,14 +74,75 @@ 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 |
| `onDirtyChange` | `(dirty) => void` | – | Whether there are unsaved changes |
| `collab` | `CollabOptions` | – | Real-time collaboration, see [collaboration](collaboration.md) |
| `comments` | `CommentOptions \| false` | `{}` | Comments (see below); `false` hides them |
| `onLoad` | `(client) => void` | – | |
| `onLoad` | `(client) => void` | – | Once per opened document |
| `onError` | `(error) => void` | – | |
| `controller` | `ViewerController` | its own | The viewer's state and commands for the host, see [headless mode](#headless-mode) |
| `headless` | `boolean` | `false` | The document alone: no top bar, zoom control, outline panel, sheet tabs or slide list |
| `icons` | `Partial<Record<string, ReactNode>>` | – | The host's icons by name (`ICON_NAMES`), sized by font-size (1em), instead of the built-in ones |

### Headless mode

For a host that draws its own controls around the document: `headless` leaves the viewer with the document alone, and a
`controller` (`createViewerController()`) carries its state and the commands that drive it. While editing, the formatting
toolbar keeps its row above the document; dialogs, the find bar and the comments panel are the viewer's own. `toolbar`
set explicitly brings back the top bar (File menu, comments, Save) and leaves the rest headless.

```tsx
import { createViewerController, DocViewer, useViewerState } from '@p10node/office-engine'
import { useMemo } from 'react'

function Viewer({ file }: { file: File }) {
const ctl = useMemo(() => createViewerController(), [])
const s = useViewerState(ctl)
return (
<>
<nav>
{s.outline?.items.map((i) => (
<button key={i.id} aria-current={i.current} style={{ paddingLeft: i.level * 12 }} onClick={() => ctl.goto(i.id)}>
{i.title}
</button>
))}
</nav>
{s.zoom && <button onClick={() => ctl.zoomIn()}>{s.zoom.value === 'fit' ? 'Fit' : `${Math.round(s.zoom.effective * 100)}%`}</button>}
{s.canEdit && <button onClick={() => ctl.setEditing(!s.editing)}>{s.editing ? 'View' : 'Edit'}</button>}
{s.dirty && <button onClick={() => ctl.save()}>Save</button>}
<DocViewer src={file} controller={ctl} headless style={{ height: 600 }} />
</>
)
}
```

| `ViewerState` | Meaning |
|---------------|---------|
| `rev` | counts the changes (the state object is replaced on each) |
| `kind` | `'docx'`, `'xlsx'`, `'pptx'`, or `null` before a document is open |
| `loading` | loading or downloading |
| `editing`, `canEdit` | in edit mode; whether editing is possible (allowed, not view only) |
| `dirty`, `saving` | unsaved changes; a save running |
| `canUndo`, `canRedo` | whether undo / redo can run (spreadsheets count the edits made here; presentations offer redo whenever editing) |
| `zoom` | `{ value: 'fit' \| number, effective }`, `null` for spreadsheets |
| `page` | `{ current, count }` from 1: the page (documents; `count` 0 while laid out) or slide in view; `null` for spreadsheets |
| `outline` | `{ kind, items: [{ id, title, level, current }] }`: a document's headings, a workbook's visible sheets, a presentation's slides (titled by their title placeholder, else "Slide n") |
| `status` | the status line ("Page 2 of 7 · 1,204 words", "Slide 3 of 12", "200 rows × 8 cols") |

Commands: `setEditing(on)`, `save()`, `undo()`, `redo()`, `zoomIn()`, `zoomOut()`, `setZoom('fit' | number)`,
`goto(outlineId)`, `gotoPage(n)`, `present()` (a slideshow from the slide in view), `print()`, `fileAction(id)` (a File menu
action: `pdf`, `html`, `text:md`, `details`, `rename`…), `toggleComments(open?)`. A command the open document has no use
for does nothing. `subscribe(fn)` returns its unsubscribe; `snapshot()` the current state. Without `react`, `mount()`
returns the controller (`mounted.controller`), and `<office-viewer headless>` has it as `element.controller`.

Controller actions obey `allowEdit`, `allowSave`, `allowDownload` and `allowOpen` even when the File menu is hidden.
`fileMenu={false}` hides that menu and its keyboard shortcuts; it does not disable a host's controller controls.
New/Open replace the document and remain available for a read-only file when `allowOpen` permits them.
Import changes a workbook and additionally requires editing permission. Controllers are created with
`createViewerController()`; publishing and attachment methods are internal to the engine.

### Comments

Expand Down Expand Up @@ -184,6 +248,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 +303,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"`, `headless`; properties `.file = File`, `.icons` (map or resolver, as `icons` above), `.strings = { … }` (see [UI texts](#ui-texts)), `.controller` (see [headless mode](#headless-mode)); events `load`, `error`, `comment` (`detail`: a `CommentEvent`).

## Core API (no React)

Expand Down
46 changes: 45 additions & 1 deletion docs/theming.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,53 @@ 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
<DocViewer
src={file}
editable
components={{
Button: ({ title, icon, label, children, active, expanded, disabled, onClick, onMouseDown }) => (
<MyIconButton tooltip={title} aria-label={title} pressed={active} aria-expanded={expanded}
disabled={disabled} onClick={onClick} onMouseDown={onMouseDown}>
{icon}{label}{children}
</MyIconButton>
),
Separator: () => <MyDivider vertical />,
}}
/>
```

| 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`, `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.

## Tokens

| Group | Tokens |
Expand Down
Loading
Loading