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
- **File menu**: new, open (also DOC / XLS / PPT / RTF / OpenDocument / Pages / Keynote / Numbers / Visio / CSV / text / Markdown / HTML / SVG / diagrams), import CSV, rename, download as PDF / HTML / text / CSV, document details, print
- **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
- **Fonts**: hand the viewer font files (the OFL fallbacks Carlito, Caladea, Liberation, or the originals) and documents are laid out once they are loaded, so lines and pages break as with the fonts the document names ([API](docs/api.md#fonts))
- **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
- **Embed anywhere**: React component, hook, vanilla `mount()`, `<office-viewer>` web component, single `<script>` file

Expand Down
47 changes: 46 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} fonts={[{ family: 'Carlito', src: '/fonts/Carlito-Regular.ttf' }]} /> // font files, see Fonts
```

### File menu
Expand Down Expand Up @@ -71,6 +72,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) |
| `fonts` | `FontSource[]` | – | Font files for the documents' text (the library ships none), loaded when a document uses them; see [Fonts](#fonts) |
| `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 +192,49 @@ import { IconsProvider, XlsxView } from '@p10node/office-engine'
</IconsProvider>
```

### Fonts

The library ships no font files. Text is shown in the fonts the browser has, and where a line or a page breaks depends on them: a document in Calibri on a machine without Calibri is set in another font and breaks elsewhere. Documents name metric-compatible fallbacks after their fonts (the same widths, under the SIL Open Font License), so supplying those files is enough for most Office documents to break as they do in Office:

| Document font | Fallback |
|------------------------|--------------------------|
| Calibri, Calibri Light | Carlito |
| Cambria | Caladea |
| Arial, Helvetica | Liberation Sans, Arimo |
| Times New Roman | Liberation Serif, Tinos |
| Courier New | Liberation Mono, Cousine |

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

// Served by your app (Carlito and Caladea: Google Fonts / Debian fonts-crosextra-*; Liberation: github.com/liberationfonts)
const fonts: FontSource[] = [
{ family: 'Carlito', src: '/fonts/Carlito-Regular.ttf' },
{ family: 'Carlito', src: '/fonts/Carlito-Bold.ttf', weight: 700 },
{ family: 'Carlito', src: '/fonts/Carlito-Italic.ttf', style: 'italic' },
{ family: 'Carlito', src: '/fonts/Carlito-BoldItalic.ttf', weight: 700, style: 'italic' },
{ family: 'Caladea', src: '/fonts/Caladea-Regular.ttf' },
{ family: 'Liberation Sans', src: '/fonts/LiberationSans-Regular.ttf' },
{ family: 'Liberation Serif', src: '/fonts/LiberationSerif-Regular.ttf' },
{ family: 'Liberation Mono', src: '/fonts/LiberationMono-Regular.ttf' },
]

<DocViewer src={file} fonts={fonts} />
```

| `FontSource` | Type | Notes |
|----------------|----------------------------------------------------|---------------------------------------------------------------------------------------|
| `family` | `string` | The name text asks for: a fallback (`Carlito`) or the document's own name (`Calibri`) |
| `src` | `string \| ArrayBuffer \| ArrayBufferView \| Blob` | A URL (resolved against the page) or the file's bytes: TTF, OTF, WOFF, WOFF2 |
| `weight` | `number \| string` | CSS `font-weight` of the file: `700`, `'bold'`, `'100 900'` for a variable font |
| `style` | `string` | `'normal'`, `'italic'`, `'oblique'` |
| `unicodeRange` | `string` | CSS `unicode-range`, when a family comes in several files |

- **Which name**: under a fallback's name (`Carlito`), the file is used where the original is not installed, and a machine that has Calibri keeps it. Under the document's own name (`Calibri`), it is used everywhere, before an installed font of that name.
- **When**: a file is fetched when a document whose text is set in its family is shown (through the fallback list too: a declared `Carlito` is fetched for a document in Calibri), not before. Nothing is fetched when no font is declared. The faces are added to the page's `document.fonts` (the `FontFace` API, no stylesheet) and shared by the viewers on the page that declare the same file; they are removed when no viewer declares them any more.
- **Layout**: a document is measured and paginated once the fonts it uses are loaded. A file that fails to load is reported to `onError` and in the console, and the text is shown in the next font of its list; one that takes more than 3 s is not waited for any longer: the document is laid out without it, and again when it arrives (the page in view and the caret stay where they are). A font the page provides itself (an `@font-face` of the host page) that arrives late also has the document laid out again. Spreadsheets fit numbers to their columns again; slides are laid out by the browser and follow by themselves. Printing and *Download as PDF* use the same files.
- **Only from the host**: fonts are taken from this list only. A document's font names pick among them, and fonts embedded in a document (`word/fontTable.xml`) are not read.

## Without a React build

```html
Expand All @@ -205,7 +250,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"`), `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`, `fonts` (a JSON list of `FontSource` with URLs: `fonts='[{"family":"Carlito","src":"/fonts/Carlito-Regular.ttf"}]'`); properties `.file = File`, `.icons` (map or resolver, as `icons` above) and `.fonts` (as `fonts` above, bytes too; it wins over the attribute); events `load`, `error`, `comment` (`detail`: a `CommentEvent`).

## Core API (no React)

Expand Down
3 changes: 2 additions & 1 deletion docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ The app reads `DocViewer` props from the query string (`?src=samples/sample.docx
| `file-menu.spec.ts` | every File entry: New, Open (conversions), Import, Save, Rename, Download as, Details, Print |
| `permissions.spec.ts` | `allowSave` / `allowDownload` combinations, image download, Ctrl+S / Ctrl+P |
| `color.spec.ts` | custom colors (system picker, recent list, persistence) in the 3 formats |
| `embed.spec.ts` | `<office-viewer>` (shadow DOM, attributes, `file`) and `mount()` |
| `embed.spec.ts` | `<office-viewer>` (shadow DOM, attributes, `file`, `fonts`) and `mount()` |
| `fonts.spec.ts` | host fonts (a generated test font): loaded before measuring, timeout, failure, late web fonts |
| `collab.spec.ts` | two editors on `scripts/collab-server.ts`: live edits, presence, File menu in a room |

`bun test` only runs `test/` (`bunfig.toml`); `bun run test:e2e` runs `e2e/`.
Expand Down
1 change: 1 addition & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
- DOCX: blocks (paragraph/table) stream in → offscreen height measurement in time slices → pagination → only visible pages render
- XLSX: rows stream in, 2D virtualized grid (only cells in viewport render), freeze panes, merge, number format, sheet tabs
- PPTX: slides parsed on demand when scrolled into view, virtualized thumbnails
- **Fonts**: the host can supply font files (`fonts`: URLs or bytes, loaded with the `FontFace` API when a document uses the family); a declared fallback serves the fonts named before it (Carlito for Calibri, Caladea for Cambria, Liberation for Arial, Times New Roman and Courier New). DOCX pages are measured once those fonts are loaded (at most 3 s, not past a failure; a font that comes later has the pages measured again); a late web font of the page also has the pages measured again; XLSX fits its numbers again. No font file ships with the library, and fonts embedded in a document are not read. See [API](api.md#fonts)

## Format support

Expand Down
2 changes: 2 additions & 0 deletions e2e/app/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* ?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}>`
* &fonts=[{"family":"Carlito","src":"/fonts/carlito.ttf"}]: the host's fonts (JSON)
*/
import { useState } from 'react'
import { createRoot } from 'react-dom/client'
Expand Down Expand Up @@ -71,6 +72,7 @@ const initial: DocViewerProps = {
</svg>
)
: undefined,
fonts: q.get('fonts') ? JSON.parse(q.get('fonts')!) : undefined,
collab: q.get('collab') ? { transport: q.get('collab')!, room: q.get('room') ?? 'e2e', base: Number(q.get('base')) || 0, user: { name: q.get('user') ?? 'Tester' } } : undefined,
}

Expand Down
40 changes: 40 additions & 0 deletions e2e/embed.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { describe, expect, test } from 'bun:test'
import { parasToDocx } from '../src/core/convert'
import { testFont } from '../test/font-builder'
import { useBrowser, viewer } from './harness'

useBrowser()
Expand Down Expand Up @@ -40,6 +42,44 @@ describe('embedding without React', () => {
await v.page.locator('#wc .de-grid').waitFor()
})

test('<office-viewer>: fonts attribute (URLs), fonts property (bytes too)', async () => {
const font = Buffer.from(testFont({ family: 'Wide Test' }))
const docx = Buffer.from(await (await parasToDocx([{ runs: [{ text: 'Wide', set: { font: 'Wide Test' } }] }])).arrayBuffer())
const asked: string[] = []
const v = await viewer(
{},
{
page: 'embed.html',
setup: (v) =>
v.ctx.route('**/gen/**', (r) => {
const name = new URL(r.request().url()).pathname.split('/').pop()!
asked.push(name)
return r.fulfill({ body: name.endsWith('.docx') ? docx : font })
}),
},
)
const wc = v.page.locator('#wc')
await wc.locator('.de-page-inner').first().waitFor()
const faces = () => v.page.evaluate(() => [...document.fonts].map((f) => `${f.family.replace(/"/g, '')} ${f.status}`))
await v.page.evaluate(() => {
const el = document.getElementById('wc')!
el.setAttribute('fonts', JSON.stringify([{ family: 'Wide Test', src: '/gen/wide.ttf' }]))
el.setAttribute('src', 'gen/wide.docx')
})
await v.page.waitForFunction(() => [...document.fonts].some((f) => f.status === 'loaded'))
expect(asked).toEqual(['wide.docx', 'wide.ttf'])
expect(await faces()).toEqual(['Wide Test loaded'])
// the property wins over the attribute: the bytes, and the file at the URL is let go
await v.page.evaluate((bytes) => {
const el = document.getElementById('wc') as HTMLElement & { fonts?: unknown }
el.fonts = [{ family: 'Wide Test', src: new Uint8Array(bytes).buffer, weight: 700 }]
}, [...font])
await v.page.waitForFunction(() => [...document.fonts].length === 1 && [...document.fonts][0].weight === '700')
expect(await faces()).toEqual(['Wide Test loaded'])
expect(asked).toEqual(['wide.docx', 'wide.ttf'])
expect(v.errors).toEqual([])
})

test('mount(): options, update(), destroy()', async () => {
const v = await viewer({}, { page: 'embed.html' })
const host = v.page.locator('#mounted')
Expand Down
Loading