diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 34d3396..3f4d46c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/README.md b/README.md index c65288b..134271c 100644 --- a/README.md +++ b/README.md @@ -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()`, `` web component, single ` + + +``` + +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 @@ -205,7 +409,7 @@ import { IconsProvider, XlsxView } from '@p10node/office-engine' ``` -``: 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`). +``: 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"`, `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) diff --git a/docs/theming.md b/docs/theming.md index ef89f4b..688df4e 100644 --- a/docs/theming.md +++ b/docs/theming.md @@ -69,9 +69,81 @@ gives the class name and style their root needs: ```tsx const root = useThemeRoot(theme) -return
+return ( + +
+
+) ``` +`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 ( + + {icon}{label}{children} + + ) +} + +function ViewerSeparator() { + return +} + +const components: Partial = { Button: ViewerButton, Separator: ViewerSeparator } + + +``` + +| 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`: `` +(when `option.icon` is set). It uses the viewer's `icons` overrides and falls back to the built-in SVGs. + ## Tokens | Group | Tokens | diff --git a/e2e/app/built-locale.html b/e2e/app/built-locale.html new file mode 100644 index 0000000..af1df32 --- /dev/null +++ b/e2e/app/built-locale.html @@ -0,0 +1,10 @@ + + +
+ + diff --git a/e2e/app/embed.html b/e2e/app/embed.html index 4608cef..a066139 100644 --- a/e2e/app/embed.html +++ b/e2e/app/embed.html @@ -9,6 +9,8 @@
+ diff --git a/e2e/app/ui.tsx b/e2e/app/ui.tsx new file mode 100644 index 0000000..178a872 --- /dev/null +++ b/e2e/app/ui.tsx @@ -0,0 +1,53 @@ +import { useEffect, useState } from 'react' +import { createRoot } from 'react-dom/client' +import { createPortal } from 'react-dom' +import { PromptDialog } from '../../src/react/common/Dialog' +import { Btn, Dropdown, Pop, ToolbarRow } from '../../src/react/edit/Toolbar' +import { OfficeUIProvider, type ButtonProps, type DialogProps, type SelectProps } from '../../src/react/ui' +import '../../src/react/styles.css' + +window.__events = [] +const noop = () => {} +function Button(p: ButtonProps) { + return +} +function WideButton(p: ButtonProps) { + return )} + +} +function PortalSelect(p: SelectProps) { + const [open, setOpen] = useState(false) + return <> + + {open && createPortal(
+ {p.options.map((o) => )} +
, document.body)} + +} +const picker = (title: string) => window.__events.push({ type: 'pick', value, title })} /> +function App() { + const [wide, setWide] = useState(false) + const [tick, setTick] = useState(0) + return +
+ + + + {Array.from({ length: 17 }, (_, i) => )} +
+ {Array.from({ length: 8 }, (_, i) => )} + {picker('Overflow picker')} +
+ {() => picker('Popover picker')} + window.__events.push({ type: 'submit', value }) }} onClose={() => window.__events.push({ type: 'close' })} /> +
+
+} +createRoot(document.getElementById('root')!).render() diff --git a/e2e/built-package.ts b/e2e/built-package.ts new file mode 100644 index 0000000..346bce8 --- /dev/null +++ b/e2e/built-package.ts @@ -0,0 +1,32 @@ +/** Emitted-package suites require a complete, fresh production build. */ +import { beforeAll } from 'bun:test' +import { existsSync, readdirSync, statSync } from 'node:fs' +import { resolve } from 'node:path' + +export const packageRoot = resolve(process.env.BUILT_PACKAGE_ROOT ?? process.cwd()) +export const builtModule = (file: string) => `/@fs${packageRoot}/dist/${file}` + +function newestSource(path: string): number { + if (!existsSync(path)) return 0 + if (!statSync(path).isDirectory()) return statSync(path).mtimeMs + return Math.max(0, ...readdirSync(path).map((name) => newestSource(`${path}/${name}`))) +} + +/** An external package without sources is checked for completeness only. */ +export function useBuiltPackage() { + beforeAll(() => { + const outputs = ['index.js', 'locales/de.js', 'office-engine.worker.js', 'office-engine.embed.js', 'styles.css'] + for (const file of outputs) { + if (!existsSync(`${packageRoot}/dist/${file}`)) throw new Error(`Missing dist/${file} in ${packageRoot}; run bun run build before browser tests`) + } + const inputs = ['src', 'package.json', 'bun.lock', 'vite.config.ts', 'vite.embed.config.ts', 'vite.worker.config.ts', 'tsconfig.build.json'] + // Published packages do not include source/build inputs; a checkout must always be fresh, + // including when explicitly selected through BUILT_PACKAGE_ROOT. + if (existsSync(`${packageRoot}/src`)) { + const newest = Math.max(...inputs.map((file) => newestSource(`${packageRoot}/${file}`))) + for (const file of outputs) { + if (statSync(`${packageRoot}/dist/${file}`).mtimeMs < newest) throw new Error(`Stale dist/${file} in ${packageRoot}; run bun run build before browser tests`) + } + } + }) +} diff --git a/e2e/collab.spec.ts b/e2e/collab.spec.ts index d3571f0..4311fdc 100644 --- a/e2e/collab.spec.ts +++ b/e2e/collab.spec.ts @@ -1,7 +1,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test' import { readFileSync } from 'node:fs' import { rebuildZip } from '../src/core/zipwrite' -import { SAMPLES, useBrowser, viewer } from './harness' +import { SAMPLES, useBrowser, viewer, fromB64, xlsxSheet, docxParas, paraText, runsOf } from './harness' useBrowser() @@ -49,6 +49,40 @@ describe('real-time collaboration', () => { await a.page.waitForFunction(() => [...document.querySelectorAll('.de-cell')].some((c) => (c as HTMLElement).innerText === '8'), null, { timeout: 20_000 }) }) + test('controller history follows collaboration across rename and save/reopen', async () => { + const id = await room('sample.xlsx') + const v = await viewer({ src: `${HTTP}/rooms/${id}/file?seq=0`, name: 'shared.xlsx', collab: `ws://localhost:${PORT}/collab`, room: id, user: 'Ann', editable: true, controller: true, onSave: true }) + await v.page.locator('.de-collab-live').waitFor() + await v.typeCell('J12', 'before rename') + await v.page.waitForFunction(() => window.__ctl.snapshot().canUndo) + await v.page.locator('.de-tab[role=tab]').first().dblclick() + await v.page.locator('.de-tab-input').fill('Renamed') + await v.page.keyboard.press('Enter') + await v.page.waitForFunction(() => window.__ctl.snapshot().outline?.items[0].title === 'Renamed') + expect(await v.page.evaluate(() => window.__ctl.snapshot().canUndo)).toBe(false) + // Verify Ctrl+Z and the controller agree on the actual document, rather than just flags. + await v.page.locator('.de-grid').focus() + await v.page.keyboard.press('Control+z') + await v.page.evaluate(() => window.__ctl.save()) + let saved = await v.waitEvent('save') + expect((await xlsxSheet(fromB64(saved.b64 as string))).cell('J12')).toBe('before rename') + await v.typeCell('J12', 'after rename') + await v.page.waitForFunction(() => window.__ctl.snapshot().canUndo) + await v.page.evaluate(() => window.__ctl.undo()) + await v.page.waitForFunction(() => window.__ctl.snapshot().canRedo && !window.__ctl.snapshot().canUndo) + await v.page.evaluate(() => window.__ctl.save()) + saved = await v.waitEvent('save', 2) + expect((await xlsxSheet(fromB64(saved.b64 as string))).cell('J12')).toBe('before rename') + await v.page.evaluate(() => window.__ctl.redo()) + await v.page.waitForFunction(() => window.__ctl.snapshot().canUndo && !window.__ctl.snapshot().canRedo) + await v.page.evaluate(() => window.__ctl.save()) + saved = await v.waitEvent('save', 3) + const reopened = await xlsxSheet(fromB64(saved.b64 as string)) + expect(reopened.names[0]).toBe('Renamed') + expect(reopened.cell('J12')).toBe('after rename') + expect(v.errors).toEqual([]) + }) + test('a newcomer opens the latest snapshot and only replays later edits', async () => { const id = await room('sample.xlsx') const a = await join(id, 'Ann') @@ -148,3 +182,65 @@ describe('docx: a built-in style the document lacks', () => { expect(v.errors).toEqual([]) }) }) + + +for (const control of ['input', 'button'] as const) { + test(`docx: focused host ${control} keeps its formatting target across peer structure and text edits`, async () => { + const id = await room('sample.docx') + const joinDoc = (user: string) => viewer({ src: `${HTTP}/rooms/${id}/file?seq=0`, name: 'shared.docx', collab: `ws://localhost:${PORT}/collab`, room: id, user, base: 0, editable: true, controller: true, onSave: true }) + const a = await joinDoc('Ann') + const b = await joinDoc('Bob') + for (const v of [a, b]) await v.page.locator('.de-collab-live').waitFor({ timeout: 20_000 }) + await b.page.evaluate(() => { + const input = document.createElement('input') + input.id = 'collab-format-input'; input.style.cssText = 'position:fixed;top:30px;left:0;z-index:999999' + document.body.append(input) + for (const [i, command] of [ + { op: 'toggle', mark: 'underline' }, { op: 'size', pt: 31 }, { op: 'color', color: '#00aa00' }, + ].entries()) { + const button = document.createElement('button') + button.id = `collab-format-${i}`; button.textContent = String(i) + button.style.cssText = `position:fixed;top:0;left:${i * 60}px;z-index:999999` + button.onclick = () => window.__ctl.format(command as any) + document.body.append(button) + } + }) + await b.selectText('document') + const commands = [{ op: 'toggle', mark: 'underline' }, { op: 'size', pt: 31 }, { op: 'color', color: '#00aa00' }] + const apply = async (i: number) => { + if (control === 'input') { + await b.page.locator('#collab-format-input').click() + await b.page.evaluate((command) => window.__ctl.format(command as any), commands[i]) + } else if (i === 2) { + await b.page.locator(`#collab-format-${i}`).focus() + await b.page.keyboard.press('Enter') + } else await b.page.locator(`#collab-format-${i}`).click() + await b.page.waitForTimeout(200) + } + await apply(0) + await a.selectText('Quarterly Report', 'start') + await a.page.keyboard.type('Peer prefix') + await a.page.keyboard.press('Enter') + await b.page.waitForFunction(() => document.querySelector('.de-pages')?.textContent?.includes('Peer prefix')) + await b.page.waitForTimeout(300) + expect(await b.page.evaluate(() => window.__ctl.snapshot().format?.underline)).toBe(true) + await apply(1) + await a.selectText('This', 'start') + await a.page.keyboard.type('Zq') + await b.page.waitForFunction(() => document.querySelector('.de-pages')?.textContent?.includes('ZqThis document')) + await b.page.waitForTimeout(300) + await apply(2) + expect(await b.page.evaluate(() => window.__ctl.snapshot().format)).toMatchObject({ underline: true, size: 31, color: '#00aa00' }) + await a.page.waitForTimeout(500) + for (const v of [a, b]) { + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save')).b64 as string) + const p = (await docxParas(bytes)).find((p) => paraText(p).startsWith('ZqThis document'))! + const run = runsOf(p).find((r) => r.text === 'document')! + expect(run.s.u).toBe('single') + expect(run.s.sz).toBe(31) + expect(run.s.color).toMatch(/00aa00/i) + expect(v.errors).toEqual([]) + } + }) +} diff --git a/e2e/components.spec.ts b/e2e/components.spec.ts new file mode 100644 index 0000000..1e7a9da --- /dev/null +++ b/e2e/components.spec.ts @@ -0,0 +1,92 @@ +import { describe, expect, test } from 'bun:test' +import { docxParas, paraText, runsOf, useBrowser, viewer } from './harness' + +useBrowser() + +const open = async (viewport?: { width: number; height: number }) => { + const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true, components: true }, { viewport }) + await v.page.locator('.de-ebar').waitFor() + return v +} + +describe('host UI components', () => { + test('docx: every toolbar button is the host Button, and it keeps the selection for formatting', async () => { + const v = await open() + const counts = await v.page.evaluate(() => { + const bar = document.querySelector('.de-ebar')! + return { + host: bar.querySelectorAll('button[data-host-button]').length, + engine: bar.querySelectorAll('button.de-tb').length, + seps: bar.querySelectorAll('[data-host-sep]').length, + engineSeps: bar.querySelectorAll('.de-tb-sep').length, + } + }) + expect(counts.host).toBeGreaterThan(10) + expect(counts.engine).toBe(0) + expect(counts.seps).toBeGreaterThan(0) + expect(counts.engineSeps).toBe(0) + + await v.selectText('document') + await v.btn('Bold').click() + await v.page.waitForFunction(() => document.querySelector('button[data-host-button][aria-label^="Bold"]')?.hasAttribute('data-active')) + const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text.includes('document'))!.s.b).toBe(true) + expect(v.errors).toEqual([]) + }) + + test('docx: a narrow toolbar still moves what does not fit under the host More button', async () => { + const v = await open({ width: 640, height: 900 }) + const more = v.page.locator('.de-ebar button[data-host-button][aria-label="More tools"]') + await more.waitFor() + // Hosts can use a wide text button: reserve its actual width, not the engine's icon width. + await v.page.waitForFunction(() => { + const bar = document.querySelector('.de-ebar')! + const right = bar.getBoundingClientRect().right + return [...bar.querySelectorAll(':scope > span')].every((el) => el.getBoundingClientRect().right <= right) + }, null, { timeout: 5000 }) + await more.click() + expect(await v.page.locator('.de-ebar-more button[data-host-button]').count()).toBeGreaterThan(0) + expect(v.errors).toEqual([]) + }) + + test('docx: the link prompt is the host Dialog and submits', async () => { + const v = await open() + await v.selectText('document') + await v.page.keyboard.press('Control+k') + const dialog = v.page.locator('[data-host-dialog][role="dialog"]') + await dialog.waitFor() + expect(await v.page.locator('.de-dialog').count()).toBe(0) + await dialog.locator('input').fill('https://example.org/docs') + await v.page.keyboard.press('Enter') + await dialog.waitFor({ state: 'detached' }) + const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text.includes('document'))!.href).toBe('https://example.org/docs') + expect(v.errors).toEqual([]) + }) + + test('docx: the built-in edit-link prompt keeps Remove link on the left and removes the link', async () => { + const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true }) + await v.selectText('document') + await v.page.keyboard.press('Control+k') + const dialog = v.page.locator('.de-dialog') + await dialog.locator('input').fill('https://example.org/docs') + await v.page.keyboard.press('Enter') + await dialog.waitFor({ state: 'detached' }) + await v.selectText('document') + await v.page.keyboard.press('Control+k') + const extra = dialog.locator('button.de-dialog-extra') + await extra.waitFor() + expect(await extra.innerText()).toBe('Remove') + const bounds = await dialog.locator('.de-dialog-btns').evaluate((row) => { + const [extra, cancel] = row.querySelectorAll('button') + return { left: row.getBoundingClientRect().left, extra: extra.getBoundingClientRect().left, gap: cancel.getBoundingClientRect().left - extra.getBoundingClientRect().right } + }) + expect(bounds.extra).toBe(bounds.left) + expect(bounds.gap).toBeGreaterThan(20) + await extra.click() + await dialog.waitFor({ state: 'detached' }) + const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text.includes('document'))!.href).toBeUndefined() + expect(v.errors).toEqual([]) + }) +}) diff --git a/e2e/controller-built.spec.ts b/e2e/controller-built.spec.ts new file mode 100644 index 0000000..00b6ef3 --- /dev/null +++ b/e2e/controller-built.spec.ts @@ -0,0 +1,68 @@ +/** Controller + locale + host UI integration against emitted production modules. */ +import { expect, test } from 'bun:test' +import { fromB64, useBrowser, viewer, xlsxSheet } from './harness' + +import { builtModule, useBuiltPackage } from './built-package' + +useBuiltPackage() +useBrowser() + +test('built controller uses current callbacks across locale/UI updates, replacement and save', async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'de-DE' }) + await v.page.waitForFunction(() => !!(window as any).__builtRuntime) + await v.page.evaluate(async ({ pkg, german }) => { + const { React: R, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + const de = (await import(/* @vite-ignore */ german)).de + if ('InternalViewerController' in api || 'internalController' in api || 'de' in api) throw new Error('private or optional export leaked') + const ctl = api.createViewerController() + const replacement = api.createViewerController() + ctl.subscribe(() => {}) + replacement.subscribe(() => {}) + ;(window as any).__builtControllers = { ctl, replacement } + let current: any = { controller: ctl, locale: 'en-GB' } + let generation = 'first' + function Button(p: any) { + return R.createElement('button', { 'data-built-host': '', 'aria-label': p.title, disabled: p.disabled, onMouseDown: p.onMouseDown, onClick: p.onClick }, p.icon, p.label, p.children) + } + const root = createRoot(document.getElementById('built')!) + function render() { + const callbackGeneration = generation + root.render(R.createElement(api.OfficeUIProvider, { strings: de, components: { Button } }, + R.createElement(api.DocViewer, { src: '/samples/sample.xlsx', editable: true, headless: true, ...current, + onLoad: (c: any) => window.__events.push({ type: 'load', kind: c.kind }), + onError: (e: Error) => window.__events.push({ type: 'error', message: e.message }), + onSave: async (blob: Blob, name: string) => { let raw = ''; for (const b of new Uint8Array(await blob.arrayBuffer())) raw += String.fromCharCode(b); window.__events.push({ type: 'save', name, b64: btoa(raw), generation: callbackGeneration }) }, + }))) + } + ;(window as any).__builtUpdate = (p: any) => { current = { ...current, ...p }; generation = 'updated'; render() } + ;(window as any).__builtUnmount = () => root.unmount() + render() + }, { pkg: builtModule('index.js'), german: builtModule('locales/de.js') }) + await v.ready('xlsx') + await v.page.locator('button[data-built-host][aria-label^="Fett"]').waitFor() + await v.page.waitForFunction(() => (window as any).__builtControllers.ctl.snapshot().status.includes('Zeilen')) + await v.typeCell('J12', 'production integration') + await v.page.waitForFunction(() => (window as any).__builtControllers.ctl.snapshot().canUndo) + await v.page.evaluate(() => (window as any).__builtUpdate({ locale: 'vi-VN' })) + await v.page.evaluate(() => { const { undo } = (window as any).__builtControllers.ctl; undo() }) + await v.page.waitForFunction(() => (window as any).__builtControllers.ctl.snapshot().canRedo) + expect(await v.shown('J12')).toBe('') + await v.page.evaluate(() => { const { redo } = (window as any).__builtControllers.ctl; redo() }) + await v.page.waitForFunction(() => (window as any).__builtControllers.ctl.snapshot().canUndo) + await v.page.evaluate(() => (window as any).__builtControllers.ctl.save()) + const saved = await v.waitEvent('save') + expect(saved.generation).toBe('updated') + expect((await xlsxSheet(fromB64(saved.b64 as string))).cell('J12')).toBe('production integration') + await v.page.evaluate(() => (window as any).__builtUpdate({ controller: (window as any).__builtControllers.replacement })) + await v.page.waitForFunction(() => { + const { ctl, replacement } = (window as any).__builtControllers + return ctl.snapshot().kind === null && replacement.snapshot().kind === 'xlsx' && replacement.snapshot().outline?.items.length > 0 + }) + await v.page.evaluate(() => (window as any).__builtControllers.replacement.goto('1')) + await v.page.waitForFunction(() => (window as any).__builtControllers.replacement.snapshot().outline.items[1].current) + expect(await v.events('load')).toHaveLength(1) + await v.page.evaluate(() => (window as any).__builtUnmount()) + expect(await v.page.evaluate(() => (window as any).__builtControllers.replacement.snapshot().kind)).toBeNull() + expect(v.errors).toEqual([]) +}) diff --git a/e2e/controller.spec.ts b/e2e/controller.spec.ts new file mode 100644 index 0000000..47fda69 --- /dev/null +++ b/e2e/controller.spec.ts @@ -0,0 +1,485 @@ +import { describe, expect, test } from 'bun:test' +import type { ViewerController, ViewerState } from '../src' +import { docxBlocks, docxParas, paraText, runsOf, fromB64, useBrowser, viewer, xlsxSheet, type Viewer } from './harness' + +useBrowser() + +const state = (v: Viewer) => v.page.evaluate(() => window.__ctl.snapshot()) as Promise +/** waits until the controller's state passes `check` (run in the page) */ +const until = (v: Viewer, check: string) => v.page.waitForFunction(`(() => { const s = window.__ctl.snapshot(); return ${check} })()`, null, { timeout: 15_000 }) + +type HistoryMethod = 'xlsx.set' | 'xlsx.undo' | 'xlsx.redo' +declare global { + interface Window { + __xlsxHistory: { hold: HistoryMethod | null; release: (() => void) | null; publications: ViewerState[] } + __oldHistoryController: ViewerController + } +} + +/** Hold a real worker response after the mutation, before the grid can apply it. */ +async function delayedXlsx() { + const v = await viewer({ controller: true, editable: true, headless: true, onSave: true }, { wait: false }) + await v.page.evaluate(() => window.__setProps({ + src: 'samples/sample.xlsx', + onLoad: (client) => { + window.__xlsxHistory = { hold: null, release: null, publications: [] } + const call = client.call.bind(client) + client.call = async (method, ...args) => { + const result = await call(method, ...args) + if (method === window.__xlsxHistory.hold) { + window.__xlsxHistory.hold = null + await new Promise((resolve) => { window.__xlsxHistory.release = resolve }) + } + return result + } + }, + })) + await v.page.locator('.de-grid').waitFor() + await until(v, "s.kind === 'xlsx' && s.editing") + return v +} + +async function holdHistory(v: Viewer, method: HistoryMethod) { + await v.page.evaluate((method) => { + window.__xlsxHistory.hold = method + window.__xlsxHistory.release = null + }, method) +} + +async function pendingHistory(v: Viewer) { + await v.page.waitForFunction(() => !!window.__xlsxHistory.release) +} + +async function saveXlsx(v: Viewer) { + const count = (await v.events('save')).length + await v.page.evaluate(() => window.__ctl.save()) + const saved = await v.waitEvent('save', count + 1) + return xlsxSheet(fromB64(saved.b64 as string)) +} + +describe('controller and headless mode', () => { + test('docx: zoom, pages and headings through the controller; no chrome of its own', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', headless: true }) + const { page } = v + expect(await page.locator('.de-bar').count()).toBe(0) + expect(await page.locator('.de-zoom').count()).toBe(0) + expect(await page.locator('.de-outline-toggle').count()).toBe(0) + + await until(v, "s.kind === 'docx' && s.page && s.page.count > 0 && s.outline && s.outline.items.length > 0") + const s = await state(v) + expect(s.zoom?.value).toBe('fit') + expect(s.status).toMatch(/Page 1 of \d+/) + expect(s.outline?.kind).toBe('headings') + expect(s.outline?.items.map((i) => i.title)).toContain('1. Highlights') + + // a heading further down: the view scrolls there and marks it current + const table = s.outline!.items.find((i) => /Table/.test(i.title))! + await page.evaluate((id) => window.__ctl.goto(id), table.id) + await until(v, `s.outline.items.find((i) => i.id === ${JSON.stringify(table.id)}).current`) + + // zoom in widens the page + const w0 = (await page.locator('.de-page').first().boundingBox())!.width + await page.evaluate(() => window.__ctl.zoomIn()) + await until(v, "typeof s.zoom.value === 'number'") + await page.waitForTimeout(200) + expect((await page.locator('.de-page').first().boundingBox())!.width).toBeGreaterThan(w0) + expect(v.errors).toEqual([]) + }) + + test('an overlapping viewer survives the old viewer unmounting', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', headless: true }) + await v.page.evaluate(() => window.__overlap(1)) + await v.waitEvent('load', 2) + await until(v, "s.kind === 'docx' && s.zoom && s.page && s.page.count > 0") + await v.page.evaluate(() => window.__overlap(2)) + await v.page.evaluate(() => window.__ctl.setZoom(1.25)) + await until(v, 's.kind === "docx" && s.zoom.value === 1.25') + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.editing') + expect(v.errors).toEqual([]) + }) + + for (const kind of ['docx', 'xlsx', 'pptx'] as const) { + test(`StrictMode loading overlap: late docx cannot steal the newer ${kind} controller`, async () => { + const v = await viewer({ controller: true, headless: true, editable: true, strict: true, onSave: true }, { wait: false }) + let oldRequest: import('playwright-core').Route | undefined + await v.page.route('**/slow-old.docx', (route) => { oldRequest = route }) + await v.page.waitForFunction(() => !!window.__setProps) + await v.page.evaluate(() => window.__setProps({ src: 'samples/slow-old.docx' })) + await v.page.waitForFunction(() => window.__ctl.snapshot().loading) + for (let i = 0; !oldRequest && i < 50; i++) await v.page.waitForTimeout(10) + expect(oldRequest).toBeDefined() + await v.page.evaluate((kind) => window.__overlap(1, { src: `samples/sample.${kind}` }), kind) + await v.waitEvent('load') + await until(v, `s.kind === '${kind}' && !s.loading && s.outline && s.outline.items.length > 0`) + await oldRequest!.fulfill({ path: process.cwd() + '/playground/public/samples/sample.docx' }) + await v.waitEvent('load', 2) + await v.page.locator('.de-pages').first().waitFor() + await v.page.evaluate(() => window.__overlap(2)) + await v.page.waitForTimeout(200) + expect((await state(v)).kind).toBe(kind) + if (kind === 'xlsx') { + expect(await state(v)).toMatchObject({ zoom: null, page: null }) + await v.page.evaluate(() => window.__ctl.goto(window.__ctl.snapshot().outline!.items[1].id)) + await until(v, 's.outline.items[1].current') + await v.typeCell('J12', 'new viewer') + await until(v, 's.canUndo') + await v.page.evaluate(() => window.__ctl.undo()) + await until(v, 's.canRedo') + expect(await v.shown('J12')).toBe('') + } else { + await v.page.evaluate(() => { const { setZoom, gotoPage } = window.__ctl; setZoom(1.25); gotoPage(2) }) + await until(v, 's.zoom.value === 1.25 && s.page.current === 2') + } + expect(v.errors).toEqual([]) + }) + } + + test('bound React callbacks and destructured commands mutate and save the document', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', headless: true, editable: true, onSave: true, hostControls: true }) + await v.typeCell('J12', 'bound callback') + await until(v, 's.canUndo') + await v.page.getByRole('button', { name: 'Host undo', exact: true }).click() + await until(v, 's.canRedo && !s.canUndo') + expect((await saveXlsx(v)).cell('J12')).toBe('') + await v.page.getByRole('button', { name: 'Host redo', exact: true }).click() + await until(v, 's.canUndo') + expect((await saveXlsx(v)).cell('J12')).toBe('bound callback') + expect(v.errors).toEqual([]) + }) + + for (const editable of [false, true]) for (const allowEdit of [false, true]) { + test(`editable=${editable}, allowEdit=${allowEdit}: toggle visibility and actual edits remain independent`, async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', editable, allowEdit, onSave: true }) + await until(v, 's.kind === "xlsx" && !s.loading') + expect((await state(v)).editing).toBe(editable) + expect((await state(v)).canEdit).toBe(true) + expect(await v.barButton(editable ? 'View' : 'Edit').count()).toBe(allowEdit ? 1 : 0) + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.editing') + await v.typeCell('J12', 'editable without toggle') + await until(v, 's.canUndo && s.dirty') + expect((await saveXlsx(v)).cell('J12')).toBe('editable without toggle') + await v.page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && !s.canUndo') + await v.page.evaluate(() => window.__ctl.undo()) + expect((await saveXlsx(v)).cell('J12')).toBe('editable without toggle') + expect(v.errors).toEqual([]) + }) + } + + test('DOCX editable with a hidden toggle: edit, clamp zoom and save/reopen', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', editable: true, allowEdit: false, onSave: true }) + await until(v, 's.editing && s.canEdit') + expect(await v.barButton('View').count()).toBe(0) + await v.selectText('Quarterly Report', 'end') + await v.page.keyboard.type(' hidden-toggle-proof') + await until(v, 's.dirty && s.canUndo') + await v.page.evaluate(() => window.__ctl.save()) + const saved = await v.waitEvent('save') + expect(JSON.stringify(await docxBlocks(fromB64(saved.b64 as string)))).toContain('hidden-toggle-proof') + await v.page.evaluate(() => { const { setZoom } = window.__ctl; setZoom(0) }) + await until(v, 's.zoom.value === 0.25') + await v.page.evaluate(() => { const { setZoom, zoomIn } = window.__ctl; setZoom(NaN); zoomIn() }) + await until(v, 's.zoom.value > 0.25') + await v.page.evaluate(() => window.__ctl.setZoom(150)) + await until(v, 's.zoom.value === 3') + expect(v.errors).toEqual([]) + }) + + test('host outline mouse-down preserves an open cross-sheet formula', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', headless: true, editable: true, onSave: true, hostControls: true }) + await v.clickCell('J12') + await v.page.keyboard.type('=SUM(') + await v.page.getByRole('button', { name: 'Host second sheet', exact: true }).click() + await until(v, 's.outline.items[1].current') + await v.clickCell('A1') + await v.page.keyboard.press('Enter') + await until(v, 's.canUndo && s.dirty') + const saved = await saveXlsx(v) + const detail = await saved.engine.call('xlsx.cell', [0, 11, 9]) as { formula?: string } + expect(detail.formula).toMatch(/^=SUM\(Notes!A1\)$/) + expect(v.errors).toEqual([]) + }) + + test('CSV import remains available when Open is disabled; no-document dialogs do not latch', async () => { + const v = await viewer({ controller: true, allowOpen: false, onSave: true }, { wait: false }) + await v.page.waitForFunction(() => !!window.__setProps) + await v.page.evaluate(() => { window.__ctl.fileAction('rename'); window.__ctl.fileAction('details') }) + await v.page.evaluate(() => window.__setProps({ src: 'samples/sample.xlsx' })) + await v.ready('xlsx') + expect(await v.page.getByRole('dialog').count()).toBe(0) + expect(await v.menuLabels()).toContain('Import CSV into new sheet…') + const chooser = v.page.waitForEvent('filechooser') + await v.page.evaluate(() => window.__ctl.fileAction('import')) + await (await chooser).setFiles({ name: 'imported.csv', mimeType: 'text/csv', buffer: Buffer.from('imported,value\nproof,42') }) + await until(v, 's.outline.items.some(i => i.title === "imported")') + const saved = await v.events('save') + await saveXlsx(v) + const imported = await v.waitEvent('save', saved.length + 1) + expect((await xlsxSheet(fromB64(imported.b64 as string), 1)).cell('B2')).toBe('42') + expect(v.errors).toEqual([]) + }) + + test('docx: editing and saving through the controller', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', headless: true, onSave: true }) + const { page } = v + await until(v, 's.canEdit') + await page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.editing') + // the formatting toolbar keeps its row in a headless viewer, without the outline button + await page.locator('.de-ebar').waitFor() + expect(await page.locator('.de-ebar [title="Document outline"]').count()).toBe(0) + await page.evaluate(() => window.__ctl.save()) + const saved = await v.waitEvent('save') + expect(saved.name).toBe('sample.docx') + await page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing') + expect(v.errors).toEqual([]) + }) + + test('docx: undo is offered only while editing', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', headless: true }) + await until(v, 's.canEdit') + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.editing') + await v.selectText('Quarterly Report', 'end') + await v.page.keyboard.type('!!') + await until(v, 's.canUndo') + await v.page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && !s.canUndo && !s.canRedo') + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.editing && s.canUndo') + expect(v.errors).toEqual([]) + }) + + test('docx: formatting state and commands through the controller', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', editable: true, onSave: true, headless: true }) + const { page } = v + await until(v, 's.editing') + await v.selectText('document') + await until(v, 's.format && !s.format.bold') + await page.evaluate(() => window.__ctl.format({ op: 'toggle', mark: 'bold' })) + await until(v, 's.format.bold') + await page.evaluate(() => window.__ctl.format({ op: 'size', pt: 20 })) + await until(v, 's.format.size === 20') + // headless: no Save button, the host saves through the controller + await page.evaluate(() => window.__ctl.save()) + const saved = await v.waitEvent('save') + const p = (await docxParas(fromB64(saved.b64 as string))).find((x) => paraText(x).startsWith('This document'))! + const run = runsOf(p).find((r) => r.text.includes('document'))! + expect(run.s.b).toBe(true) + expect(run.s.sz).toBe(20) + // viewing: no formatting state, and commands do nothing + await page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && s.format === null') + expect(v.errors).toEqual([]) + }) + + test("xlsx: the active cell's format through the controller", async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', editable: true, onSave: true, headless: true }) + const { page } = v + await page.locator('.de-grid').waitFor() + await v.typeCell('J10', '12.5') + await v.clickCell('J10') + await until(v, 's.format && !s.format.bold && s.format.list === undefined') + await page.evaluate(() => window.__ctl.format({ op: 'toggle', mark: 'bold' })) + await page.evaluate(() => window.__ctl.format({ op: 'highlight', color: '#ffff00' })) + await until(v, "s.format.bold && /255, 255, 0|ffff00/i.test(s.format.highlight ?? '')") + // lists are not a cell format: nothing happens + await page.evaluate(() => window.__ctl.format({ op: 'list', list: 'bullet' })) + + // viewing: undo is not offered and does not change the workbook + await until(v, 's.canUndo') + await page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && !s.canUndo && s.format === null') + await page.evaluate(() => window.__ctl.undo()) + await page.waitForTimeout(300) + await page.evaluate(() => window.__ctl.setEditing(true)) + await v.clickCell('J10') + // the fill was the last edit: it is still there + await until(v, "s.format && /255, 255, 0|ffff00/i.test(s.format.highlight ?? '') && s.canUndo") + expect(v.errors).toEqual([]) + }) + + test('xlsx: the sheets as the outline, no tabs of its own', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', headless: true }) + const { page } = v + expect(await page.locator('.de-tabs').isVisible()).toBe(false) + await until(v, "s.kind === 'xlsx' && s.outline && s.outline.kind === 'sheets'") + const s = await state(v) + expect(s.zoom).toBeNull() + expect(s.outline!.items.map((i) => i.title)).toEqual(['Sales', 'Notes', 'Data']) + expect(s.outline!.items[0].current).toBe(true) + await page.evaluate((id) => window.__ctl.goto(id), s.outline!.items[1].id) + await until(v, 's.outline.items[1].current') + expect(v.errors).toEqual([]) + }) + + test('xlsx: history cannot mutate a workbook outside editing', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', editable: true, headless: true }) + await v.typeCell('J12', 'history') + await until(v, 's.canUndo') + await v.page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && !s.canUndo && !s.canRedo') + await v.page.evaluate(() => { window.__ctl.undo(); window.__ctl.redo() }) + expect(await v.shown('J12')).toBe('history') + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.canUndo') + await v.page.evaluate(() => window.__ctl.undo()) + await until(v, 's.canRedo') + expect(await v.shown('J12')).toBe('') + }) + + test('xlsx: a delayed edit publishes history to the replacement controller only', async () => { + const v = await delayedXlsx() + await holdHistory(v, 'xlsx.set') + await v.clickCell('J12') + await v.page.keyboard.type('pending edit') + await v.page.keyboard.press('Enter') + await pendingHistory(v) + await v.page.evaluate(async (path) => { + const { createViewerController } = await import(path) + window.__oldHistoryController = window.__ctl + window.__ctl = createViewerController() + window.__ctl.subscribe(() => {}) + window.__setProps({ controller: window.__ctl }) + }, '/@fs/' + process.cwd() + '/src/index.ts') + await until(v, "s.kind === 'xlsx' && s.editing") + const detached = await v.page.evaluate(() => window.__oldHistoryController.snapshot()) + expect(detached).toMatchObject({ kind: null, editing: false, canUndo: false, canRedo: false }) + await v.page.evaluate(() => window.__xlsxHistory.release!()) + await until(v, 's.dirty && s.canUndo') + expect(await v.page.evaluate(() => window.__oldHistoryController.snapshot())).toEqual(detached) + expect((await saveXlsx(v)).cell('J12')).toBe('pending edit') + await v.page.evaluate(() => window.__ctl.undo()) + await until(v, 's.canRedo && !s.canUndo') + expect((await saveXlsx(v)).cell('J12')).toBe('') + expect(v.errors).toEqual([]) + }) + + for (const method of ['xlsx.set', 'xlsx.undo', 'xlsx.redo'] as const) { + test(`xlsx: delayed ${method} completion respects the current edit gate`, async () => { + const v = await delayedXlsx() + if (method !== 'xlsx.set') { + await v.typeCell('J12', 'pending history') + await until(v, 's.canUndo') + if (method === 'xlsx.redo') { + await v.page.evaluate(() => window.__ctl.undo()) + await until(v, 's.canRedo && !s.canUndo') + } + await saveXlsx(v) + await until(v, '!s.dirty') + } + await holdHistory(v, method) + if (method === 'xlsx.set') { + await v.clickCell('J12') + await v.page.keyboard.type('pending history') + await v.page.keyboard.press('Enter') + } else await v.page.evaluate((method) => method === 'xlsx.undo' ? window.__ctl.undo() : window.__ctl.redo(), method) + await pendingHistory(v) + await v.page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && !s.canUndo && !s.canRedo') + await v.page.evaluate(() => { + window.__ctl.subscribe(() => window.__xlsxHistory.publications.push(window.__ctl.snapshot())) + window.__xlsxHistory.release!() + }) + // Dirty is published by the mounted workbook after the held response resumes; this waits for completion. + await until(v, 's.dirty') + expect(await state(v)).toMatchObject({ editing: false, canUndo: false, canRedo: false }) + expect(await v.page.evaluate(() => window.__xlsxHistory.publications.some((s) => s.canUndo || s.canRedo))).toBe(false) + expect((await saveXlsx(v)).cell('J12')).toBe(method === 'xlsx.undo' ? '' : 'pending history') + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, method === 'xlsx.undo' ? 's.canRedo && !s.canUndo' : 's.canUndo && !s.canRedo') + expect(v.errors).toEqual([]) + }) + } + + for (const replacement of ['docx', 'xlsx'] as const) test(`xlsx: an unmounted view cannot publish delayed dirty/history over replacement ${replacement}`, async () => { + const v = await delayedXlsx() + await holdHistory(v, 'xlsx.set') + await v.clickCell('J12') + await v.page.keyboard.type('old workbook') + await v.page.keyboard.press('Enter') + await pendingHistory(v) + await v.page.evaluate((kind) => window.__setProps({ src: `samples/sample.${kind}?replacement=1`, onLoad: () => window.__events.push({ type: 'replacement-load' }) }), replacement) + await v.waitEvent('replacement-load') + await until(v, `s.kind === '${replacement}' && !s.loading && !s.dirty && !s.canUndo && !s.canRedo`) + await v.page.evaluate(async () => { + window.__ctl.subscribe(() => window.__xlsxHistory.publications.push(window.__ctl.snapshot())) + window.__xlsxHistory.release!() + // The response continuation runs in microtasks before the next frame, even though its grid is gone. + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + }) + expect(await v.page.evaluate(() => window.__xlsxHistory.publications.some((s) => s.canUndo || s.canRedo))).toBe(false) + expect(await state(v)).toMatchObject({ kind: replacement, dirty: false, canUndo: false, canRedo: false }) + if (replacement === 'xlsx') expect((await saveXlsx(v)).cell('J12')).toBe('') + expect(v.errors).toEqual([]) + }) + + test('fully unmounted viewer rejects delayed completion and keeps empty defaults', async () => { + const v = await delayedXlsx() + await holdHistory(v, 'xlsx.set') + await v.clickCell('J12') + await v.page.keyboard.type('unmounted') + await v.page.keyboard.press('Enter') + await pendingHistory(v) + await v.page.evaluate(() => window.__overlap(3)) + await until(v, 's.kind === null && !s.dirty && !s.canUndo') + const detached = await state(v) + await v.page.evaluate(async () => { + window.__xlsxHistory.release!() + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + }) + expect(await state(v)).toEqual(detached) + expect(v.errors).toEqual([]) + }) + + test('controller file actions enforce permissions even with the menu hidden', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', fileMenu: false, allowOpen: false, allowEdit: false, editable: true, allowSave: false, allowDownload: false, onSave: true }) + const pickers: string[] = [], downloads: string[] = [] + v.page.on('filechooser', () => pickers.push('picker')) + v.page.on('download', () => downloads.push('download')) + await v.page.evaluate(() => { + for (const id of ['new:docx', 'new:invalid', 'open', 'import', 'save', 'original', 'pdf', 'print']) window.__ctl.fileAction(id) + window.__ctl.setEditing(true) + }) + await v.page.waitForTimeout(300) + expect(pickers).toEqual([]) + expect(downloads).toEqual([]) + expect(await v.events('save')).toEqual([]) + expect((await state(v)).editing).toBe(true) + expect((await state(v)).kind).toBe('xlsx') + await v.page.evaluate(() => window.__setProps({ allowDownload: true })) + const dl = await v.download(() => v.page.evaluate(() => window.__ctl.fileAction('text:csv'))) + expect(dl.name).toBe('sample.csv') + expect(v.errors).toEqual([]) + }) + + test('pptx: slides, zoom and the slide in view; no thumbnails, zoom or Present button', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.pptx', headless: true }) + const { page } = v + expect(await page.locator('.de-thumbs').count()).toBe(0) + expect(await page.locator('.de-zoom').count()).toBe(0) + expect(await page.locator('.de-present-btn').count()).toBe(0) + await until(v, "s.kind === 'pptx' && s.page && s.outline && s.outline.kind === 'slides'") + const s = await state(v) + expect(s.page!.current).toBe(1) + expect(s.outline!.items.length).toBe(s.page!.count) + await page.evaluate(() => window.__ctl.gotoPage(3)) + await until(v, 's.page.current === 3') + // slide titles arrive from the slides' title placeholders + await until(v, "s.outline.items.some((i) => !/^Slide \\d+$/.test(i.title))") + expect(v.errors).toEqual([]) + }) + + test('with chrome: the controller still follows the view', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx' }) + const { page } = v + expect(await page.locator('.de-bar').count()).toBe(1) + await until(v, "s.kind === 'docx' && s.zoom") + await page.locator('button[aria-label="Zoom in"]').click() + await until(v, "typeof s.zoom.value === 'number'") + expect(v.errors).toEqual([]) + }) +}) diff --git a/e2e/embed.spec.ts b/e2e/embed.spec.ts index d7d38f3..2a59833 100644 --- a/e2e/embed.spec.ts +++ b/e2e/embed.spec.ts @@ -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([]) + }) }) diff --git a/e2e/format-built.spec.ts b/e2e/format-built.spec.ts new file mode 100644 index 0000000..6f63bd7 --- /dev/null +++ b/e2e/format-built.spec.ts @@ -0,0 +1,182 @@ +/** Host formatting through the emitted library and real worker, including save/reopen. */ +import { expect, test } from 'bun:test' +import { strFromU8, unzipSync } from 'fflate' +import { docxParas, fromB64, paraText, runsOf, useBrowser, viewer, xlsxSheet, type Viewer } from './harness' + +import { builtModule, useBuiltPackage } from './built-package' + +useBuiltPackage() +useBrowser() + +async function select(v: Viewer, kind: 'docx' | 'xlsx' | 'pptx') { + if (kind === 'xlsx') await v.clickCell('B2') + else if (kind === 'docx') await v.selectText('document') + else { + await v.page.locator('.de-slide-frame').first().getByText('office-engine', { exact: true }).click() + await v.page.locator('.de-txt-edit').waitFor() + await v.page.keyboard.press('ControlOrMeta+a') + } + await v.page.waitForTimeout(150) +} + +for (const kind of ['docx', 'xlsx', 'pptx'] as const) { + test(`built ${kind}: inline React host formatting preserves focus, history and saved/reopened values`, async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false }) + await v.page.waitForFunction(() => !!(window as any).__builtRuntime) + await v.page.evaluate(async ({ pkg, kind }) => { + const { React: R, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + const ctl = api.createViewerController() + window.__ctl = ctl + const root = createRoot(document.getElementById('built')!) + function Host() { + const f = api.useViewerState(ctl).format + const [props, setProps] = R.useState({ src: `/samples/sample.${kind}`, name: `sample.${kind}` }) + window.__setProps = (p: any) => setProps((old: any) => ({ ...old, ...p })) + return R.createElement(R.Fragment, null, + R.createElement('input', { 'aria-label': 'Production size', type: 'number', disabled: !f, + onChange: (e: any) => ctl.format({ op: 'size', pt: e.currentTarget.valueAsNumber }) }), + R.createElement('button', { 'aria-label': 'Production undo', onClick: ctl.undo }, 'Undo'), + R.createElement(api.DocViewer, { ...props, controller: ctl, editable: true, headless: true, + onLoad: (c: any) => window.__events.push({ type: 'load', kind: c.kind }), + onError: (e: Error) => window.__events.push({ type: 'error', message: e.message }), + onSave: async (blob: Blob, name: string) => { + let raw = '' + for (const b of new Uint8Array(await blob.arrayBuffer())) raw += String.fromCharCode(b) + window.__events.push({ type: 'save', name, b64: btoa(raw) }) + }, + })) + } + root.render(R.createElement(Host)) + }, { pkg: builtModule('index.js'), kind }) + await v.ready(kind) + const cellBefore = kind === 'xlsx' ? await v.shown('B2') : undefined + const inputBefore = kind === 'xlsx' ? await v.formula('B2') : undefined + await select(v, kind) + const input = v.page.getByLabel('Production size', { exact: true }) + await input.click() + await v.page.keyboard.type('14', { delay: 120 }) + await v.page.waitForTimeout(200) + expect(await input.inputValue()).toBe('14') + expect(await input.evaluate((el) => el === document.activeElement)).toBe(true) + await v.page.keyboard.press('Backspace') + await v.page.waitForTimeout(150) + expect(await input.inputValue()).toBe('1') + expect(await input.evaluate((el) => el === document.activeElement)).toBe(true) + await v.page.keyboard.type('4') + await v.page.waitForTimeout(150) + expect(await v.page.evaluate(() => window.__ctl.snapshot().format?.size)).toBe(14) + await v.page.getByLabel('Production undo', { exact: true }).click() + await v.page.waitForTimeout(150) + expect(await v.page.evaluate(() => window.__ctl.snapshot().format?.size)).toBe(1) + if (kind !== 'xlsx') expect(await v.page.evaluate(() => document.activeElement?.matches('.de-pages, .de-txt-edit'))).toBe(true) + await v.page.evaluate(() => window.__ctl.redo()) + await v.page.waitForTimeout(150) + expect(await v.page.evaluate(() => window.__ctl.snapshot().format?.size)).toBe(14) + // Main's save flush must include the last PPTX command without waiting for the text debounce. + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save')).b64 as string) + const part = kind === 'docx' ? 'word/document.xml' : kind === 'pptx' ? 'ppt/slides/slide1.xml' : 'xl/styles.xml' + const xml = strFromU8(unzipSync(bytes)[part]) + expect(xml).toContain(kind === 'docx' ? 'w:sz w:val="28"' : kind === 'pptx' ? 'sz="1400"' : 'val="14"') + if (kind === 'docx') { + const p = (await docxParas(bytes)).find((p) => paraText(p).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text === 'document')?.s.sz).toBe(14) + } + if (kind === 'xlsx') expect((await xlsxSheet(bytes)).cell('B2')).toBe(cellBefore!) + await v.page.evaluate((data) => window.__setProps({ src: new Blob([new Uint8Array(data)]), name: 'reopened.' + window.__ctl.snapshot().kind }), Array.from(bytes)) + await v.waitEvent('load', 2) + await v.page.waitForTimeout(300) + await select(v, kind) + expect(await v.page.evaluate(() => window.__ctl.snapshot().format?.size)).toBe(14) + if (kind === 'xlsx') expect(await v.formula('B2')).toBe(inputBefore!) + if (kind !== 'xlsx') { + await v.page.evaluate(() => { + const root = document.getElementById('built')! + const wrapper = document.createElement('div') + wrapper.id = 'focusable-app'; wrapper.tabIndex = -1 + root.before(wrapper); wrapper.append(root) + const text = document.createElement('p') + text.textContent = 'Host page background' + text.style.cssText = 'position:fixed;top:0;right:0;z-index:999999;background:white' + wrapper.append(text) + }) + await v.page.getByText('Host page background', { exact: true }).click() + expect(await v.page.evaluate(() => document.activeElement?.id)).toBe('focusable-app') + await v.page.waitForFunction(() => window.__ctl.snapshot().format === null, null, { timeout: 3000 }) + await v.page.evaluate(() => window.__ctl.format({ op: 'toggle', mark: 'italic' })) + expect(await v.page.evaluate(() => window.__ctl.snapshot().dirty)).toBe(false) + } + expect(v.errors).toEqual([]) + }) +} + +for (const keyboard of [false, true]) { + test(`built DOCX: consecutive commands from ${keyboard ? 'keyboard-activated' : 'plain mouse'} host buttons keep the selected text`, async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false }) + await v.page.waitForFunction(() => !!(window as any).__builtRuntime) + await v.page.evaluate(async ({ pkg, keyboard }) => { + const { React: R, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + const ctl = api.createViewerController() + window.__ctl = ctl + const root = createRoot(document.getElementById('built')!) + function Host() { + const f = api.useViewerState(ctl).format + const [props, setProps] = R.useState({ src: '/samples/sample.docx', name: 'sample.docx' }) + window.__setProps = (p: any) => setProps((old: any) => ({ ...old, ...p })) + const commands = [ + { op: 'toggle', mark: 'underline' }, + { op: 'size', pt: 30 }, + { op: 'color', color: '#00aa00' }, + ] + return R.createElement(R.Fragment, null, + ...commands.map((c, i) => R.createElement('button', { + key: i, 'aria-label': `Host command ${i}`, disabled: !f, + 'aria-pressed': i === 0 ? !!f?.underline : undefined, + onMouseDown: keyboard ? (e: any) => e.preventDefault() : undefined, + onClick: () => ctl.format(c), + }, String(i))), + R.createElement(api.DocViewer, { ...props, controller: ctl, editable: true, headless: true, + onLoad: (c: any) => window.__events.push({ type: 'load', kind: c.kind }), + onSave: async (blob: Blob) => { + let raw = '' + for (const b of new Uint8Array(await blob.arrayBuffer())) raw += String.fromCharCode(b) + window.__events.push({ type: 'save', b64: btoa(raw) }) + }, + })) + } + root.render(R.createElement(Host)) + }, { pkg: builtModule('index.js'), keyboard }) + await v.ready('docx') + await select(v, 'docx') + if (keyboard) await v.page.getByLabel('Host command 0', { exact: true }).focus() + for (let i = 0; i < 3; i++) { + const button = v.page.getByLabel(`Host command ${i}`, { exact: true }) + if (keyboard) { + if (i) await v.page.keyboard.press('Tab') + for (let press = 0; press < (i === 0 ? 3 : 1); press++) { + await v.page.keyboard.press('Enter') + await v.page.waitForTimeout(100) + if (i === 0) expect(await button.getAttribute('aria-pressed')).toBe(press % 2 ? 'false' : 'true') + } + } else await button.click() + await v.page.waitForTimeout(150) + expect(await button.evaluate((el) => el === document.activeElement)).toBe(true) + expect(await v.page.getByLabel('Host command 0', { exact: true }).getAttribute('aria-pressed')).toBe('true') + } + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save')).b64 as string) + const p = (await docxParas(bytes)).find((p) => paraText(p).startsWith('This document'))! + const run = runsOf(p).find((r) => r.text === 'document')! + expect(run.s.u).toBe('single') + expect(run.s.sz).toBe(30) + expect(run.s.color).toMatch(/00aa00/i) + await v.page.evaluate((data) => window.__setProps({ src: new Blob([new Uint8Array(data)]), name: 'reopened.docx' }), Array.from(bytes)) + await v.waitEvent('load', 2) + await v.page.locator('.de-pages [data-pa]').filter({ hasText: 'This document' }).first().waitFor() + await select(v, 'docx') + expect(await v.page.evaluate(() => window.__ctl.snapshot().format)).toMatchObject({ underline: true, size: 30 }) + expect(v.errors).toEqual([]) + }) +} diff --git a/e2e/format-controls.spec.ts b/e2e/format-controls.spec.ts new file mode 100644 index 0000000..a29f276 --- /dev/null +++ b/e2e/format-controls.spec.ts @@ -0,0 +1,364 @@ +import { strFromU8, unzipSync } from 'fflate' +import { expect, test } from 'bun:test' +import { docxParas, fromB64, openFile, xlsxSheet, paraText, runsOf, useBrowser, viewer, type Viewer } from './harness' + +useBrowser() +const state = (v: Viewer) => v.page.evaluate(() => window.__ctl.snapshot()) +const settle = (v: Viewer) => v.page.waitForTimeout(150) +const formatting = (s: Awaited>) => ({ format: s.format, dirty: s.dirty, canUndo: s.canUndo, canRedo: s.canRedo }) + +async function selectTarget(v: Viewer, kind: 'docx' | 'pptx', index = 0) { + if (kind === 'docx' && index === 0) return v.selectText('document') + if (kind === 'docx') { + await v.page.evaluate((i) => { + const root = document.querySelectorAll('.de-pages')[i] + root.focus() + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT) + for (let n = walker.nextNode(); n; n = walker.nextNode()) { + const start = n.textContent!.indexOf('document') + if (start < 0) continue + const range = document.createRange() + range.setStart(n, start) + range.setEnd(n, start + 8) + getSelection()!.removeAllRanges() + getSelection()!.addRange(range) + break + } + }, index) + } else { + await v.page.locator('.de-main').nth(index).locator('.de-slide-frame').first().getByText('office-engine', { exact: true }).click() + await v.page.locator('.de-txt-edit').waitFor() + await v.page.keyboard.press('ControlOrMeta+a') + } + await settle(v) +} + +for (const kind of ['docx', 'pptx'] as const) { + test(`${kind}: live host inputs retain the target, focus and text selection; saved size is 25`, async () => { + const v = await viewer({ controller: true, src: `samples/sample.${kind}`, editable: true, headless: true, onSave: true }) + await selectTarget(v, kind) + expect((await state(v)).format).not.toBeNull() + await v.page.evaluate(() => { + for (const type of ['number', 'text']) { + const input = document.createElement('input') + input.id = `host-${type}` + input.type = type + input.value = type === 'number' ? '14' : 'Calibri' + input.style.cssText = `position:fixed;top:0;left:${type === 'text' ? 220 : 0}px;z-index:999999;background:white` + input.addEventListener('input', () => window.__ctl.format(type === 'number' ? { op: 'size', pt: Number(input.value) } : { op: 'font', name: input.value })) + const sync = () => { input.disabled = !window.__ctl.snapshot().format } + window.__ctl.subscribe(sync) + sync() + document.body.append(input) + } + }) + for (const type of ['number', 'text']) { + const input = v.page.locator(`#host-${type}`) + await input.click() + await input.selectText() + await settle(v) + expect(await input.isEnabled()).toBe(true) + expect((await state(v)).format).not.toBeNull() + const value = type === 'number' ? '25' : 'Arial' + await v.page.keyboard.type(value, { delay: 200 }) + await settle(v) + expect(await input.inputValue()).toBe(value) + expect(await input.evaluate((el) => el === document.activeElement)).toBe(true) + expect((await state(v)).format?.size).toBe(25) + if (type === 'text') { + expect((await state(v)).format?.font).toBe('Arial') + await input.evaluate((el) => (el as HTMLInputElement).setSelectionRange(0, 1)) + await v.page.evaluate(() => window.__ctl.format({ op: 'color', color: '#123456' })) + await settle(v) + expect(await input.evaluate((el) => [(el as HTMLInputElement).selectionStart, (el as HTMLInputElement).selectionEnd])).toEqual([0, 1]) + expect(await input.evaluate((el) => el === document.activeElement)).toBe(true) + } + } + // PPTX commits are debounced (#18 is handled separately); verify the committed formatting here. + if (kind === 'pptx') await v.page.waitForTimeout(500) + await v.page.evaluate(() => window.__ctl.save()) + const saved = fromB64((await v.waitEvent('save')).b64 as string) + if (kind === 'docx') { + const p = (await docxParas(saved)).find((p) => paraText(p).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text === 'document')?.s.sz).toBe(25) + } else { + const { engine } = await openFile(saved) + const slide: any = await engine.call('pptx.slide', [0]) + expect(slide.els.flatMap((e: any) => e.text?.paras ?? []).flatMap((p: any) => p.runs).find((r: any) => r.text === 'office-engine')?.sz).toBe(25) + } + // A caret uses the synchronous restore path, rather than the range's pending re-render restore. + if (kind === 'docx') await v.selectText('document', 'end') + else { + await v.page.locator('.de-txt-edit').focus() + await v.page.keyboard.press('ControlOrMeta+a') + await v.page.keyboard.press('ArrowRight') + await settle(v) + } + await v.page.locator('#host-number').click() + await v.page.locator('#host-number').selectText() + await v.page.keyboard.type('26', { delay: 200 }) + await settle(v) + expect(await v.page.locator('#host-number').inputValue()).toBe('26') + expect(await v.page.locator('#host-number').evaluate((el) => el === document.activeElement)).toBe(true) + expect((await state(v)).format?.size).toBe(26) + if (kind === 'docx') await v.selectText('document') + else { + await v.page.locator('.de-txt-edit').focus() + await v.page.keyboard.press('ControlOrMeta+a') + await settle(v) + } + await v.page.locator('#host-number').click() + // A real DOM selection loss must also invalidate a pending range restore. + await v.page.evaluate(() => { + // A pending restore from this command must also respect the selection loss. + window.__ctl.format({ op: 'size', pt: 27 }) + ;(document.activeElement as HTMLElement).blur() + getSelection()!.removeAllRanges() + document.dispatchEvent(new Event('selectionchange')) + }) + await settle(v) + expect((await state(v)).format).toBeNull() + expect(await v.page.evaluate(() => document.activeElement?.matches('.de-pages, .de-txt-edit'))).toBe(false) + await v.page.evaluate(() => window.__ctl.format({ op: 'size', pt: 70 })) + expect((await state(v)).format).toBeNull() + await v.page.evaluate(() => window.__ctl.setEditing(false)) + await settle(v) + expect((await state(v)).format).toBeNull() + expect(v.errors).toEqual([]) + }) + + test(`${kind}: an older editing view cannot publish or clear its successor's format`, async () => { + const v = await viewer({ controller: true, src: `samples/sample.${kind}`, editable: true, headless: true }) + await v.page.evaluate(() => window.__overlap(1)) + await v.waitEvent('load', 2) + await settle(v) + await selectTarget(v, kind, 1) + const before = (await state(v)).format + expect(before).not.toBeNull() + // The old editor also hears this selection change; its null notification must be ignored. + await v.page.evaluate(() => document.dispatchEvent(new Event('selectionchange'))) + await settle(v) + expect((await state(v)).format).toEqual(before) + await v.page.evaluate(() => window.__overlap(2)) + await settle(v) + expect((await state(v)).format).toEqual(before) + await v.page.evaluate(() => window.__ctl.format({ op: 'size', pt: 23 })) + await settle(v) + expect((await state(v)).format?.size).toBe(23) + expect(v.errors).toEqual([]) + }) + + test(`${kind}: controller replacement, edit exit and source replacement clear format ownership`, async () => { + const v = await viewer({ controller: true, src: `samples/sample.${kind}`, editable: true, headless: true }) + await selectTarget(v, kind) + await v.page.evaluate(async (path) => { + const { createViewerController } = await import(path) + const old = window.__ctl + const next = createViewerController() + ;(window as any).__old = old + window.__ctl = next + next.subscribe(() => {}) + window.__setProps({ controller: next }) + }, '/@fs/' + process.cwd() + '/src/index.ts') + await settle(v) + expect(await v.page.evaluate(() => (window as any).__old.snapshot().format)).toBeNull() + expect((await state(v)).format).not.toBeNull() + await v.page.evaluate(() => window.__ctl.setEditing(false)) + await settle(v) + expect((await state(v)).format).toBeNull() + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await selectTarget(v, kind) + await v.page.evaluate(() => window.__setProps({ src: 'samples/sample.xlsx' })) + await v.waitEvent('load', 2) + await v.page.locator('.de-grid').waitFor() + await settle(v) + expect((await state(v)).kind).toBe('xlsx') + expect((await state(v)).format?.list).toBeUndefined() + expect(await v.page.evaluate(() => (window as any).__old.snapshot().format)).toBeNull() + expect(v.errors).toEqual([]) + }) +} + + +test('xlsx: live host number input retains focus and saved cell value through typing and Backspace', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', editable: true, headless: true, onSave: true }) + await v.typeCell('B2', 'keep-value') + await v.clickCell('B2') + await v.page.evaluate(() => { + const input = document.createElement('input') + input.type = 'number'; input.id = 'host-size'; input.value = '' + input.style.cssText = 'position:fixed;top:0;left:0;z-index:999999' + input.oninput = () => window.__ctl.format({ op: 'size', pt: input.valueAsNumber }) + document.body.append(input) + }) + const input = v.page.locator('#host-size') + await input.click() + await v.page.keyboard.type('14', { delay: 200 }) + await settle(v) + expect(await input.inputValue()).toBe('14') + expect(await input.evaluate((el) => el === document.activeElement)).toBe(true) + await v.page.keyboard.press('Backspace') + await settle(v) + expect(await input.inputValue()).toBe('1') + await v.page.keyboard.type('4') + await settle(v) + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save')).b64 as string) + expect((await xlsxSheet(bytes)).cell('B2')).toBe('keep-value') + expect((await state(v)).format?.size).toBe(14) + expect(strFromU8(unzipSync(bytes)['xl/styles.xml'])).toContain('val="14"') + // Direct calls retain whichever element the host focused; the grid's keyboard still works afterward. + await v.page.evaluate(() => window.__ctl.format({ op: 'size', pt: 18 })) + await settle(v) + expect(await input.evaluate((el) => el === document.activeElement)).toBe(true) + await v.page.evaluate(() => window.__ctl.undo()) + await settle(v) + expect((await state(v)).format?.size).toBe(14) + await v.page.evaluate(() => window.__ctl.redo()) + await settle(v) + expect((await state(v)).format?.size).toBe(18) + await v.page.evaluate(() => window.__ctl.undo()) + await settle(v) + await v.page.evaluate((data) => window.__setProps({ src: new Blob([new Uint8Array(data)]), name: 'reopened.xlsx' }), Array.from(bytes)) + await v.waitEvent('load', 2) + await v.page.locator('.de-grid').waitFor() + await settle(v) + await v.clickCell('B2') + expect(await v.shown('B2')).toBe('keep-value') + expect((await state(v)).format?.size).toBe(14) + await v.page.keyboard.press('ArrowRight') + expect(await v.page.locator('.de-fx-ref').innerText()).toBe('C2') + await v.page.evaluate(() => window.__ctl.goto('1')) + await settle(v) + expect((await state(v)).outline?.items.find((i) => i.current)?.id).toBe('1') + + expect(v.errors).toEqual([]) +}) + +test('docx: controlled host rerenders with inline callbacks preserve the logical target', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', editable: true, headless: true, onSave: true, renderHost: true }) + await v.selectText('document') + const input = v.page.getByLabel('React host size') + await input.click() + await settle(v) + expect(await input.isEnabled()).toBe(true) + await input.selectText() + await v.page.keyboard.type('14', { delay: 200 }) + await settle(v) + expect(await input.inputValue()).toBe('14') + expect((await state(v)).format?.size).toBe(14) + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save')).b64 as string) + expect(runsOf((await docxParas(bytes)).find((p) => paraText(p).startsWith('This document'))!).find((r) => r.text === 'document')?.s.sz).toBe(14) +}) + +test('docx without controller: Ctrl+S then Ctrl+K preserves selection and saves the link', async () => { + const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true }) + await v.selectText('document') + await v.page.keyboard.press('Control+s') + await v.waitEvent('save') + await v.page.keyboard.press('Control+k') + await v.page.locator('.de-dialog input').fill('https://example.org/after-save') + await v.page.keyboard.press('Enter') + await settle(v) + const bytes = (await v.save()).bytes + const p = (await docxParas(bytes)).find((p) => paraText(p).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text === 'document')?.href).toBe('https://example.org/after-save') + expect(v.errors).toEqual([]) +}) + +for (const kind of ['docx', 'pptx'] as const) { + test(`${kind}: a host format command does not suppress later undo caret restoration`, async () => { + const v = await viewer({ controller: true, src: `samples/sample.${kind}`, editable: true, headless: true, onSave: true }) + await selectTarget(v, kind) + const original = (await state(v)).format!.size + await v.page.evaluate(() => { + const input = document.createElement('input') + input.id = 'focus-host'; input.style.cssText = 'position:fixed;top:0;left:0;z-index:999999' + const undo = document.createElement('button') + undo.id = 'undo-host'; undo.textContent = 'Undo host' + undo.style.cssText = 'position:fixed;top:0;left:220px;z-index:999999' + undo.onclick = window.__ctl.undo + document.body.append(input, undo) + }) + await v.page.locator('#focus-host').click() + await v.page.evaluate(() => window.__ctl.format({ op: 'size', pt: 35 })) + await settle(v) + expect(await v.page.locator('#focus-host').evaluate((el) => el === document.activeElement)).toBe(true) + await v.page.locator('#undo-host').click() + await settle(v) + expect(await v.page.evaluate(() => document.activeElement?.matches('.de-pages, .de-txt-edit'))).toBe(true) + expect((await state(v)).format?.size).toBe(original) + expect(await v.page.evaluate(() => getSelection()?.toString())).toBe(kind === 'docx' ? 'document' : 'office-engine') + await v.page.evaluate(() => window.__ctl.redo()) + await settle(v) + expect((await state(v)).format?.size).toBe(35) + expect(v.errors).toEqual([]) + }) +} + +for (const kind of ['docx', 'xlsx', 'pptx'] as const) { + test(`${kind}: invalid runtime commands preserve dirty/history/XML and opaque colors save and reopen`, async () => { + const v = await viewer({ controller: true, src: `samples/sample.${kind}`, editable: true, headless: true, onSave: true }) + if (kind === 'xlsx') await v.clickCell('B2') + else await selectTarget(v, kind) + const invalid = async () => { + await v.page.evaluate(() => { + const commands = [ + { op: 'bold' }, { op: 'font', name: '' }, { op: 'font', name: ' ' }, + ...['red', 'rgb(255,0,0)', '#ff000080'].flatMap((color) => [{ op: 'color', color }, { op: 'highlight', color }]), + ...[0.5, 1000, NaN, Infinity, Number.MIN_VALUE, Number.MAX_VALUE].map((pt) => ({ op: 'size', pt })), + ] + commands.forEach((c) => (window.__ctl.format as (c: unknown) => void)(c)) + }) + await settle(v) + } + const before = await state(v) + await invalid() + expect(formatting(await state(v))).toEqual(formatting(before)) + const path = kind === 'docx' ? 'word/document.xml' : kind === 'pptx' ? 'ppt/slides/slide1.xml' : 'xl/styles.xml' + const saveXML = async () => { + const count = (await v.events('save')).length + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save', count + 1)).b64 as string) + return { bytes, xml: strFromU8(unzipSync(bytes)[path]) } + } + const initial = await saveXML() + await v.page.evaluate(() => { + window.__ctl.format({ op: 'color', color: '#123456ff' }) + window.__ctl.format({ op: 'highlight', color: '#abc' }) + }) + await v.page.waitForTimeout(kind === 'pptx' ? 550 : 200) + const colored = await saveXML() + expect(colored.xml).not.toBe(initial.xml) + expect(colored.xml).toMatch(/123456/i) + expect(colored.xml).toMatch(/AABBCC/i) + const stable = await state(v) + await invalid() + expect(formatting(await state(v))).toEqual(formatting(stable)) + expect((await saveXML()).xml).toBe(colored.xml) + await v.page.evaluate((data) => window.__setProps({ src: new Blob([new Uint8Array(data.bytes)]), name: `reopened.${data.kind}` }), { bytes: Array.from(colored.bytes), kind }) + await v.waitEvent('load', 2) + await v.page.waitForTimeout(500) + if (kind === 'xlsx') await v.clickCell('B2') + else await selectTarget(v, kind) + expect((await state(v)).format?.color?.toLowerCase()).toBe('#123456') + expect((await state(v)).format?.highlight?.toLowerCase()).toBe('#aabbcc') + expect(v.errors).toEqual([]) + }) +} + +test('shared SizeBox retains decimal-comma semantics and commits half points once', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', editable: true, onSave: true }) + await v.selectText('document') + const size = v.page.getByRole('textbox', { name: 'Font size', exact: true }) + await size.fill('12,5') + await size.press('Enter') + await settle(v) + expect((await state(v)).format?.size).toBe(12.5) + const p = (await docxParas((await v.save()).bytes)).find((p) => paraText(p).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text === 'document')?.s.sz).toBe(12.5) + await v.page.evaluate(() => window.__ctl.undo()) + await settle(v) + expect((await state(v)).canUndo).toBe(false) +}) diff --git a/e2e/harness.ts b/e2e/harness.ts index c2e8ce6..5fdbf82 100644 --- a/e2e/harness.ts +++ b/e2e/harness.ts @@ -38,7 +38,8 @@ export function useBrowser() { beforeAll(async () => { server = await createServer({ configFile: 'vite.e2e.config.ts', server: { port: 0, strictPort: false } }) await server.listen() - const browser = await chromium.launch() + // PLAYWRIGHT_CHANNEL=chrome / msedge: an installed browser instead of Playwright's own Chromium + const browser = await chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || undefined }) shared = { base: server.resolvedUrls!.local[0], browser } }) afterEach(async () => { @@ -56,9 +57,9 @@ export function useBrowser() { export type Params = Record /** 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) diff --git a/e2e/locale-built.spec.ts b/e2e/locale-built.spec.ts new file mode 100644 index 0000000..46905a5 --- /dev/null +++ b/e2e/locale-built.spec.ts @@ -0,0 +1,301 @@ +/** Production-artifact checks: run `bun run build` first, as CI does before browser tests. */ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { parasToDocx, rowsToXlsx } from '../src/core/convert' +import { unzipSync, zipSync, strFromU8, strToU8 } from 'fflate' +import { useBrowser, viewer, type Viewer, SAMPLES } from './harness' + +import { builtModule, useBuiltPackage } from './built-package' + +useBuiltPackage() +useBrowser() +const pkg = builtModule('index.js') +const german = builtModule('locales/de.js') + +/** Load the emitted package in a real browser, sharing the fixture's React runtime. */ +async function mount(v: Viewer, props: Record = {}, outerGerman = false) { + await v.page.waitForFunction(() => !!(window as any).__builtRuntime) + await v.page.evaluate(async ({ pkg, german, props, outerGerman }) => { + const { React, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + const de = outerGerman ? (await import(/* @vite-ignore */ german)).de : undefined + const root = createRoot(document.getElementById('built')!) + let current = props + const onLoad = (c: any) => { (window as any).__builtClient = c; window.__events.push({ type: 'load', kind: c.kind, name: c.name }) } + const onError = (e: Error) => window.__events.push({ type: 'error', message: e.message }) + const render = () => { + const view = React.createElement(api.DocViewer, { + ...current, + onLoad, + onError, + }) + root.render(outerGerman ? React.createElement(api.StringsProvider, { strings: de }, view) : view) + } + ;(window as any).__builtUpdate = (next: any) => { current = { ...current, ...next }; render() } + ;(window as any).__builtApi = api + render() + }, { pkg, german, props, outerGerman }) + if (props.src) await v.ready() + else await v.page.locator('.de-file').waitFor() +} + +async function open(props: Record, locale = 'en-GB', outerGerman = false) { + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale }) + await mount(v, props, outerGerman) + return v +} + +async function update(v: Viewer, props: Record) { + await v.page.evaluate((props) => (window as any).__builtUpdate(props), props) +} + +function emfDeck() { + const files = unzipSync(readFileSync(`${SAMPLES}/sample.pptx`)) + const slide = 'ppt/slides/slide1.xml' + files[slide] = strToU8(strFromU8(files[slide]).replace('', ``)) + const rel = 'ppt/slides/_rels/slide1.xml.rels' + files[rel] = strToU8(strFromU8(files[rel]).replace('', '')) + files['ppt/media/regression.emf'] = new Uint8Array([1, 0, 0, 0]) + files['[Content_Types].xml'] = strToU8(strFromU8(files['[Content_Types].xml']).replace('', '')) + return Buffer.from(zipSync(files)) +} + +describe('built package localization', () => { + for (const locale of ['en-GB', 'vi-VN', 'de-DE', 'ar-EG']) { + test(`default formatting follows the ${locale} browser; invalid tags fall back`, async () => { + const v = await open({ src: 'samples/sample.docx' }, locale) + const read = () => v.page.evaluate(() => { + const api = (window as any).__builtApi + const s = api.resolveStrings() + const date = new Date('2026-03-05T14:00:00Z') + return { locale: s.locale, date: date.toLocaleString(s.locale), browserDate: date.toLocaleString(), count: s.docx.status(1, 2, 1234567, s.locale), browserCount: (1234567).toLocaleString() } + }) + const initial = await read() + const optionalGermanRequests = await v.page.evaluate(() => performance.getEntriesByType('resource').filter((e) => e.name.includes('/locales/de.js')).length) + expect(optionalGermanRequests).toBe(0) + const created = await v.page.evaluate(async () => { + const xml = await (await (window as any).__builtClient.call('part', 'docProps/core.xml')).text() + const value = new DOMParser().parseFromString(xml, 'application/xml').getElementsByTagNameNS('*', 'created')[0]!.textContent! + return new Date(value).toLocaleString() + }) + await v.menu('Document details') + await v.page.locator('[role=dialog] dd', { hasText: created }).first().waitFor() + expect(await v.page.locator('[role=dialog]').innerText()).toContain('8.5 × 11 in') + expect(await v.status()).toMatch(/^Page 1 of [0-9]+/) + await v.page.locator('[role=dialog] button', { hasText: 'Close' }).click() + expect(initial.locale).toBeUndefined() + expect(initial.date).toBe(initial.browserDate) + expect(initial.count).toContain(initial.browserCount) + expect(await v.page.locator('.de-file').innerText()).toBe('File') + for (const malformed of [{ locale: 'de_DE' }, { locale: '__proto__' }, { locale: undefined, strings: { locale: 'de_DE' } }]) { + await update(v, malformed) + await v.page.locator('.de-page-inner').first().waitFor() + expect(await v.page.locator('.de-file').innerText()).toBe('File') + await v.menu('Document details') + await v.page.locator('[role=dialog] dd', { hasText: created }).first().waitFor() + await v.page.locator('[role=dialog] button', { hasText: 'Close' }).click() + expect(v.errors).toEqual([]) + } + // Render date/count consumers inside the actual provider, not only the resolver. + const rendered = await v.page.evaluate(async ({ pkg }) => { + const { React, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + const host = document.createElement('div'); document.body.append(host) + const root = createRoot(host) + function Probe() { + const s = api.useStrings() + return React.createElement('span', null, `${new Date('2026-03-05T14:00:00Z').toLocaleString(s.locale)}|${s.docx.status(1, 2, 1234567, s.locale)}`) + } + root.render(React.createElement(api.StringsProvider, { locale: 'de_DE' }, React.createElement(Probe))) + await new Promise((r) => setTimeout(r, 100)) + const text = host.textContent; root.unmount(); host.remove() + return text + }, { pkg }) + expect(rendered).toContain(initial.browserDate) + expect(rendered).toContain(initial.browserCount) + }) + } + + + test('standalone production embed loads English and explicitly imported German', async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'vi-VN' }) + await v.page.addScriptTag({ url: builtModule('office-engine.embed.js') }) + await v.page.evaluate(() => { + const el = document.createElement('office-viewer') + el.setAttribute('src', '/samples/sample.docx') + el.setAttribute('locale', 'de_DE') + el.addEventListener('load', (e: any) => window.__events.push({ type: 'load', ...e.detail })) + el.addEventListener('error', (e: any) => window.__events.push({ type: 'error', message: e.detail?.message })) + document.getElementById('built')!.append(el) + }) + await v.ready('docx') + expect(await v.page.locator('office-viewer .de-file').innerText()).toBe('File') + await v.page.evaluate(async ({ german }) => { + const el = document.querySelector('office-viewer')! as any + el.strings = (await import(/* @vite-ignore */ german)).de + el.setAttribute('locale', 'en-GB') + }, { german }) + await v.page.locator('office-viewer .de-file', { hasText: 'Datei' }).waitFor() + await v.page.locator('office-viewer .de-file').click() + await v.page.locator('office-viewer .de-dd-text', { hasText: 'Dokumenteigenschaften' }).click() + await v.page.locator('office-viewer [role=dialog][aria-label="Dokumenteigenschaften"]').waitFor() + expect((await v.events('load')).length).toBe(1) + expect(v.errors).toEqual([]) + }) + + test('opt-in German, outer provider, partial overrides, pluralization and live switching', async () => { + const v = await open({ src: 'samples/sample.xlsx', editable: true, comments: { open: true } }, 'en-GB', true) + expect(await v.page.locator('.de-file').innerText()).toBe('Datei') + await v.page.locator('.de-cm-empty', { hasText: 'Zelle' }).waitFor() + await v.page.evaluate(async ({ german }) => { + const { React, createRoot } = (window as any).__builtRuntime + const api = (window as any).__builtApi + const de = (await import(/* @vite-ignore */ german)).de + const host = document.createElement('div'); host.id = 'plural-probe'; document.body.append(host) + function Probe() { + const s = api.useStrings() + return React.createElement('span', null, [s.docx.status(1, 1, 1, s.locale), s.xlsx.status(1, 1, s.locale), s.xlsx.usedRangeValue(2, 3, s.locale), s.pptx.status(1, 2, s.locale)].join('|')) + } + createRoot(host).render(React.createElement(api.StringsProvider, { strings: de }, React.createElement(Probe))) + return { loaded: performance.getEntriesByType('resource').map((e) => e.name).filter((x) => x.includes('/locales/de.js')) } + }, { german }) + await v.page.locator('#plural-probe', { hasText: '1 Wort|1 Zeile × 1 Spalte|2 Zeilen × 3 Spalten|Folie 1 von 2' }).waitFor() + expect(await v.page.evaluate(() => performance.getEntriesByType('resource').some((e) => e.name.includes('/locales/de.js')))).toBe(true) + await update(v, { strings: { file: { menu: 'Ablage' } } }) + await v.page.locator('.de-file', { hasText: 'Ablage' }).waitFor() + expect(await v.barButton('Ansicht').count()).toBe(1) + // Override the inherited German table with the emitted English table and switch back without reopening. + await v.page.evaluate(() => (window as any).__builtUpdate({ strings: (window as any).__builtApi.en })) + await v.page.locator('.de-file', { hasText: 'File' }).waitFor() + await v.page.locator('.de-cm-empty', { hasText: 'cell' }).waitFor() + await update(v, { strings: undefined }) + await v.page.locator('.de-file', { hasText: 'Datei' }).waitFor() + await v.page.locator('.de-cm-empty', { hasText: 'Zelle' }).waitFor() + expect((await v.events('load')).length).toBe(1) + expect(v.errors).toEqual([]) + }) + + + test('running DOCX/XLSX status receives numeric counts and renders singular German', async () => { + const docx = Buffer.from(await (await parasToDocx([{ runs: [{ text: 'Wort' }] }])).arrayBuffer()) + const xlsx = Buffer.from(await (await rowsToXlsx([['Wert']], 'Blatt')).arrayBuffer()) + const statuses: Record = {} + for (const [kind, bytes] of [['docx', docx], ['xlsx', xlsx]] as const) { + const v = await viewer({}, { page: 'built-locale.html', wait: false }) + await v.page.route(`**/singular.${kind}`, (route) => route.fulfill({ body: bytes })) + await mount(v, { src: `/singular.${kind}` }, true) + const expected = kind === 'docx' ? 'Seite 1 von 1 · 1 Wort' : '1 Zeile × 1 Spalte' + await v.page.locator('.de-bar .de-status', { hasText: expected }).waitFor() + statuses[kind] = await v.page.locator('.de-bar .de-status').first().innerText() + expect(statuses[kind]).toBe(expected) + if (kind === 'docx') { + await v.page.evaluate(() => (window as any).__builtUpdate({ strings: { docx: { status: (p: number, ps: number, words: number) => `${typeof p}/${typeof ps}/${typeof words}:${words === 1 ? 'one' : 'many'}` } } })) + await v.page.locator('.de-bar .de-status', { hasText: 'number/number/number:one' }).waitFor() + } + expect(v.errors).toEqual([]) + } + }) + + test('comment navigation survives fresh strings identities on the same sheet', async () => { + const v = await open({ src: 'samples/sample.xlsx', editable: true, comments: { open: true } }) + await v.clickCell('B3') + await v.page.locator('.de-cm-new').click() + await v.page.locator('.de-cm-draft textarea').fill('Navigation regression') + await v.page.locator('.de-cm-draft button', { hasText: 'Comment' }).click() + const card = v.page.locator('.de-cm-card').first() + await card.waitFor() + await v.clickCell('A1') + await card.click() + await v.page.waitForFunction(() => document.querySelector('.de-fx-ref')?.textContent === 'B3') + await v.clickCell('A1') + await update(v, { strings: { file: { menu: 'Fresh identity' } } }) + await v.page.locator('.de-file', { hasText: 'Fresh identity' }).waitFor() + await card.click() + await v.page.waitForFunction(() => document.querySelector('.de-fx-ref')?.textContent === 'B3', null, { timeout: 3000 }) + expect(await v.page.locator('.de-fx-ref').innerText()).toBe('B3') + expect(v.errors).toEqual([]) + }) + + test('German clipboard failures and paste limits use the active strings', async () => { + const bytes = Buffer.from(await (await rowsToXlsx(Array.from({ length: 6000 }, (_, i) => [String(i)]), 'Data')).arrayBuffer()) + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'de-DE' }) + await v.page.route('**/clipboard.xlsx', (route) => route.fulfill({ body: bytes })) + await mount(v, { src: '/clipboard.xlsx', editable: true }, true) + await v.clickCell('A1') + await v.page.keyboard.press('ControlOrMeta+a') + await v.page.evaluate(() => { + Object.defineProperty(navigator.clipboard, 'writeText', { + configurable: true, + value: async () => { throw new DOMException('Clipboard denied', 'NotAllowedError') }, + }) + const data = new DataTransfer() + document.activeElement!.dispatchEvent(new ClipboardEvent('copy', { clipboardData: data, bubbles: true, cancelable: true })) + }) + await v.page.locator('.de-toast', { hasText: 'Der Browser hat den Zugriff auf die Zwischenablage blockiert. Zum Kopieren weniger Zeilen auswählen.' }).waitFor() + await v.clickCell('A1') + await v.page.evaluate(() => { + const client = (window as any).__builtClient + const call = client.call.bind(client) + client.call = (op: string, ...args: any[]) => { + const result = call(op, ...args) + if (op === 'xlsx.set') (window as any).__pasteDone = result + return result + } + const data = new DataTransfer() + data.setData('text/plain', Array.from({ length: 100001 }, (_, i) => String(i)).join('\n')) + document.activeElement!.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true })) + }) + await v.page.locator('.de-toast', { hasText: 'Nur die ersten 100.000 von 100.001 Zellen wurden eingefügt' }).waitFor() + await v.page.evaluate(() => (window as any).__pasteDone) + expect(v.errors).toEqual([]) + }) + + test('Visio labels use the active table and main keeps the drawing read-only', async () => { + const v = await open({ src: 'samples/sample.vsdx', editable: true }, 'en-GB', true) + await v.menu('Dokumenteigenschaften') + const germanLabel = await v.page.locator('[role=dialog]').innerText() + expect(germanLabel).toContain('Microsoft-Visio-Zeichnung') + expect(await v.barButton('Ansicht').count()).toBe(0) + await v.page.locator('[role=dialog] button', { hasText: 'Schließen' }).click() + await v.page.evaluate(() => (window as any).__builtUpdate({ strings: (window as any).__builtApi.en })) + await v.page.locator('.de-file', { hasText: 'File' }).waitFor() + await v.menu('Document details') + const englishLabel = await v.page.locator('[role=dialog]').innerText() + expect(englishLabel).toContain('Microsoft Visio drawing') + expect(v.errors).toEqual([]) + }) + + test('German EMF label survives HTML export/reopen and print/PDF separate roots', async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false }) + await v.page.route('**/locale-emf.pptx', (route) => route.fulfill({ body: emfDeck(), contentType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' })) + // Avoid opening the native dialog, while retaining the actual production print preparation and root. + await v.page.addInitScript(() => { + window.print = () => {} + Document.prototype.execCommand = () => true + }) + await mount(v, { src: '/locale-emf.pptx' }, true) + await v.page.locator('.de-slide-inner .de-ph', { hasText: 'EMF-Bild' }).first().waitFor() + const html = await v.downloadAs('Webseite') + expect(html.text.includes('EMF-Bild')).toBe(true) + expect(html.text.includes('EMF image')).toBe(false) + const reopened = await v.ctx.newPage() + await reopened.setContent(html.text) + expect(await reopened.locator('.de-ph', { hasText: 'EMF-Bild' }).count()).toBeGreaterThan(0) + for (const action of ['Drucken', 'PDF-Dokument']) { + await v.menu(action) + const captured = await v.page.waitForFunction(() => { + const frame = [...document.querySelectorAll('iframe')].find((f) => !f.hasAttribute('data-captured') && f.contentDocument?.querySelector('.de-print')?.textContent?.includes('EMF-Bild')) + if (!frame) return false + frame.setAttribute('data-captured', '') + return frame.contentDocument!.documentElement.outerHTML + }) + const prepared = await captured.jsonValue() as string + expect(prepared).not.toContain('EMF image') + if (action === 'PDF-Dokument') { + await reopened.setContent(prepared) + expect((await reopened.pdf({ preferCSSPageSize: true })).subarray(0, 4).toString()).toBe('%PDF') + } + } + expect(v.errors).toEqual([]) + }) +}) diff --git a/e2e/locale-docx.spec.ts b/e2e/locale-docx.spec.ts new file mode 100644 index 0000000..c93fd40 --- /dev/null +++ b/e2e/locale-docx.spec.ts @@ -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([]) + }) +}) diff --git a/e2e/locale-xlsx.spec.ts b/e2e/locale-xlsx.spec.ts new file mode 100644 index 0000000..ec1f076 --- /dev/null +++ b/e2e/locale-xlsx.spec.ts @@ -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([]) + }) +}) diff --git a/e2e/locale.spec.ts b/e2e/locale.spec.ts new file mode 100644 index 0000000..1d19424 --- /dev/null +++ b/e2e/locale.spec.ts @@ -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([]) + }) +}) diff --git a/e2e/ui-built.spec.ts b/e2e/ui-built.spec.ts new file mode 100644 index 0000000..d2ad794 --- /dev/null +++ b/e2e/ui-built.spec.ts @@ -0,0 +1,49 @@ +/** Exercise host UI/provider composition against emitted ESM, after `bun run build`. */ +import { expect, test } from 'bun:test' +import { docxParas, paraText, runsOf, useBrowser, viewer } from './harness' + +import { builtModule, useBuiltPackage } from './built-package' + +useBuiltPackage() +useBrowser() + +test('built UI inherits German through formatting-only locales and defined components, preserving real edits', async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'en-GB' }) + await v.page.waitForFunction(() => !!(window as any).__builtRuntime) + await v.page.evaluate(async ({ pkg, german }) => { + const { React: R, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + if ('de' in api || 'LOCALES' in api) throw new Error('optional German leaked into root exports') + const de = (await import(/* @vite-ignore */ german)).de + function Button(p: any) { + return R.createElement('button', { 'data-built-host': '', 'aria-label': p.title, 'data-active': p.active ? '' : undefined, disabled: p.disabled, onMouseDown: p.onMouseDown, onClick: p.onClick }, p.icon, p.label, p.children) + } + const root = createRoot(document.getElementById('built')!) + let current: any = { src: '/samples/sample.docx', editable: true, locale: 'en-GB' } + const onLoad = (c: any) => window.__events.push({ type: 'load', kind: c.kind }) + const onError = (e: Error) => window.__events.push({ type: 'error', message: e.message }) + function render() { + root.render(R.createElement(api.OfficeUIProvider, { strings: de, components: { Button } }, + R.createElement(api.OfficeUIProvider, { locale: 'fr-FR', components: { Button: undefined } }, + R.createElement(api.DocViewer, { ...current, strings: { file: { menu: 'Ablage' } }, + onLoad, onError, + onSave: async (f: File) => { const bytes = new Uint8Array(await f.arrayBuffer()); let raw = ''; for (const b of bytes) raw += String.fromCharCode(b); window.__events.push({ type: 'save', b64: btoa(raw) }) }, + })))) + } + ;(window as any).__builtUpdate = (p: any) => { current = { ...current, ...p }; render() } + render() + }, { pkg: builtModule('index.js'), german: builtModule('locales/de.js') }) + await v.ready('docx') + expect(await v.page.locator('.de-file').innerText()).toBe('Ablage') + await v.selectText('document') + await v.page.locator('button[data-built-host][aria-label^="Fett"]').click() + await v.page.locator('button[data-built-host][aria-label^="Fett"][data-active]').waitFor() + await v.page.evaluate(() => (window as any).__builtUpdate({ locale: 'vi-VN' })) + expect(await v.page.locator('.de-file').innerText()).toBe('Ablage') + await v.page.locator('.de-bar button.de-mode', { hasText: 'Speichern' }).click() + const saved = await v.waitEvent('save') + const p = (await docxParas(Buffer.from(saved.b64 as string, 'base64'))).find((x) => paraText(x).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text.includes('document'))!.s.b).toBe(true) + expect(await v.events('load')).toHaveLength(1) + expect(v.errors).toEqual([]) +}) diff --git a/e2e/ui-layout.spec.ts b/e2e/ui-layout.spec.ts new file mode 100644 index 0000000..97c5047 --- /dev/null +++ b/e2e/ui-layout.spec.ts @@ -0,0 +1,110 @@ +import { expect, test } from 'bun:test' +import { useBrowser, viewer } from './harness' + +useBrowser() + +test('More keeps its natural width in a 600px row and replacement host components are remeasured', async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const more = v.page.locator('.de-ebar').first().locator('.de-ebar-morewrap button') + await more.waitFor() + const bounds = () => v.page.locator('.de-ebar').first().evaluate((row) => { + const wrapper = row.querySelector('.de-ebar-morewrap')! + const clone = wrapper.cloneNode(true) as HTMLElement + clone.style.cssText = 'position:absolute;width:max-content;visibility:hidden' + row.append(clone) + const natural = clone.getBoundingClientRect().width + clone.remove() + return { + natural, width: wrapper.getBoundingClientRect().width, + right: wrapper.getBoundingClientRect().right, edge: row.getBoundingClientRect().right - 8, + cut: row.querySelectorAll(':scope > [data-i]').length, + } + }) + const before = await bounds() + console.info('initial More bounds', JSON.stringify(before)) + await v.page.getByText('Replace components', { exact: true }).click() + const after = await bounds() + console.info('replacement More bounds', JSON.stringify(after)) + expect(before.width).toBeCloseTo(before.natural, 1) + expect(before.right).toBeLessThanOrEqual(before.edge + 1) + expect(after.cut).toBeLessThan(before.cut) + expect(after.width).toBeCloseTo(after.natural, 1) + expect(after.right).toBeLessThanOrEqual(after.edge + 1) + // Unrelated host rerenders must not read toolbar item geometry again. + await v.page.evaluate(() => { + const original = Element.prototype.getBoundingClientRect + Element.prototype.getBoundingClientRect = function () { + if (this.matches('.de-ebar > [data-i], .de-ebar-morewrap')) window.__events.push({ type: 'measure' }) + return original.call(this) + } + }) + await v.page.getByText('Rerender 0', { exact: true }).click() + console.info('geometry reads on unrelated rerender', (await v.events('measure')).length) + expect(await v.events('measure')).toHaveLength(0) + await more.click() + expect(await v.page.locator('.de-ebar-more button').count()).toBeGreaterThan(0) + expect(v.errors).toEqual([]) +}) + +test('a delayed host dialog focuses and selects the prompt input', async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const input = v.page.getByRole('dialog').locator('input') + await input.waitFor() + const focus = await input.evaluate((el: HTMLInputElement) => ({ focused: document.activeElement === el, start: el.selectionStart, end: el.selectionEnd })) + console.info('delayed prompt focus/selection', JSON.stringify(focus)) + expect(focus).toEqual({ focused: true, start: 0, end: 6 }) + expect(v.errors).toEqual([]) +}) + +test('a prompt host footer outside the form and Enter each submit once', async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const input = v.page.getByRole('dialog').locator('input') + await input.waitFor() + expect(await v.page.getByRole('button', { name: 'OK', exact: true }).evaluate((el) => !!el.closest('form'))).toBe(false) + await input.fill('From footer') + await v.page.getByRole('button', { name: 'OK', exact: true }).click() + console.info('external footer submit events', JSON.stringify(await v.events('submit'))) + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'From footer' }]) + expect(await v.events('close')).toHaveLength(1) + await input.fill('From form') + await input.press('Enter') + console.info('footer then Enter submit events', JSON.stringify(await v.events('submit'))) + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'From footer' }, { type: 'submit', value: 'From form' }]) + expect(await v.events('close')).toHaveLength(2) + expect(v.errors).toEqual([]) +}) + +test('the built-in prompt submits once per primary click or Enter', async () => { + const v = await viewer({ defaultDialog: true }, { page: 'ui.html', wait: false }) + const input = v.page.getByRole('dialog').locator('input') + await input.fill('Click') + await v.page.getByRole('button', { name: 'OK', exact: true }).click() + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'Click' }]) + await input.fill('Enter') + await input.press('Enter') + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'Click' }, { type: 'submit', value: 'Enter' }]) + expect(await v.events('close')).toHaveLength(2) + expect(v.errors).toEqual([]) +}) + +for (const placement of ['overflow', 'popover'] as const) { + test(`a React-portaled host Select in ${placement} survives mousedown and delivers onChange`, async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const title = placement === 'overflow' ? 'Overflow picker' : 'Popover picker' + const parent = placement === 'overflow' ? v.page.locator('[data-portal-overflow] .de-ebar-more') : v.page.locator('.de-tb-pop').last() + if (placement === 'overflow') await v.page.locator('[data-portal-overflow] .de-ebar-morewrap > button').click() + else await v.page.getByRole('button', { name: 'Open popover', exact: true }).click() + await v.page.getByRole('button', { name: title, exact: true }).click() + const option = v.page.getByRole('option', { name: 'Choose option' }) + await option.waitFor() + expect(await option.evaluate((el) => !!el.closest('.de-ebar-more, .de-tb-pop'))).toBe(false) + await option.click() + console.info(`${placement} portal after option click`, JSON.stringify({ parentVisible: await parent.isVisible(), events: await v.events('pick') })) + expect(await v.events('pick')).toEqual([{ type: 'pick', value: 'chosen', title }]) + expect(await parent.isVisible()).toBe(true) + await v.page.getByText('Outside with stopped propagation', { exact: true }).click() + await parent.waitFor({ state: 'detached', timeout: 5000 }) + expect(await parent.count()).toBe(0) + expect(v.errors).toEqual([]) + }) +} diff --git a/package.json b/package.json index bd00820..b0092fc 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/collab/docx.ts b/src/collab/docx.ts index 1fce1a2..d21a939 100644 --- a/src/collab/docx.ts +++ b/src/collab/docx.ts @@ -668,8 +668,8 @@ export class DocxCollab implements Adapter { /** remembers the selection (by paragraph id + text) before the model changes */ private capture() { if (this.snap || !this.host) return - const focused = !!this.ed.input.readSel() - const sel = this.ed.input.sel() + const focused = this.ed.input.focused && !!this.ed.input.readSel() + const sel = focused ? this.ed.input.sel() : this.ed.input.lastSel const a = sel && this.toD(sel.a) const f = sel && this.toD(sel.f) if (!a || !f) return @@ -711,6 +711,7 @@ export class DocxCollab implements Adapter { // keep the caret where the user was; never steal focus from other controls this.ed.pendingSel = s.focused ? sel : null if (!s.focused) this.ed.input.lastSel = sel + this.ed.onSelection(sel) } // ---------------------------------------------------------------- presence diff --git a/src/collab/hosts.ts b/src/collab/hosts.ts index e7bddf2..5227a54 100644 --- a/src/collab/hosts.ts +++ b/src/collab/hosts.ts @@ -89,3 +89,20 @@ export function onLocal(client: object, fn: (data: unknown) => void): () => void c.localFns.add(fn) return () => c.localFns.delete(fn) } + +// Local XLSX undo/redo belongs to the session, rather than the worker's standalone history. +export interface LocalHistory { undo: number; redo: number } +const histories = new WeakMap() +const historyListeners = new WeakMap void>>() +export const getLocalHistory = (client: object): LocalHistory | undefined => histories.get(client) +export function setLocalHistory(client: object, history?: LocalHistory) { + if (history) histories.set(client, history) + else histories.delete(client) + for (const fn of historyListeners.get(client) ?? []) fn() +} +export function subscribeLocalHistory(client: object, fn: () => void): () => void { + let listeners = historyListeners.get(client) + if (!listeners) historyListeners.set(client, (listeners = new Set())) + listeners.add(fn) + return () => { listeners.delete(fn) } +} diff --git a/src/collab/react.tsx b/src/collab/react.tsx index ffc37b7..bc869f5 100644 --- a/src/collab/react.tsx +++ b/src/collab/react.tsx @@ -6,6 +6,7 @@ import type { DocumentClient } from '../core/worker/client' import { getPeers, subscribePeers, type PeerView } from './hosts' import { startCollab, type Collab, type CollabOptions } from './index' import type { CollabStatus } from './session' +import { useStrings } from '../react/strings' const transportIds = new WeakMap() let nextTransportId = 0 @@ -66,16 +67,10 @@ const initials = (name: string) => .map((w) => w[0]!.toUpperCase()) .join('') || '?' -const LABEL: Record = { - connecting: 'Connecting…', - syncing: 'Syncing…', - live: 'Live', - offline: 'Offline · changes will sync', - error: 'Not synced', -} - /** status chip + collaborators' avatars (top bar) */ export function CollabBar({ client, state }: { client: DocumentClient; state: CollabState }) { + const t = useStrings() + const LABEL: Record = t.collab const peers = useSyncExternalStore( (fn) => subscribePeers(client, fn), () => getPeers(client), @@ -88,12 +83,12 @@ export function CollabBar({ client, state }: { client: DocumentClient; state: Co return () => clearInterval(t) }, [state.collab]) if (!state.status) return null - const title = state.status === 'error' ? state.error ?? 'Collaboration stopped' : state.status === 'live' && pending ? `Saving ${pending} change${pending > 1 ? 's' : ''}…` : LABEL[state.status] + const title = state.status === 'error' ? state.error ?? t.collab.stopped : state.status === 'live' && pending ? t.collab.saving(pending) : LABEL[state.status] return ( - {state.status === 'live' ? (peers.length ? `${peers.length + 1} editing` : 'Live') : LABEL[state.status]} + {state.status === 'live' ? (peers.length ? t.collab.editing(peers.length + 1) : LABEL.live) : LABEL[state.status]} {peers.length > 0 && ( diff --git a/src/collab/xlsx.ts b/src/collab/xlsx.ts index 103e195..9209ba2 100644 --- a/src/collab/xlsx.ts +++ b/src/collab/xlsx.ts @@ -7,7 +7,7 @@ import type { DocumentClient } from '../core/worker/client' import type { Methods } from '../core/worker/protocol' import type { BookOp, Range, SheetOp, WorkbookMeta } from '../core/xlsx/types' -import { onLocal } from './hosts' +import { onLocal, setLocalHistory } from './hosts' import type { Adapter, ApplyResult } from './session' import { conflictsX, isStructural, STRUCTURAL, transformX, type PBookOp, type XOp } from './xlsx-ops' import { applyComment, revertComment, type CommentOp } from './comments' @@ -43,6 +43,7 @@ export class XlsxCollab implements Adapter { private offLocal: () => void constructor(private client: DocumentClient) { + this.publishHistory() this.offLocal = onLocal(client, (d) => { const s = d as XlsxLocalSel const sheet = this.path(s.sheet) @@ -52,6 +53,11 @@ export class XlsxCollab implements Adapter { dispose() { this.offLocal() + setLocalHistory(this.client) + } + + private publishHistory() { + setLocalHistory(this.client, { undo: this.undoStack.length, redo: this.redoStack.length }) } private get meta() { @@ -120,6 +126,7 @@ export class XlsxCollab implements Adapter { } else if (!isStructural(op)) this.undoStack.push({ kind: 'op', id: op.id }) if (this.undoStack.length > 200) this.undoStack.shift() this.redoStack = [] + this.publishHistory() return this.submit!(op) } @@ -127,6 +134,7 @@ export class XlsxCollab implements Adapter { const e = from.pop() if (!e) return Promise.resolve(null) to.push(e) + this.publishHistory() if (e.kind === 'op') return this.submit!({ t: 'revert', id: this.id(), target: e.id, which }) return this.submit!({ t: 'sheet', id: this.id(), sheet: e.sheet, op: which === 'prev' ? e.undo : e.redo }) } @@ -153,6 +161,7 @@ export class XlsxCollab implements Adapter { const keep = (e: UndoEntry) => e.kind === 'inverse' && kind === 'local' this.undoStack = this.undoStack.filter(keep) this.redoStack = this.redoStack.filter(keep) + this.publishHistory() } if (kind !== 'local' && res) this.client.notify('collab:xlsx', res) return { result: res, undo: rec } diff --git a/src/core/pptx/parser.ts b/src/core/pptx/parser.ts index be740c5..fa656d9 100644 --- a/src/core/pptx/parser.ts +++ b/src/core/pptx/parser.ts @@ -183,6 +183,22 @@ function phOf(el: XEl): { type: string; idx?: string } | undefined { return { type: ph.a.type ?? 'body', idx: ph.a.idx } } +// A slide title as plain text: symbol-font characters (Wingdings arrows, check marks) have no glyph +// outside their font, so the usual ones become their Unicode look-alikes and the rest are dropped. +const TITLE_SYMBOLS: Record = { + '\uF0E0': '➔', '\uF0E8': '➔', '\uF0F0': '⇨', '\uF0D8': '➢', '\uF0FC': '✓', '\uF0FB': '✗', '\uF0B7': '•', '\uF0A7': '▪', '\uF06C': '●', +} +const plainTitle = (paras: string[]) => paras.join(' ').replace(/[\uF000-\uF0FF]/g, (c) => TITLE_SYMBOLS[c] ?? '').replace(/\s+/g, ' ').trim() + +/** the text of the title placeholder in a slide's shape tree (groups included), or '' */ +function titleOf(tree: XEl | undefined): string { + for (const c of tree?.c ?? []) { + const t = c.n === 'grpSp' ? titleOf(c) : c.n === 'sp' && ['title', 'ctrTitle'].includes(phOf(c)?.type ?? '') ? plainTitle(kids(kid(c, 'txBody'), 'p').map((p) => p.c.map((c) => c.n === 'br' ? ' ' : textOf(c)).join(''))) : '' + if (t) return t + } + return '' +} + const masterType = (t: string) => (t === 'ctrTitle' ? 'title' : t === 'subTitle' || t === 'obj' ? 'body' : t) function indexPlaceholders(spTree: XEl | undefined) { @@ -373,10 +389,18 @@ export class PptxPresentation { bg: r.background(), els, hidden: slide.root.a.show === '0', + title: r.title, notes: await this.notesOf(slide.rels), } } + /** every slide's title placeholder text ('' where there is none): its XML only, nothing laid out */ + async titles(): Promise { + const out: string[] = [] + for (const s of this.meta.slides) out.push(titleOf((await this.part(s.path)).spTree)) + return out + } + /** speaker notes: the text of the body placeholder of the slide's notes slide (paragraphs on lines) */ private async notesOf(slideRels: Rels): Promise { const rel = relOfType(slideRels, 'notesSlide') @@ -389,7 +413,6 @@ export class PptxPresentation { } return undefined } - get defaults() { return this.defaultTextStyle } @@ -538,6 +561,8 @@ function readXfrm(x: XEl | undefined): Box | undefined { } class SlideRenderer { + /** the text of the slide's title placeholder, once walked */ + title: string | undefined constructor( private pres: PptxPresentation, private slide: Part, @@ -953,6 +978,11 @@ class SlideRenderer { const idAttr = path(el, 'nvSpPr', 'cNvPr')?.a.id const sid = part === this.slide && el.n === 'sp' && idAttr ? Number(idAttr) : undefined const text = el.n === 'sp' ? this.textBody(kid(el, 'txBody'), chain, ph, kid(style, 'fontRef'), part, sid) : undefined + // the slide's own title placeholder names the slide (outline, slide list) + if (text && part === this.slide && this.title === undefined && (ph?.type === 'title' || ph?.type === 'ctrTitle')) { + const t = plainTitle(text.paras.map((p) => p.runs.map((r) => r.br ? ' ' : r.text).join(''))) + if (t) this.title = t + } if ((!fill || fill.t === 'none') && !stroke && !text) return out.push({ t: 'shape', box, geom, adj, fill, stroke, text, path: pathD, sid }) } diff --git a/src/core/pptx/types.ts b/src/core/pptx/types.ts index 104ddc3..cc27fff 100644 --- a/src/core/pptx/types.ts +++ b/src/core/pptx/types.ts @@ -125,6 +125,8 @@ export interface SlideModel { els: SlideEl[] notes?: string hidden?: boolean + /** the text of its title placeholder */ + title?: string } export interface PresentationMeta { diff --git a/src/core/worker/client.ts b/src/core/worker/client.ts index 656653e..f09c2a7 100644 --- a/src/core/worker/client.ts +++ b/src/core/worker/client.ts @@ -38,6 +38,11 @@ export class DocumentClient { private urls = new Map>() private destroyed = false + /** the document was closed (`destroy`): every call now fails with "Document closed" */ + get closed(): boolean { + return this.destroyed + } + private constructor(opts: OpenOptions) { const factory = opts.worker === false ? undefined : opts.worker ?? defaultWorkerFactory if (factory) { diff --git a/src/core/worker/engine.ts b/src/core/worker/engine.ts index fc0d0a4..b392a64 100644 --- a/src/core/worker/engine.ts +++ b/src/core/worker/engine.ts @@ -245,6 +245,8 @@ export class Engine { return addSlideImage(this.need(this.pptx), args[0] as number, new Uint8Array(args[1] as ArrayBuffer), args[2] as string) case 'pptx.slide': return this.need(this.pptx).slide(args[0] as number) + case 'pptx.titles': + return this.need(this.pptx).titles() case 'pptx.undo': return undoShapes(this.need(this.pptx), !!args[0]) } diff --git a/src/core/worker/protocol.ts b/src/core/worker/protocol.ts index f2ba4c9..c461e3a 100644 --- a/src/core/worker/protocol.ts +++ b/src/core/worker/protocol.ts @@ -106,6 +106,8 @@ export interface Methods { 'xlsx.undo'(): XlsxEditResult | null 'xlsx.redo'(): XlsxEditResult | null 'pptx.slide'(index: number): SlideModel + /** every slide's title placeholder text ('' where there is none), read without laying out the slides */ + 'pptx.titles'(): string[] /** `cell`: [row, column] of a table cell (`sid` is then the table's graphic frame) */ 'pptx.setText'(index: number, sid: number, paras: PParaSpec[], cell?: [number, number]): SlideModel 'pptx.shapes'(index: number, ops: ShapeOp[]): SlideModel diff --git a/src/embed.ts b/src/embed.ts index 925e128..96680b4 100644 --- a/src/embed.ts +++ b/src/embed.ts @@ -3,12 +3,16 @@ import { createRoot, type Root } from 'react-dom/client' import './core/default-worker' import { DocViewer, type DocViewerProps } from './react/DocViewer' import type { Icons } from './react/edit/Toolbar' +import type { StringsOverride } from './react/strings' +import { createViewerController, type ViewerController } from './react/controller' export type MountOptions = Omit const THEMES = ['light', 'dark', 'auto'] as const export interface MountedViewer { + /** the viewer's state and commands (the one passed in `options.controller`, else its own) */ + controller: ViewerController update(next: Partial): void destroy(): void } @@ -17,12 +21,16 @@ export interface MountedViewer { export function mount(el: HTMLElement, options: MountOptions): MountedViewer { let root: Root | null = createRoot(el) let props = options + const ownController = createViewerController() + let controller = options.controller ?? ownController const shadow = el.getRootNode() instanceof ShadowRoot ? (el.getRootNode() as ShadowRoot) : undefined - const render = () => root?.render(createElement(DocViewer, { ...props, styleTarget: shadow })) + const render = () => root?.render(createElement(DocViewer, { ...props, controller, styleTarget: shadow })) render() return { + get controller() { return controller }, update(next) { props = { ...props, ...next } + controller = props.controller ?? ownController render() }, destroy() { @@ -36,19 +44,24 @@ export function mount(el: HTMLElement, options: MountOptions): MountedViewer { * `` * Rendered inside a shadow root so host page CSS cannot leak in. * Attributes: src, name, editable, toolbar / thumbnails / save / download / file-menu / open / capture-select-all ("false" to turn off), - * theme ("light" | "dark" | "auto"); + * theme ("light" | "dark" | "auto"), locale (BCP 47 number/date formatting tag); other languages are supplied through `.strings`. * real-time collaboration: collab (hub WebSocket URL), room, user (display name), base (snapshot seq `src` was opened at). - * Properties: `file` (File/Blob/ArrayBuffer) for local data; `icons` (map or resolver, as DocViewer's `icons`). + * Properties: `file` (File/Blob/ArrayBuffer) for local data; `icons` (map or resolver, as DocViewer's `icons`); + * `strings` (texts replacing English or the enclosing provider's). + * `controller` (ViewerController) for state and commands; `headless` displays the document alone. */ export class OfficeViewerElement extends HTMLElement { - static observedAttributes = ['src', 'name', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments'] + static observedAttributes = ['src', 'name', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments', 'locale', 'headless'] private viewer?: MountedViewer private _file?: Blob | ArrayBuffer private _icons?: Icons + private _strings?: StringsOverride // one function each for the element's life: a new one with every update would run the viewer's load effect again (a `load` event per update) private readonly onLoad: NonNullable = (client) => this.dispatchEvent(new CustomEvent('load', { detail: { kind: client.kind, name: client.name } })) private readonly onError: NonNullable = (error) => this.dispatchEvent(new CustomEvent('error', { detail: error })) private readonly onComment = (e: unknown) => this.dispatchEvent(new CustomEvent('comment', { detail: e })) + /** the viewer's state and commands, the same object for the element's whole life */ + readonly controller = createViewerController() get file() { return this._file @@ -65,6 +78,13 @@ export class OfficeViewerElement extends HTMLElement { this._icons = v this.sync() } + get strings() { + return this._strings + } + set strings(v: StringsOverride | undefined) { + this._strings = v + this.sync() + } connectedCallback() { if (this.viewer) return @@ -90,7 +110,7 @@ export class OfficeViewerElement extends HTMLElement { return { src: this._file ?? this.getAttribute('src'), name: this.getAttribute('name') ?? undefined, - toolbar: this.getAttribute('toolbar') !== 'false', + toolbar: this.hasAttribute('toolbar') ? this.getAttribute('toolbar') !== 'false' : undefined, thumbnails: this.getAttribute('thumbnails') !== 'false', editable: this.hasAttribute('editable') && this.getAttribute('editable') !== 'false', allowSave: this.getAttribute('save') !== 'false', @@ -100,6 +120,10 @@ export class OfficeViewerElement extends HTMLElement { captureSelectAll: this.getAttribute('capture-select-all') !== 'false', theme: THEMES.find((t) => t === this.getAttribute('theme')), icons: this._icons, + locale: this.getAttribute('locale') ?? undefined, + strings: this._strings, + headless: this.hasAttribute('headless') && this.getAttribute('headless') !== 'false', + controller: this.controller, collab: this.getAttribute('collab') && this.getAttribute('room') ? { diff --git a/src/index.ts b/src/index.ts index ec48d5b..aa63a9c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,10 @@ export { useDocument, type DocumentState } from './react/useDocument' export { injectStyles, stylesText } from './react/injectStyles' export type { Zoom } from './react/common/ZoomControl' export { THEME_TOKENS, createTheme, themeStyle, useThemeRoot, type Theme, type ThemeMode, type ThemeOptions, type ThemeToken, type ThemeTokens } from './react/theme' -export { IconsProvider, ICON_NAMES, type IconName, type Icons } from './react/edit/Toolbar' +export { Icon, IconsProvider, ICON_NAMES, type DropOption, type IconName, type Icons } from './react/edit/Toolbar' +export { OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogAction, type DialogProps, type SelectProps, type ToastProps, type UIComponents } from './react/ui' +export { StringsProvider, useStrings, resolveStrings, en, type Strings, type StringsOverride, type Locale } from './react/strings' +export { type ViewerController, createViewerController, useViewerState, type FormatCommand, type TextFormat, type ViewerState, type ViewerOutline, type OutlineItem } from './react/controller' export { DocumentClient, setDefaultWorker, type OpenOptions } from './core/worker/client' export type { DocSource } from './core/source' diff --git a/src/locales/de.ts b/src/locales/de.ts new file mode 100644 index 0000000..97d0fa3 --- /dev/null +++ b/src/locales/de.ts @@ -0,0 +1,2 @@ +/** Optional German (Germany) UI texts. Import and pass as `strings` to opt in. */ +export { de } from '../react/strings/de' diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx index 59ca633..54f3fd4 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useInsertionEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react' +import { useCallback, useEffect, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react' import type { DocSource } from '../core/source' import type { DocumentClient, OpenOptions } from '../core/worker/client' import type { Zoom } from './common/ZoomControl' @@ -7,13 +7,14 @@ import { ViewerContext, type FileOps, type ViewerApi } from './common/Slots' import { StatusContext } from './common/Status' import { ConfirmDialog, PromptDialog, Toast } from './common/Dialog' import { download, Icon, IconsProvider, type Icons } from './edit/Toolbar' +import { UIComponentsProvider, type UIComponents } from './ui' +import { createViewerController, internalController, type ViewerController } from './controller' import { DetailsDialog } from './file/DetailsDialog' -import { FileMenu, KIND_LABEL, useFileActions, type FileMenuItem } from './file/FileMenu' +import { FileMenu, useFileActions, type FileMenuItem } from './file/FileMenu' import { importFile, type Imported } from './file/importFile' import { blankPptx, parasToDocx, rowsToXlsx } from '../core/convert' import type { DocKind } from '../core/opc' import { extOf, HAS_SOURCE, PLAIN_EXT, PLAIN_FILE, unpackedName, type PlainFormat } from '../core/plain' -import type { LegacyFormat } from '../core/legacy' import { injectStyles } from './injectStyles' import { isTextEntry, useSize } from './common/hooks' import { useThemeRoot, type Theme } from './theme' @@ -26,6 +27,7 @@ import type { CollabOptions } from '../collab' import { CollabBar, PeerOverlay, useCollab } from '../collab/react' import { CommentsContext, CommentsCtl, useCommentsState, type CommentOptions } from './comments/Comments' import { COMMENT_KEYS, CommentsPanel } from './comments/CommentsPanel' +import { formatBytes, StringsProvider, useStrings, type Locale, type StringsOverride } from './strings' export interface DocViewerProps { /** @@ -112,39 +114,32 @@ export interface DocViewerProps { * Each is rendered in `span.de-icon`, sized by font-size (1em). */ icons?: Icons + /** + * The host's own UI components (`Button`, `Select`, `Separator`, `Dialog`, `Toast`), rendered in the toolbars and + * dialogs instead of the built-in ones; each one left out keeps the built-in one. See docs/theming.md. + */ + components?: Partial + /** BCP 47 number/date formatting tag; defaults to the enclosing table or browser. Does not select UI texts. */ + locale?: Locale + /** Texts replacing the enclosing provider's or English texts, key by key (see `Strings`): a group may be given in part, e.g. `{ file: { menu: 'Datei' } }`. */ + strings?: StringsOverride + /** + * The viewer's state and commands for the host (`createViewerController()`): zoom, page, outline, editing, unsaved + * changes, save, undo… Subscribe to it to draw your own controls; see `headless`. + */ + controller?: ViewerController + /** + * The document alone: no top bar, zoom control, outline panel, sheet tabs or slide list (the host draws its own, + * driven by `controller`). While editing, the formatting toolbar keeps its row. The top bar shows when `toolbar` is + * set explicitly. Default false. + */ + headless?: boolean } const EXT: Record = { docx: '.docx', xlsx: '.xlsx', pptx: '.pptx' } -const FROM_LABEL: Record<'pages' | 'keynote' | 'numbers' | 'visio', string> = { - pages: 'Apple Pages document', - keynote: 'Apple Keynote presentation', - numbers: 'Apple Numbers spreadsheet', - visio: 'Microsoft Visio drawing', -} -const CONVERTED_LABEL: Record = { - doc: 'Word 97-2003 document', - xls: 'Excel 97-2003 workbook', - ppt: 'PowerPoint 97-2003 presentation', - rtf: 'Rich Text Format document', - odt: 'OpenDocument text', - ods: 'OpenDocument spreadsheet', - odp: 'OpenDocument presentation', -} const IMPORTED_BADGE: Record = { csv: 'csv', tsv: 'tsv', text: 'txt', markdown: 'md', html: 'html', svg: 'svg', mermaid: 'mmd', plantuml: 'puml', graphviz: 'dot' } -const IMPORTED_LABEL: Record = { - csv: 'CSV file', - tsv: 'Tab-separated values', - text: 'Plain text', - markdown: 'Markdown', - html: 'HTML page', - svg: 'SVG picture', - mermaid: 'Mermaid diagram', - plantuml: 'PlantUML diagram', - graphviz: 'Graphviz diagram', -} /** plain formats saved back as themselves: Markdown and HTML built again from the document when it was edited, SVG from its text */ const SAVES_SOURCE = new Set(['markdown', 'html', 'svg']) -const UNTITLED: Record = { docx: 'Untitled document', xlsx: 'Untitled spreadsheet', pptx: 'Untitled presentation' } /** a key per opened client: a view is built again for each (the edited source's previews have one name) */ const clientIds = new WeakMap() @@ -155,14 +150,24 @@ const clientKey = (c: object) => { return id } -function fmtBytes(n: number) { - if (n < 1024) return `${n} B` - if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB` - return `${(n / 1024 / 1024).toFixed(1)} MB` +export function DocViewer(props: DocViewerProps) { + return ( + + + + ) } -export function DocViewer(props: DocViewerProps) { - const { src, name, className, style, toolbar = true, toolbarExtra, zoom, thumbnails, headers, credentials, worker, styleTarget, theme, onLoad, onError } = props +function Viewer(props: DocViewerProps) { + const t = useStrings() + const fmtBytes = (n: number) => formatBytes(t, n) + const { src, name, className, style, toolbarExtra, zoom, thumbnails, headers, credentials, worker, styleTarget, theme, onLoad, onError } = props + const headless = !!props.headless + const toolbar = props.toolbar ?? !headless + // without a controller from the host the viewer keeps its own: the view publishes to one either way + const ownCtl = useMemo(() => createViewerController(), []) + const controller = internalController(props.controller ?? ownCtl) + const ctl = useMemo(() => controller.createBinding(), [controller]) const root = useThemeRoot(theme, style) const { allowEdit = true, allowSave = true, allowDownload = true, fileMenu = true, allowOpen = true, captureSelectAll = true, onSave, onDirtyChange } = props const [editing, setEditing] = useState(!!props.editable) @@ -196,6 +201,7 @@ export function DocViewer(props: DocViewerProps) { saveSession.live = false } }, [saveSession]) + const viewCtl = useMemo(() => ctl.createView(), [ctl, client]) const docName = renamed ?? loadName const collab = useCollab(client, props.collab) const srcFormat = client?.info?.imported @@ -290,6 +296,7 @@ export function DocViewer(props: DocViewerProps) { const cmOpts = props.comments || {} if (cmCtl) { cmCtl.opts = cmOpts + cmCtl.t = t cmCtl.me = cmOpts.user ?? props.collab?.user ?? { name: 'Me' } cmCtl.canComment = !readOnly && (cmOpts.canComment ?? (editing && canEdit)) } @@ -401,8 +408,8 @@ export function DocViewer(props: DocViewerProps) { // next to its source, the document is a preview: it is edited through the source const docEditable = editing && canEdit && !codeShown const api = useMemo( - () => ({ bar: barEl, editable: docEditable, setDirty: setDocDirty, save, canDownload: allowDownload, client, fileOps, selectAll }), - [barEl, docEditable, setDocDirty, save, allowDownload, client], + () => ({ bar: barEl, editable: docEditable, setDirty: setDocDirty, save, canDownload: allowDownload, client, fileOps, selectAll, ctl: viewCtl, headless }), + [barEl, docEditable, setDocDirty, save, allowDownload, client, viewCtl, headless], ) const editSource = (text: string) => { @@ -496,30 +503,30 @@ export function DocViewer(props: DocViewerProps) { setOpened(doc) if (edit) setEditing(true) }, []) - const canOpen = fileMenu && allowOpen && !props.collab + const canOpen = allowOpen && !props.collab const fileActions = useFileActions({ kind: client?.kind, ext: officeExt, base: baseName, canOpen, - canImport: fileMenu && allowEdit && canEdit, - canSave: fileMenu && canSave, - canDownload: fileMenu && allowDownload && !!client, + canImport: allowEdit && canEdit, + canSave, + canDownload: allowDownload && !!client, ops: fileOps, create: (kind: DocKind) => - replace(`A new ${UNTITLED[kind].split(' ')[1]} replaces the current document. Your changes are not saved.`, () => { + replace(t.bar.replaceNew(t.newWhat[kind]), () => { const blank = kind === 'docx' ? parasToDocx([]) : kind === 'xlsx' ? rowsToXlsx([], 'Sheet1') : blankPptx() - blank.then((src) => show({ src, name: UNTITLED[kind] + EXT[kind], converted: false }, allowEdit), (e: Error) => setToast(e.message)) + blank.then((src) => show({ src, name: t.untitled[kind] + EXT[kind], converted: false }, allowEdit), (e: Error) => setToast(e.message)) }), open: (file) => - replace(`Opening “${file.name}” replaces the current document. Your changes are not saved.`, () => { - importFile(file).then(show, (e: Error) => setToast(e.message)) + replace(t.bar.replaceOpen(file.name), () => { + importFile(file, t.file.unsupported).then(show, (e: Error) => setToast(e.message)) }), save, downloadOriginal: () => saveFile(true), picture: isPicture ? { - label: 'SVG picture', + label: t.file.picture, ext: '.svg', download: async () => download(new Blob([await sourceText()], { type: 'image/svg+xml' }), saveName), } @@ -559,12 +566,31 @@ export function DocViewer(props: DocViewerProps) { const busy = loading || (!!progress && pct < 100) const title = renamed ?? client?.name ?? docName ?? (typeof src === 'string' ? decodeURIComponent(src.split(/[?#]/)[0].split('/').pop() ?? '') : (src as File | undefined)?.name) ?? '' + // ---- controller: the viewer's part of the state, and its commands ---- + const editAllowed = !readOnly && !codeShown + useEffect(() => { + ctl.update({ kind: client?.kind ?? null, loading: busy, editing: docEditable, canEdit: !!client && editAllowed && canEdit, dirty, saving }) + }, [ctl, client, busy, docEditable, editAllowed, canEdit, dirty, saving]) + const commands = useRef({ editAllowed, save, fileActions, cmCtl }) + commands.current = { editAllowed, save, fileActions, cmCtl } + useLayoutEffect(() => { + return ctl.attachViewer({ + setEditing: (on) => { + if (!on || commands.current.editAllowed) setEditing(on) + }, + save: () => commands.current.save(), + fileAction: (id) => commands.current.fileActions.run(id), + toggleComments: (open) => commands.current.cmCtl?.toggle(open), + }) + }, [ctl]) + useLayoutEffect(() => viewCtl.activate(), [viewCtl]) + let body: ReactNode if (error) { body = (
- Cannot open document. + {t.bar.cannotOpen}
{error.message}
@@ -573,10 +599,10 @@ export function DocViewer(props: DocViewerProps) { body = src || opened ? (
-
{progress?.phase === 'download' && progress.total ? `Downloading… ${fmtBytes(progress.loaded)} / ${fmtBytes(progress.total)}` : 'Opening…'}
+
{progress?.phase === 'download' && progress.total ? t.bar.downloading(fmtBytes(progress.loaded), fmtBytes(progress.total)) : t.bar.opening}
) : ( -
No document
+
{t.bar.noDocument}
) } else if (isPicture) body = else if (client.kind === 'docx') body = @@ -585,7 +611,8 @@ export function DocViewer(props: DocViewerProps) { return ( -
+ +
{toolbar && (
{client && {client.info?.from ?? client.info?.converted ?? (client.info?.imported ? IMPORTED_BADGE[client.info.imported] : client.kind)}} @@ -603,11 +630,11 @@ export function DocViewer(props: DocViewerProps) { className={'de-mode' + (codeShown ? ' de-mode-on' : '')} onClick={() => setCodeOpen((v) => !v)} aria-pressed={codeShown} - title={codeShown ? 'Hide the source' : 'Edit the source side by side with the document'} + title={codeShown ? t.bar.codeHide : t.bar.codeShow} data-testid="de-code-toggle" > - Code + {t.bar.code} )} {cmCtl && ( @@ -615,31 +642,31 @@ export function DocViewer(props: DocViewerProps) { type="button" className={'de-mode de-cm-toggle' + (cmState.open ? ' de-mode-on' : '')} onClick={() => cmCtl.toggle()} - title={cmCtl.canComment ? `Comments (${COMMENT_KEYS} to comment on the selection)` : 'Comments'} + title={cmCtl.canComment ? t.bar.commentsTitle(COMMENT_KEYS) : t.bar.comments} aria-pressed={cmState.open} data-testid="de-comments-toggle" > - Comments + {t.bar.comments} {cmCount > 0 && {cmCount}} )} {client && allowEdit && !readOnly && !codeShown && ( - )} {client && canSave && ((editing && !readOnly) || dirty) && ( - )}
)} - {toolbar && client && docEditable &&
} + {(toolbar || headless) && client && docEditable &&
}
{codeShown && (
@@ -655,13 +682,13 @@ export function DocViewer(props: DocViewerProps) { readOnly={!allowEdit || !!props.collab} notice={ dirty && !sourceEdited.current && !rebuilds - ? 'Changes made in the document are not in this source: editing it builds the document again from the source.' + ? t.bar.sourceStale : undefined } onCopy={() => navigator.clipboard?.writeText(code).then( - () => setToast('Source copied'), - () => setToast('Cannot copy here'), + () => setToast(t.bar.sourceCopied), + () => setToast(t.bar.cannotCopy), ) } onDownload={allowDownload ? () => download(new Blob([code], { type: PLAIN_FILE[srcFormat!].mime }), sourceName()) : undefined} @@ -674,7 +701,7 @@ export function DocViewer(props: DocViewerProps) { className="de-split-handle" role="separator" aria-orientation={stacked ? 'horizontal' : 'vertical'} - aria-label="Resize the source" + aria-label={t.bar.resizeSource} aria-valuenow={Math.round(split * 100)} aria-valuemin={15} aria-valuemax={85} @@ -699,14 +726,14 @@ export function DocViewer(props: DocViewerProps) { {cmCtl && cmState.open && }
{toast && } - {confirm && setConfirm(null)} />} + {confirm && setConfirm(null)} />} {renaming && client && ( { const next = v.trim().replace(/[\\/:*?"<>|]+/g, ' ').replace(new RegExp(`(\\${officeExt}|\\${saveExt})$`, 'i'), '') if (!next) return @@ -721,25 +748,26 @@ export function DocViewer(props: DocViewerProps) { 0 ? [['File size', fmtBytes(client.size)] as [string, string]] : []), - ...(dirty ? [['Status', 'Unsaved changes'] as [string, string]] : []), + ...(client.size > 0 ? [[t.details.fileSize, fmtBytes(client.size)] as [string, string]] : []), + ...(dirty ? [[t.details.status, t.details.unsaved] as [string, string]] : []), ]} stats={fileOps.current?.stats() ?? []} onClose={() => setDetails(false)} /> )}
+ ) } diff --git a/src/react/comments/Comments.ts b/src/react/comments/Comments.ts index 060c64c..e76f696 100644 --- a/src/react/comments/Comments.ts +++ b/src/react/comments/Comments.ts @@ -7,6 +7,7 @@ import { createContext, useContext, useSyncExternalStore } from 'react' import { initialsOf, nowIso, newCommentId, threadsOf, type CommentAnchor, type CommentThread, type CommentUser, type DocComment } from '../../core/comments' import type { DocKind } from '../../core/opc' import type { DocumentClient } from '../../core/worker/client' +import { en, type Strings } from '../strings/en' export interface CommentOptions { /** who writes the comments made here (default: the collaboration user, else "Me") */ @@ -66,7 +67,7 @@ export interface CommentHost { /** shows thread `id`'s place */ reveal(id: string): void /** what to do to comment, when `pending()` finds nothing */ - hint: string + hint: () => string } export interface CommentsState { @@ -87,6 +88,15 @@ export class CommentsCtl { host: CommentHost | null = null opts: CommentOptions = {} me: CommentUser = { name: 'Me' } + /** texts of the notices */ + private texts: Strings = en + get t(): Strings { return this.texts } + set t(value: Strings) { + if (value === this.texts) return + this.texts = value + // Quotes may contain translated locations; keep the host (and its navigation sequence) intact. + this.placedCache = null + } canComment = false loaded = false private subs = new Set<() => void>() @@ -187,7 +197,7 @@ export class CommentsCtl { if (!this.canComment || !this.host) return false const draft = at ?? this.host.pending() if (!draft) { - this.set({ open: true, draft: null, notice: this.host.hint }) + this.set({ open: true, draft: null, notice: this.host.hint() }) return false } if (draft.existing) { @@ -222,7 +232,7 @@ export class CommentsCtl { await this.client.call('comments.set', id, c) return true } catch (e) { - this.set({ notice: `Couldn't save the comment: ${(e as Error).message}` }) + this.set({ notice: this.t.comments.saveFailed((e as Error).message) }) return false } } @@ -263,7 +273,7 @@ export class CommentsCtl { const mine = () => (this.state.draft === draft ? { draft: null } : {}) if (host.attach && !(await host.attach(id, draft))) { await this.write(id, null) - this.set({ ...mine(), notice: 'The commented text is no longer there' }) + this.set({ ...mine(), notice: this.t.comments.textGone }) return false } this.set(this.state.draft === draft ? { draft: null, active: id } : {}) diff --git a/src/react/comments/CommentsPanel.tsx b/src/react/comments/CommentsPanel.tsx index 28f4238..a0fc37c 100644 --- a/src/react/comments/CommentsPanel.tsx +++ b/src/react/comments/CommentsPanel.tsx @@ -5,6 +5,7 @@ import { ContextMenu, MOD, type MenuItem } from '../common/ContextMenu' import { ConfirmDialog } from '../common/Dialog' import { Icon } from '../edit/Toolbar' import { useCommentsState, type CommentsCtl, type PlacedThread } from './Comments' +import { useStrings, type Strings } from '../strings' const ALT = MOD === '⌘' ? '⌥' : 'Alt+' /** shortcut that starts a comment on the selection */ @@ -17,16 +18,16 @@ function colorOf(u: CommentUser): string { return PEER_COLORS[h % PEER_COLORS.length] } -function ago(iso: string, now: number): string { +function ago(iso: string, now: number, str: Strings): string { const t = Date.parse(iso) if (!Number.isFinite(t)) return '' const s = Math.max(0, (now - t) / 1000) - if (s < 45) return 'just now' - if (s < 3600) return `${Math.round(s / 60)} min ago` - if (s < 86400) return `${Math.round(s / 3600)} h ago` - if (s < 7 * 86400) return `${Math.round(s / 86400)} d ago` + if (s < 45) return str.comments.justNow + if (s < 3600) return str.comments.minutesAgo(Math.round(s / 60)) + if (s < 86400) return str.comments.hoursAgo(Math.round(s / 3600)) + if (s < 7 * 86400) return str.comments.daysAgo(Math.round(s / 86400)) const d = new Date(t) - return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', ...(d.getFullYear() !== new Date(now).getFullYear() ? { year: 'numeric' } : {}) }) + return d.toLocaleDateString(str.locale, { month: 'short', day: 'numeric', ...(d.getFullYear() !== new Date(now).getFullYear() ? { year: 'numeric' } : {}) }) } /** comment text with its mentions set apart */ @@ -80,6 +81,7 @@ export function Composer(props: { onCancel?: () => void }) { const { ctl } = props + const str = useStrings() const [text, setText] = useState(props.initial ?? '') const [mentions, setMentions] = useState(props.mentions ?? []) const [pop, setPop] = useState<{ at: number; end: number; list: CommentUser[]; hi: number } | null>(null) @@ -204,10 +206,10 @@ export function Composer(props: {
)}
- {canMention && @ to mention} + {canMention && {str.comments.mentionTip}} {props.onCancel && ( )} )} -
{ctl.canComment && !st.draft && ( - )} {st.notice && (
{st.notice} -
@@ -395,7 +401,7 @@ export function CommentsPanel({ ctl }: { ctl: CommentsCtl }) { {ctl.me.name}
- ctl.post(t, m)} onCancel={() => ctl.cancelDraft()} /> + ctl.post(t, m)} onCancel={() => ctl.cancelDraft()} />
)} {shown.map((t) => ( @@ -403,16 +409,16 @@ export function CommentsPanel({ ctl }: { ctl: CommentsCtl }) { ))} {!shown.length && !st.draft && (
- {all.length ? 'Every comment is resolved.' : ctl.canComment ? `No comments yet. ${ctl.host?.hint ?? ''}` : 'No comments.'} + {all.length ? str.comments.allResolved : ctl.canComment ? str.comments.noneYet(ctl.host?.hint() ?? '') : str.comments.none}
)}
{menu && setMenu(null)} />} {confirm && ( void ctl.remove(confirm.id)} onClose={() => setConfirm(null)} /> diff --git a/src/react/common/Dialog.tsx b/src/react/common/Dialog.tsx index 74678b7..0ca8de9 100644 --- a/src/react/common/Dialog.tsx +++ b/src/react/common/Dialog.tsx @@ -1,4 +1,6 @@ -import { useEffect, useRef, useState, type ReactNode } from 'react' +import { useCallback, useEffect, useState, type ReactNode } from 'react' +import { useStrings } from '../strings' +import { DefaultDialog, DefaultToast, useHostUI, type DialogAction } from '../ui' export interface PromptSpec { title: string @@ -16,10 +18,10 @@ export interface PromptSpec { /** Small modal prompt (no window.prompt: works in sandboxed / embedded pages). */ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () => void }) { + const t = useStrings() + const Dialog = useHostUI().Dialog ?? DefaultDialog const [v, setV] = useState(spec.initial ?? '') - const ref = useRef(null) - useEffect(() => { - const el = ref.current + const ref = useCallback((el: HTMLInputElement | HTMLTextAreaElement | null) => { el?.focus() el?.select() }, []) @@ -27,107 +29,64 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () onClose() spec.onOk(v) } + const actions: DialogAction[] = [ + ...(spec.extra + ? [ + { + label: spec.extra.label, + extra: true, + onClick: () => { + onClose() + spec.extra!.run() + }, + }, + ] + : []), + { label: t.common.cancel, onClick: onClose }, + { label: spec.ok ?? t.common.ok, primary: true, submit: true, onClick: done }, + ] return ( -
e.target === e.currentTarget && onClose()} - onKeyDown={(e) => { - if (e.key === 'Escape') { - e.stopPropagation() - onClose() - } - }} - > -
{ - e.preventDefault() - done() - }} - > -
{spec.title}
- {spec.label && } - {spec.area ? ( -