From 4caec8dae99397688ace5d21d178f2ab4fe099f0 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:04:43 +0100 Subject: [PATCH 01/20] feat(i18n): reconstruct PR6 on main and address locale review --- .gitignore | 3 + README.md | 1 + artifacts/pr6-description.md | 20 + artifacts/pr6-review-response.md | 46 ++ docs/api.md | 94 +++- e2e/app/built-locale.html | 10 + e2e/app/embed.html | 2 + e2e/app/main.tsx | 8 + e2e/embed.spec.ts | 30 ++ e2e/harness.ts | 4 +- e2e/locale-built.spec.ts | 282 +++++++++++ e2e/locale-docx.spec.ts | 23 + e2e/locale-xlsx.spec.ts | 21 + e2e/locale.spec.ts | 85 ++++ package.json | 4 + src/collab/react.tsx | 15 +- src/embed.ts | 25 +- src/index.ts | 1 + src/locales/de.ts | 2 + src/react/DocViewer.tsx | 114 ++--- src/react/comments/Comments.ts | 18 +- src/react/comments/CommentsPanel.tsx | 72 +-- src/react/common/Dialog.tsx | 9 +- src/react/common/ZoomControl.tsx | 12 +- src/react/docx/DocxToolbar.tsx | 231 ++++----- src/react/docx/DocxView.tsx | 129 ++--- src/react/docx/FindBar.tsx | 20 +- src/react/docx/HeaderFooterDialog.tsx | 60 ++- src/react/docx/PageSetupDialog.tsx | 82 ++-- src/react/docx/render.tsx | 14 +- src/react/edit/Toolbar.tsx | 21 +- src/react/file/DetailsDialog.tsx | 29 +- src/react/file/FileMenu.tsx | 58 ++- src/react/file/importFile.ts | 8 +- src/react/file/print.tsx | 13 +- src/react/picture/PictureView.tsx | 8 +- src/react/pptx/PptxToolbar.tsx | 216 ++++----- src/react/pptx/PptxView.tsx | 66 +-- src/react/pptx/Slide.tsx | 10 +- src/react/source/SourceEditor.tsx | 12 +- src/react/strings/de.ts | 635 +++++++++++++++++++++++++ src/react/strings/en.ts | 649 ++++++++++++++++++++++++++ src/react/strings/index.tsx | 74 +++ src/react/styles.css | 2 +- src/react/xlsx/XlsxToolbar.tsx | 225 ++++----- src/react/xlsx/XlsxView.tsx | 96 ++-- src/react/xlsx/drawings.tsx | 12 +- src/react/xlsx/print.tsx | 8 +- test/strings-render.test.tsx | 82 ++++ test/strings.test.ts | 103 ++++ vite.config.ts | 2 +- 51 files changed, 2993 insertions(+), 773 deletions(-) create mode 100644 artifacts/pr6-description.md create mode 100644 artifacts/pr6-review-response.md create mode 100644 e2e/app/built-locale.html create mode 100644 e2e/locale-built.spec.ts create mode 100644 e2e/locale-docx.spec.ts create mode 100644 e2e/locale-xlsx.spec.ts create mode 100644 e2e/locale.spec.ts create mode 100644 src/locales/de.ts create mode 100644 src/react/strings/de.ts create mode 100644 src/react/strings/en.ts create mode 100644 src/react/strings/index.tsx create mode 100644 test/strings-render.test.tsx create mode 100644 test/strings.test.ts diff --git a/.gitignore b/.gitignore index a410154..fd190e5 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ playground/public/samples/large-* dist-site packages/*/LICENSE __pycache__ + +# Local production-localization validation logs and generated exports +/artifacts/pr6-validation/ 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 +295,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"`; properties `.file = File`, `.icons` (map or resolver, as `icons` above) and `.strings = { … }` (see [UI texts](#ui-texts)); events `load`, `error`, `comment` (`detail`: a `CommentEvent`). ## Core API (no React) 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/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/src/react/common/Dialog.tsx b/src/react/common/Dialog.tsx index d9a8ad8..0ca8de9 100644 --- a/src/react/common/Dialog.tsx +++ b/src/react/common/Dialog.tsx @@ -1,4 +1,4 @@ -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' @@ -21,9 +21,7 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () 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() }, []) @@ -45,7 +43,7 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () ] : []), { label: t.common.cancel, onClick: onClose }, - { label: spec.ok ?? t.common.ok, primary: true, submit: true }, + { label: spec.ok ?? t.common.ok, primary: true, submit: true, onClick: done }, ] return ( diff --git a/src/react/edit/Toolbar.tsx b/src/react/edit/Toolbar.tsx index 88189ea..fbafebe 100644 --- a/src/react/edit/Toolbar.tsx +++ b/src/react/edit/Toolbar.tsx @@ -3,6 +3,7 @@ import { createContext, Fragment, isValidElement, + useCallback, useContext, useEffect, useLayoutEffect, @@ -228,19 +229,33 @@ function PopBox(props: { className?: string; children: ReactNode; onMouseDown?: ) } -/** closes a popup on outside mousedown (shadow-DOM safe: uses the composed path) */ +/** Closes on outside mousedown; attach the returned capture handler to the popup's wrapper for React portals. */ export function useDismiss(ref: RefObject, open: boolean, close: () => void) { const cb = useRef(close) + const insideEvents = useRef(new WeakSet()) cb.current = close + const onMouseDownCapture = useCallback((e: React.MouseEvent) => { + insideEvents.current.add(e.nativeEvent) + }, []) useEffect(() => { if (!open) return + let active = true const on = (e: MouseEvent) => { const el = ref.current - if (el && !e.composedPath().includes(el)) cb.current() + if (!el || e.composedPath().includes(el)) return + // React capture follows the logical tree through portals. Wait for it even if bubbling is stopped. + setTimeout(() => { + if (active && !insideEvents.current.has(e)) cb.current() + insideEvents.current.delete(e) + }, 0) } window.addEventListener('mousedown', on, true) - return () => window.removeEventListener('mousedown', on, true) + return () => { + active = false + window.removeEventListener('mousedown', on, true) + } }, [open, ref]) + return onMouseDownCapture } function DefaultButton(props: ButtonProps) { @@ -328,7 +343,7 @@ function DefaultSelect(props: SelectProps) { const check = props.value !== undefined const sel = check ? options.findIndex((o) => o.value === props.value) : -1 const current = sel >= 0 ? options[sel] : undefined - useDismiss(ref, open, () => setOpen(false)) + const onMouseDownCapture = useDismiss(ref, open, () => setOpen(false)) const pick = (o: DropOption | undefined) => { if (!o || o.disabled) return @@ -397,7 +412,7 @@ function DefaultSelect(props: SelectProps) { const label = props.label !== undefined ? props.label : (current?.label ?? props.placeholder ?? '') return ( - + diff --git a/test/ui.test.tsx b/test/ui.test.tsx index 61e41ce..aa38434 100644 --- a/test/ui.test.tsx +++ b/test/ui.test.tsx @@ -1,10 +1,10 @@ import { describe, expect, test } from 'bun:test' -import type { ReactNode } from 'react' +import type { ReactElement, ReactNode } from 'react' import { renderToStaticMarkup } from 'react-dom/server' import type { Icon as PublicIcon } from '../src' import { ConfirmDialog, PromptDialog, Toast } from '../src/react/common/Dialog' import { Btn, ColorBtn, Dropdown, Icon, Pop, Sep } from '../src/react/edit/Toolbar' -import { OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogProps, type SelectProps, type UIComponents } from '../src/react/ui' +import { DefaultDialog, OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogProps, type SelectProps, type UIComponents } from '../src/react/ui' const seen: { button: ButtonProps[]; select: SelectProps[]; dialog: DialogProps[] } = { button: [], select: [], dialog: [] } const host: Partial = { @@ -44,15 +44,16 @@ describe('UI components', () => { expect(html(, null)).toBe('') expect(html(, null)).toContain('class="de-dd"') expect(html(, null)).toBe('
Saved
') - expect(html(, null)).toBe( - '
', - ) - expect(html(, null)).toBe( - '
', - ) - expect(html(, null)).toBe( - '
Delete?
Gone for good
', - ) + const prompt = html(, null) + expect(prompt).toContain('role="dialog" aria-label="Link"') + expect(prompt).toContain('') + expect([...prompt.matchAll(/]*>([^<]*)<\/button>/g)].map((m) => m[1])).toEqual(['Remove link', 'Cancel', 'OK']) + expect(prompt).toContain('') + const notes = html(, null) + expect(notes).toContain('') + const confirm = html(, null) + expect(confirm).toContain('role="alertdialog" aria-label="Delete?"') + expect(confirm).toContain('') }) test('Button gets title, resolved icon, state, the engine classes and the focus-keeping mouse down', () => { @@ -83,6 +84,8 @@ describe('UI components', () => { expect(html()).toBe('
') expect(html()).toBe('2') expect(seen.select[0]).toMatchObject({ title: 'Style', value: 'b' }) + html() + expect(seen.select[1]).toMatchObject({ label: null, icon: 'bold', className: 'host-trigger' }) }) test('dialogs: prompt submits through its primary action, confirm is an alert', () => { @@ -101,6 +104,31 @@ describe('UI components', () => { expect(confirm.actions.at(-1)).toMatchObject({ label: 'Delete', primary: true, autoFocus: true }) }) + + test('a host footer outside the form can invoke the prompt primary action', () => { + const values: string[] = [] + let closes = 0 + seen.dialog.length = 0 + html( values.push(v) }} onClose={() => closes++} />) + seen.dialog[0].actions.find((a) => a.primary)!.onClick!() + expect(values).toEqual(['Report']) + expect(closes).toBe(1) + }) + + test('the default form submits once without also invoking the submit action callback', () => { + let submissions = 0 + let clicks = 0 + const tree = DefaultDialog({ title: 'Rename', children: null, onClose: noop, onSubmit: () => submissions++, actions: [{ label: 'OK', submit: true, onClick: () => clicks++ }] }) + const form = tree.props.children as ReactElement<{ onSubmit: (e: { preventDefault: () => void }) => void; children: ReactElement<{ children: ReactElement[] }> }> + const actions = form.props.children.props.children[2] as ReactElement<{ children: ReactElement<{ onClick?: () => void; type: string }>[] }> + const button = actions.props.children[0] + expect(button.props.type).toBe('submit') + button.props.onClick?.() + form.props.onSubmit({ preventDefault: noop }) + expect(submissions).toBe(1) + expect(clicks).toBe(0) + }) + test('host Select can render option icons through the public Icon export and host icon provider', () => { // The root entry includes Vite worker imports; check its public type without loading it in Bun. const OptionIcon: typeof PublicIcon = Icon @@ -129,4 +157,5 @@ describe('UI components', () => { ) expect(out).toBe('innert') }) + }) From 695d0cea614574c2e03ee80946b1323eb4f6004d Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:03:10 +0100 Subject: [PATCH 07/20] fix(ui): inherit nested provider strings and defined components --- docs/theming.md | 6 ++++-- src/react/ui.tsx | 6 +++++- test/ui.test.tsx | 31 ++++++++++++++++++++++++++++++- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/docs/theming.md b/docs/theming.md index 7a70f2f..688df4e 100644 --- a/docs/theming.md +++ b/docs/theming.md @@ -70,14 +70,16 @@ gives the class name and style their root needs: ```tsx const root = useThemeRoot(theme) return ( - +
) ``` `OfficeUIProvider` carries what `DocViewer` takes as `icons`, `components`, `locale` and `strings` to views mounted on -their own. +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 diff --git a/src/react/ui.tsx b/src/react/ui.tsx index d9e8200..76c7b38 100644 --- a/src/react/ui.tsx +++ b/src/react/ui.tsx @@ -94,7 +94,11 @@ const UIContext = createContext>({}) /** Replaces UI components for everything below it; an outer provider's components stay for those left out. */ export function UIComponentsProvider({ components, children }: { components?: Partial; children?: ReactNode }) { const outer = useContext(UIContext) - const value = useMemo(() => (components ? { ...outer, ...components } : outer), [outer, components]) + const value = useMemo(() => { + if (!components) return outer + const defined = Object.fromEntries(Object.entries(components).filter(([, component]) => component !== undefined)) + return { ...outer, ...defined } + }, [outer, components]) return {children} } diff --git a/test/ui.test.tsx b/test/ui.test.tsx index aa38434..e1e4f1c 100644 --- a/test/ui.test.tsx +++ b/test/ui.test.tsx @@ -4,6 +4,8 @@ import { renderToStaticMarkup } from 'react-dom/server' import type { Icon as PublicIcon } from '../src' import { ConfirmDialog, PromptDialog, Toast } from '../src/react/common/Dialog' import { Btn, ColorBtn, Dropdown, Icon, Pop, Sep } from '../src/react/edit/Toolbar' +import { useStrings, type Strings } from '../src/react/strings' +import { de } from '../src/locales/de' import { DefaultDialog, OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogProps, type SelectProps, type UIComponents } from '../src/react/ui' const seen: { button: ButtonProps[]; select: SelectProps[]; dialog: DialogProps[] } = { button: [], select: [], dialog: [] } @@ -37,6 +39,11 @@ const host: Partial = { /** renders with the host components, or with `null` with the built-in ones */ const html = (node: ReactNode, components: Partial | null = host) => renderToStaticMarkup({node}) const noop = () => {} +const texts: Strings[] = [] +function TextProbe() { + texts.push(useStrings()) + return null +} describe('UI components', () => { test('without host components the built-in markup is unchanged', () => { @@ -149,7 +156,7 @@ describe('UI components', () => { test('nested providers: inner components win, the outer ones stay for the rest', () => { const out = renderToStaticMarkup( - inner }}> + inner, Toast: undefined }}> @@ -158,4 +165,26 @@ describe('UI components', () => { expect(out).toBe('innert') }) + test('nested OfficeUIProvider inherits texts and merges only defined string overrides', () => { + texts.length = 0 + renderToStaticMarkup( + + + + + + , + ) + expect(texts[1]).toBe(texts[0]) + expect(texts[2].locale).toBe('de-CH') + expect(texts[2].common.ok).toBe('Outer OK') + expect(texts[2].common.cancel).toBe('Inner cancel') + expect(texts[2].file.menu).toBe('Ablage') + expect(texts[2].file.print).toBe(de.file.print) + expect(texts[3].locale).toBe('en-GB') + expect(texts[3].common.ok).toBe('Inner OK') + expect(texts[3].file.menu).toBe('Ablage') + expect(texts[3].file.print).toBe(de.file.print) + expect(de.common.ok).toBe('OK') + }) }) From aedfd2bce15959725d394bc72a0492fbfa518c8f Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:10:07 +0100 Subject: [PATCH 08/20] test(ui): verify rebuilt provider semantics against production ESM --- e2e/ui-built.spec.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++ test/ui.test.tsx | 2 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 e2e/ui-built.spec.ts diff --git a/e2e/ui-built.spec.ts b/e2e/ui-built.spec.ts new file mode 100644 index 0000000..256879a --- /dev/null +++ b/e2e/ui-built.spec.ts @@ -0,0 +1,46 @@ +/** 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' + +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: `/@fs${process.cwd()}/dist/index.js`, german: `/@fs${process.cwd()}/dist/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/test/ui.test.tsx b/test/ui.test.tsx index e1e4f1c..36c9ae0 100644 --- a/test/ui.test.tsx +++ b/test/ui.test.tsx @@ -168,7 +168,7 @@ describe('UI components', () => { test('nested OfficeUIProvider inherits texts and merges only defined string overrides', () => { texts.length = 0 renderToStaticMarkup( - + From b24e0a47b16b15b6a99af046a29dd69dcba22697 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:14:03 +0100 Subject: [PATCH 09/20] fix(ui): retain PR6 string table keys for host compatibility --- src/react/strings/de.ts | 1 + src/react/strings/en.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/react/strings/de.ts b/src/react/strings/de.ts index 8f12b99..68369cd 100644 --- a/src/react/strings/de.ts +++ b/src/react/strings/de.ts @@ -136,6 +136,7 @@ export const de: Strings = { fontSize: 'Schriftgrad', fontSizeDown: 'Schriftgrad verkleinern', fontSizeUp: 'Schriftgrad vergrößern', + more: 'Mehr', moreTools: 'Weitere Werkzeuge', custom: 'Benutzerdefiniert', customColor: 'Benutzerdefinierte Farbe', diff --git a/src/react/strings/en.ts b/src/react/strings/en.ts index 87158f0..b282f41 100644 --- a/src/react/strings/en.ts +++ b/src/react/strings/en.ts @@ -140,6 +140,7 @@ export const en = { fontSize: 'Font size', fontSizeDown: 'Decrease font size', fontSizeUp: 'Increase font size', + more: 'More', moreTools: 'More tools', custom: 'Custom', customColor: 'Custom color', From 9f71702de0f43474b23011719963d86397982ada Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:44:24 +0100 Subject: [PATCH 10/20] test(ui): require fresh emitted packages for browser coverage --- e2e/built-package.ts | 32 ++++++++++++++++++++++++++++++++ e2e/locale-built.spec.ts | 28 ++++++++-------------------- e2e/ui-built.spec.ts | 5 ++++- 3 files changed, 44 insertions(+), 21 deletions(-) create mode 100644 e2e/built-package.ts 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/locale-built.spec.ts b/e2e/locale-built.spec.ts index d45e892..46905a5 100644 --- a/e2e/locale-built.spec.ts +++ b/e2e/locale-built.spec.ts @@ -1,14 +1,16 @@ /** Production-artifact checks: run `bun run build` first, as CI does before browser tests. */ -import { beforeAll, describe, expect, test } from 'bun:test' -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +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 packageRoot = process.env.BUILT_PACKAGE_ROOT ?? process.cwd() -const pkg = `/@fs${packageRoot}/dist/index.js` -const german = `/@fs${packageRoot}/dist/locales/de.js` +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) { @@ -58,20 +60,6 @@ function emfDeck() { return Buffer.from(zipSync(files)) } -// Refuse missing or stale local output rather than silently skipping or testing an old bundle. -function newestSource(path: string): number { - return Math.max(...readdirSync(path, { withFileTypes: true }).map((entry) => { - const file = `${path}/${entry.name}` - return entry.isDirectory() ? newestSource(file) : statSync(file).mtimeMs - })) -} -beforeAll(() => { - expect(existsSync(`${packageRoot}/dist/index.js`), 'Run bun run build before browser tests').toBe(true) - if (!process.env.BUILT_PACKAGE_ROOT) { - expect(statSync(`${packageRoot}/dist/index.js`).mtimeMs, 'dist is stale; run bun run build').toBeGreaterThanOrEqual(newestSource(`${packageRoot}/src`)) - } -}) - 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 () => { @@ -131,7 +119,7 @@ describe('built package localization', () => { 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: `/@fs${packageRoot}/dist/office-engine.embed.js` }) + 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') diff --git a/e2e/ui-built.spec.ts b/e2e/ui-built.spec.ts index 256879a..d2ad794 100644 --- a/e2e/ui-built.spec.ts +++ b/e2e/ui-built.spec.ts @@ -2,6 +2,9 @@ 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 () => { @@ -29,7 +32,7 @@ test('built UI inherits German through formatting-only locales and defined compo } ;(window as any).__builtUpdate = (p: any) => { current = { ...current, ...p }; render() } render() - }, { pkg: `/@fs${process.cwd()}/dist/index.js`, german: `/@fs${process.cwd()}/dist/locales/de.js` }) + }, { 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') From b4d8c85a8b964efbb3c7dcae6c8a9e943054fc83 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:55:52 +0100 Subject: [PATCH 11/20] test(ui): inspect parsed controls instead of serialized markup --- test/ui.test.tsx | 83 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 57 insertions(+), 26 deletions(-) diff --git a/test/ui.test.tsx b/test/ui.test.tsx index 36c9ae0..069c6e6 100644 --- a/test/ui.test.tsx +++ b/test/ui.test.tsx @@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test' import type { ReactElement, ReactNode } from 'react' import { renderToStaticMarkup } from 'react-dom/server' import type { Icon as PublicIcon } from '../src' +import { parseXml, textOf, type XEl } from '../src/core/xml' import { ConfirmDialog, PromptDialog, Toast } from '../src/react/common/Dialog' import { Btn, ColorBtn, Dropdown, Icon, Pop, Sep } from '../src/react/edit/Toolbar' import { useStrings, type Strings } from '../src/react/strings' @@ -38,6 +39,11 @@ const host: Partial = { } /** renders with the host components, or with `null` with the built-in ones */ const html = (node: ReactNode, components: Partial | null = host) => renderToStaticMarkup({node}) +/** React's static markup is XML-compatible; inspect its elements rather than its serialization. */ +const tree = (markup: string) => parseXml(`${markup}`) +const elements = (el: XEl): XEl[] => el.c.flatMap((child) => [child, ...elements(child)]) +const tagged = (el: XEl, name: string) => elements(el).filter((child) => child.n === name) +const classes = (el: XEl) => el.a.class?.split(/\s+/) ?? [] const noop = () => {} const texts: Strings[] = [] function TextProbe() { @@ -46,28 +52,41 @@ function TextProbe() { } describe('UI components', () => { - test('without host components the built-in markup is unchanged', () => { - expect(html(, null)).toStartWith('') - expect([...prompt.matchAll(/]*>([^<]*)<\/button>/g)].map((m) => m[1])).toEqual(['Remove link', 'Cancel', 'OK']) - expect(prompt).toContain('') - const notes = html(, null) - expect(notes).toContain('') - const confirm = html(, null) - expect(confirm).toContain('role="alertdialog" aria-label="Delete?"') - expect(confirm).toContain('') + test('built-in controls retain their roles, classes and action order', () => { + const button = tagged(tree(html(, null)), 'button')[0] + expect(button.a).toMatchObject({ type: 'button', title: 'Bold', 'aria-label': 'Bold', 'aria-pressed': 'true' }) + expect(classes(button)).toEqual(expect.arrayContaining(['de-tb', 'de-tb-on'])) + expect(classes(tagged(tree(html(, null)), 'span')[0])).toContain('de-tb-sep') + expect(elements(tree(html(, null))).some((el) => classes(el).includes('de-dd'))).toBe(true) + const toast = tagged(tree(html(, null)), 'div')[0] + expect(toast.a.role).toBe('status') + expect(classes(toast)).toContain('de-toast') + expect(textOf(toast)).toBe('Saved') + const prompt = tree(html(, null)) + expect(elements(prompt).find((el) => el.a.role === 'dialog')?.a['aria-label']).toBe('Link') + const actions = tagged(prompt, 'button') + expect(actions.map(textOf)).toEqual(['Remove link', 'Cancel', 'OK']) + expect(actions[0].a.type).toBe('button') + expect(classes(actions[0])).toEqual(expect.arrayContaining(['de-btn', 'de-dialog-extra'])) + expect(actions[2].a.type).toBe('submit') + expect(classes(actions[2])).toContain('de-btn-primary') + const notes = tagged(tree(html(, null)), 'textarea')[0] + expect(notes.a.rows).toBe('3') + expect(textOf(notes)).toBe('Text') + const confirm = tree(html(, null)) + expect(elements(confirm).find((el) => el.a.role === 'alertdialog')?.a['aria-label']).toBe('Delete?') + const primary = tagged(confirm, 'button').find((el) => classes(el).includes('de-btn-primary'))! + expect(primary.a.type).toBe('button') + expect(primary.a).toHaveProperty('autofocus') + expect(textOf(primary)).toBe('Delete') }) test('Button gets title, resolved icon, state, the engine classes and the focus-keeping mouse down', () => { seen.button.length = 0 const out = html() - expect(out).toContain('data-host="button"') - expect(out).toContain(' { test('Separator and Select are replaced; Select gets the options and value', () => { seen.select.length = 0 - expect(html()).toBe('
') - expect(html()).toBe('2') + expect(tagged(tree(html()), 'hr')[0].a['data-host']).toBe('sep') + const select = tagged(tree(html()), 'span')[0] + expect(select.a['data-host']).toBe('select') + expect(textOf(select)).toBe('2') expect(seen.select[0]).toMatchObject({ title: 'Style', value: 'b' }) html() expect(seen.select[1]).toMatchObject({ label: null, icon: 'bold', className: 'host-trigger' }) @@ -98,9 +119,9 @@ describe('UI components', () => { test('dialogs: prompt submits through its primary action, confirm is an alert', () => { seen.dialog.length = 0 const out = html() - expect(out).toContain('aria-label="Link"') - expect(out).toContain('value="https://x"') - expect(out).toContain('Remove link|Cancel|OK') + const rendered = tree(out) + expect(tagged(rendered, 'section')[0].a['aria-label']).toBe('Link') + expect(tagged(rendered, 'input')[0].a.value).toBe('https://x') html() const [prompt, confirm] = seen.dialog expect(prompt.onSubmit).toBeFunction() @@ -145,12 +166,18 @@ describe('UI components', () => {
, ) - expect(out).toContain('') - expect(out).toContain(' classes(el).includes('de-icon'))! + expect(custom.a['aria-hidden']).toBe('true') + expect(textOf(custom)).toBe('host bold') + expect(tagged(custom, 'b').length).toBe(1) + expect(tagged(rendered, 'svg')[0].a).toMatchObject({ width: '16', height: '16' }) }) test('Toast', () => { - expect(html()).toBe('Saved') + const toast = tagged(tree(html()), 'output')[0] + expect(toast.a['data-host']).toBe('toast') + expect(textOf(toast)).toBe('Saved') }) test('nested providers: inner components win, the outer ones stay for the rest', () => { @@ -162,7 +189,11 @@ describe('UI components', () => {
, ) - expect(out).toBe('innert') + const rendered = tree(out) + expect(textOf(tagged(rendered, 'i')[0])).toBe('inner') + const toast = tagged(rendered, 'output')[0] + expect(toast.a['data-host']).toBe('toast') + expect(textOf(toast)).toBe('t') }) test('nested OfficeUIProvider inherits texts and merges only defined string overrides', () => { From 8ec37cf2c3d82c2aa36c0f30a8887d64f35542df Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 14 Nov 2026 22:35:46 +0100 Subject: [PATCH 12/20] feat(viewer): headless mode and a controller for host-drawn controls A host that draws its own controls around the document gets ``. `headless` leaves the viewer with the document alone: no top bar, zoom control, outline panel or button, sheet tabs, slide list or Present button. While editing, the formatting toolbar keeps its row, and an explicit `toolbar` brings back the top bar (File menu, comments, Save). The controller (src/react/controller.ts, framework-free) holds the state - kind, loading, editing, canEdit, dirty, saving, canUndo/canRedo, zoom, page, outline (headings, sheets or slides), status - and runs the commands: setEditing, save, undo, redo, zoomIn/zoomOut/setZoom, goto, gotoPage, present, print, fileAction, toggleComments. The viewer and its mounted view publish to it and register their commands; without one from the host the viewer keeps its own, so nothing else changes. When the viewer or its view unmounts, its part of the state is cleared, so a controller that outlives it shows no document. `useViewerState(ctl)` reads the state in React. - DOCX: headings are read for the controller whether or not the outline panel is open (once edits rest), with the current one, which stays the heading jumped to while its page is in view; DocxEditor reports its undo/redo history after each step, offered only while editing. - XLSX: the visible sheets as the outline; undo/redo counted per edit, cleared when a sheet is added, deleted, moved, renamed or imported, as the worker's history is. A sheet switched to through the controller keeps a formula being typed open, for cross-sheet references, as the built-in tabs do. - PPTX: slides titled by their title placeholder, read by a title-only worker call (`pptx.titles`, no layout) only while a host subscribes (`observed`, `watchObserved`), and kept current as slides are edited; symbol-font characters in titles as their Unicode look-alikes. Undo and redo through the controller do nothing outside edit mode. - `onLoad` fires once per opened document, also with an inline callback. - mount() returns the controller; has .controller. - e2e harness: PLAYWRIGHT_CHANNEL picks an installed browser. Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 58 +++++++- e2e/app/main.tsx | 9 +- e2e/controller.spec.ts | 112 +++++++++++++++ e2e/harness.ts | 3 +- src/core/pptx/parser.ts | 31 +++++ src/core/pptx/types.ts | 2 + src/core/worker/engine.ts | 2 + src/core/worker/protocol.ts | 2 + src/embed.ts | 16 ++- src/index.ts | 1 + src/react/DocViewer.tsx | 53 +++++++- src/react/common/Slots.tsx | 7 + src/react/common/Status.tsx | 6 +- src/react/common/ZoomControl.tsx | 8 +- src/react/controller.ts | 227 +++++++++++++++++++++++++++++++ src/react/docx/DocxEditor.ts | 20 ++- src/react/docx/DocxToolbar.tsx | 5 +- src/react/docx/DocxView.tsx | 63 ++++++++- src/react/pptx/PptxView.tsx | 70 +++++++++- src/react/styles.css | 3 + src/react/xlsx/XlsxView.tsx | 59 +++++++- test/controller.test.ts | 79 +++++++++++ test/core.test.ts | 4 + test/docx-edge.test.ts | 12 ++ 24 files changed, 814 insertions(+), 38 deletions(-) create mode 100644 e2e/controller.spec.ts create mode 100644 src/react/controller.ts create mode 100644 test/controller.test.ts diff --git a/docs/api.md b/docs/api.md index 378d58d..b760d71 100644 --- a/docs/api.md +++ b/docs/api.md @@ -81,8 +81,62 @@ CSS is auto-injected, no import needed (or import `@p10node/office-engine/styles | `onDirtyChange` | `(dirty) => void` | – | Whether there are unsaved changes | | `collab` | `CollabOptions` | – | Real-time collaboration, see [collaboration](collaboration.md) | | `comments` | `CommentOptions \| false` | `{}` | Comments (see below); `false` hides them | -| `onLoad` | `(client) => void` | – | | +| `onLoad` | `(client) => void` | – | Once per opened document | | `onError` | `(error) => void` | – | | +| `controller` | `ViewerController` | its own | The viewer's state and commands for the host, see [headless mode](#headless-mode) | +| `headless` | `boolean` | `false` | The document alone: no top bar, zoom control, outline panel, sheet tabs or slide list | +| `icons` | `Partial>` | – | The host's icons by name (`ICON_NAMES`), sized by font-size (1em), instead of the built-in ones | + +### Headless mode + +For a host that draws its own controls around the document: `headless` leaves the viewer with the document alone, and a +`controller` (`createViewerController()`) carries its state and the commands that drive it. While editing, the formatting +toolbar keeps its row above the document; dialogs, the find bar and the comments panel are the viewer's own. `toolbar` +set explicitly brings back the top bar (File menu, comments, Save) and leaves the rest headless. + +```tsx +import { createViewerController, DocViewer, useViewerState } from '@p10node/office-engine' +import { useMemo } from 'react' + +function Viewer({ file }: { file: File }) { + const ctl = useMemo(() => createViewerController(), []) + const s = useViewerState(ctl) + return ( + <> + + {s.zoom && } + {s.canEdit && } + {s.dirty && } + + + ) +} +``` + +| `ViewerState` | Meaning | +|---------------|---------| +| `rev` | counts the changes (the state object is replaced on each) | +| `kind` | `'docx'`, `'xlsx'`, `'pptx'`, or `null` before a document is open | +| `loading` | loading or downloading | +| `editing`, `canEdit` | in edit mode; whether editing is possible (allowed, not view only) | +| `dirty`, `saving` | unsaved changes; a save running | +| `canUndo`, `canRedo` | whether undo / redo can run (spreadsheets count the edits made here; presentations offer redo whenever editing) | +| `zoom` | `{ value: 'fit' \| number, effective }`, `null` for spreadsheets | +| `page` | `{ current, count }` from 1: the page (documents; `count` 0 while laid out) or slide in view; `null` for spreadsheets | +| `outline` | `{ kind, items: [{ id, title, level, current }] }`: a document's headings, a workbook's visible sheets, a presentation's slides (titled by their title placeholder, else "Slide n") | +| `status` | the status line ("Page 2 of 7 · 1,204 words", "Slide 3 of 12", "200 rows × 8 cols") | + +Commands: `setEditing(on)`, `save()`, `undo()`, `redo()`, `zoomIn()`, `zoomOut()`, `setZoom('fit' | number)`, +`goto(outlineId)`, `gotoPage(n)`, `present()` (a slideshow from the slide in view), `print()`, `fileAction(id)` (a File menu +action: `pdf`, `html`, `text:md`, `details`, `rename`…), `toggleComments(open?)`. A command the open document has no use +for does nothing. `subscribe(fn)` returns its unsubscribe; `snapshot()` the current state. Without `react`, `mount()` +returns the controller (`mounted.controller`), and `` has it as `element.controller`. ### Comments @@ -296,7 +350,7 @@ Document content stays in its original language. Default new sheet names, the au ``` -``: attributes `src`, `name`, `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `locale="en-GB"` (number/date formatting), `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`; properties `.file = File`, `.icons` (map or resolver, as `icons` above) and `.strings = { … }` (see [UI texts](#ui-texts)); events `load`, `error`, `comment` (`detail`: a `CommentEvent`). +``: 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/e2e/app/main.tsx b/e2e/app/main.tsx index f3ffbb2..1573173 100644 --- a/e2e/app/main.tsx +++ b/e2e/app/main.tsx @@ -5,10 +5,11 @@ * &icons=1: every icon from a host resolver, as `` * texts: &locale=de-DE opts into the explicitly imported German table, &fileLabel=… overrides the File label * &components=1: the host's own Button, Separator, Dialog and Toast (`data-host-*` markers) + * &headless=1: the document alone; the viewer is driven through window.__ctl (its controller) either way */ import { useState } from 'react' import { createRoot } from 'react-dom/client' -import { DocViewer, type DocViewerProps, type FileMenuItem, type UIComponents } from '../../src' +import { createViewerController, DocViewer, type DocViewerProps, type FileMenuItem, type UIComponents, type ViewerController } from '../../src' import { de } from '../../src/locales/de' type Ev = { type: string; [k: string]: unknown } @@ -18,9 +19,13 @@ declare global { __setProps: (p: Partial) => void __setLanguage: (language: 'en' | 'de-DE') => void __german: typeof de + __ctl: ViewerController } } window.__events = [] +window.__ctl = createViewerController() +// a host reading the state, as the tests do through snapshot(): views read slide titles only for one +window.__ctl.subscribe(() => {}) const log = (e: Ev) => window.__events.push(e) const q = new URLSearchParams(location.search) @@ -99,6 +104,8 @@ const initial: DocViewerProps = { injectStyles: flag('injectStyles'), locale: (texts ? undefined : q.get('locale') as DocViewerProps['locale']) ?? undefined, strings: q.has('fileLabel') ? { ...texts, file: { ...(texts?.file ?? {}), menu: q.get('fileLabel')! } } : texts, + headless: flag('headless'), + controller: window.__ctl, onSave: q.has('onSave') ? async (blob, name) => void log({ type: 'save', name, b64: await b64(blob) }) : undefined, onDirtyChange: (dirty) => log({ type: 'dirty', dirty }), onRename: (name) => log({ type: 'rename', name }), diff --git a/e2e/controller.spec.ts b/e2e/controller.spec.ts new file mode 100644 index 0000000..ea4d760 --- /dev/null +++ b/e2e/controller.spec.ts @@ -0,0 +1,112 @@ +import { describe, expect, test } from 'bun:test' +import type { ViewerState } from '../src' +import { useBrowser, viewer, 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 }) + +describe('controller and headless mode', () => { + test('docx: zoom, pages and headings through the controller; no chrome of its own', async () => { + const v = await viewer({ 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('docx: editing and saving through the controller', async () => { + const v = await viewer({ 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({ 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('xlsx: the sheets as the outline, no tabs of its own', async () => { + const v = await viewer({ 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('pptx: slides, zoom and the slide in view; no thumbnails, zoom or Present button', async () => { + const v = await viewer({ 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({ 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/harness.ts b/e2e/harness.ts index 99ccf4f..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 () => { diff --git a/src/core/pptx/parser.ts b/src/core/pptx/parser.ts index f2da5ed..af18afe 100644 --- a/src/core/pptx/parser.ts +++ b/src/core/pptx/parser.ts @@ -157,6 +157,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(textOf)) : '' + if (t) return t + } + return '' +} + const masterType = (t: string) => (t === 'ctrTitle' ? 'title' : t === 'subTitle' || t === 'obj' ? 'body' : t) function indexPlaceholders(spTree: XEl | undefined) { @@ -312,9 +328,17 @@ export class PptxPresentation { bg: r.background(), els, hidden: slide.root.a.show === '0', + title: r.title, } } + /** 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 + } + get defaults() { return this.defaultTextStyle } @@ -458,6 +482,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, @@ -873,6 +899,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.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 810a008..b7513c1 100644 --- a/src/core/pptx/types.ts +++ b/src/core/pptx/types.ts @@ -124,6 +124,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/engine.ts b/src/core/worker/engine.ts index a797e98..d44f399 100644 --- a/src/core/worker/engine.ts +++ b/src/core/worker/engine.ts @@ -238,6 +238,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 4be56bb..8c99142 100644 --- a/src/core/worker/protocol.ts +++ b/src/core/worker/protocol.ts @@ -100,6 +100,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[] 'pptx.setText'(index: number, sid: number, paras: PParaSpec[]): SlideModel 'pptx.shapes'(index: number, ops: ShapeOp[]): SlideModel 'pptx.slides'(op: SlideOp): PresentationMeta diff --git a/src/embed.ts b/src/embed.ts index 02eb3db..57c9589 100644 --- a/src/embed.ts +++ b/src/embed.ts @@ -4,12 +4,15 @@ 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 { 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 } @@ -18,10 +21,12 @@ export interface MountedViewer { export function mount(el: HTMLElement, options: MountOptions): MountedViewer { let root: Root | null = createRoot(el) let props = options + const controller = options.controller ?? new ViewerController() 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 { + controller, update(next) { props = { ...props, ...next } render() @@ -41,9 +46,10 @@ export function mount(el: HTMLElement, options: MountOptions): MountedViewer { * 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`); * `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', 'locale'] + 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 @@ -51,6 +57,8 @@ export class OfficeViewerElement extends HTMLElement { // Keep event callbacks stable across attribute/property updates: changing UI texts must not replay load/error events. private onLoad: NonNullable = (client) => this.dispatchEvent(new CustomEvent('load', { detail: { kind: client.kind, name: client.name } })) private onError: NonNullable = (error) => this.dispatchEvent(new CustomEvent('error', { detail: error })) + /** the viewer's state and commands, the same object for the element's whole life */ + readonly controller = new ViewerController() get file() { return this._file @@ -99,7 +107,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', @@ -111,6 +119,8 @@ export class OfficeViewerElement extends HTMLElement { 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 84bc54b..3eafcee 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,6 +13,7 @@ export { THEME_TOKENS, createTheme, themeStyle, useThemeRoot, type Theme, type T 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 { ViewerController, createViewerController, useViewerState, 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/react/DocViewer.tsx b/src/react/DocViewer.tsx index e605850..ab9feab 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -8,6 +8,7 @@ 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 { ViewerController } from './controller' import { DetailsDialog } from './file/DetailsDialog' import { FileMenu, useFileActions, type FileMenuItem } from './file/FileMenu' import { importFile, type Imported } from './file/importFile' @@ -122,6 +123,17 @@ export interface DocViewerProps { 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' } @@ -153,7 +165,12 @@ export function DocViewer(props: DocViewerProps) { function Viewer(props: DocViewerProps) { const t = useStrings() const fmtBytes = (n: number) => formatBytes(t, n) - const { src, name, className, style, toolbar = true, toolbarExtra, zoom, thumbnails, headers, credentials, worker, styleTarget, theme, onLoad, onError } = props + 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(() => new ViewerController(), []) + const ctl = props.controller ?? ownCtl 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) @@ -305,9 +322,12 @@ function Viewer(props: DocViewerProps) { cmCtl.select(root) }, [cmCtl, cmFocus, cmState.rev]) + // once per opened document, also when the host passes a new callback on every render + const onLoadRef = useRef(onLoad) + onLoadRef.current = onLoad useEffect(() => { - if (client) onLoad?.(client) - }, [client, onLoad]) + if (client) onLoadRef.current?.(client) + }, [client]) useEffect(() => { if (error) onError?.(error) }, [error, onError]) @@ -385,8 +405,8 @@ function Viewer(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, headless }), + [barEl, docEditable, setDocDirty, save, allowDownload, client, ctl, headless], ) const editSource = (text: string) => { @@ -541,6 +561,25 @@ function Viewer(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 = allowEdit && !readOnly && !codeShown + useEffect(() => { + ctl.update({ kind: client?.kind ?? null, loading: busy, editing: docEditable, canEdit: 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 } + useEffect(() => { + 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), + }) + return () => ctl.attachViewer(null) + }, [ctl]) + let body: ReactNode if (error) { body = ( @@ -568,7 +607,7 @@ function Viewer(props: DocViewerProps) { return ( -
+
{toolbar && (
{client && {client.info?.from ?? client.info?.converted ?? (client.info?.imported ? IMPORTED_BADGE[client.info.imported] : client.kind)}} @@ -622,7 +661,7 @@ function Viewer(props: DocViewerProps) {
)} - {toolbar && client && docEditable &&
} + {(toolbar || headless) && client && docEditable &&
}
{codeShown && (
diff --git a/src/react/common/Slots.tsx b/src/react/common/Slots.tsx index b5541e5..f55aafa 100644 --- a/src/react/common/Slots.tsx +++ b/src/react/common/Slots.tsx @@ -3,6 +3,7 @@ import { createPortal } from 'react-dom' import { ToolbarRow } from '../edit/Toolbar' import type { DocumentClient } from '../../core/worker/client' import type { Printable } from '../file/print' +import type { ViewerController } from '../controller' /** What the active view offers to the File menu. */ export interface FileOps { @@ -33,6 +34,10 @@ export interface ViewerApi { fileOps: { current: FileOps | null } /** set by the mounted view (see useSelectAll): Ctrl/⌘+A */ selectAll: { current: (() => void) | null } + /** the viewer's controller: the view publishes its state and registers its commands there */ + ctl: ViewerController | null + /** the host draws the controls: the view shows no zoom, outline, sheet tabs or slide list of its own */ + headless: boolean } export const ViewerContext = createContext({ @@ -44,6 +49,8 @@ export const ViewerContext = createContext({ client: null, fileOps: { current: null }, selectAll: { current: null }, + ctl: null, + headless: false, }) export const useViewer = () => useContext(ViewerContext) diff --git a/src/react/common/Status.tsx b/src/react/common/Status.tsx index 61b8bce..a1cefea 100644 --- a/src/react/common/Status.tsx +++ b/src/react/common/Status.tsx @@ -1,13 +1,17 @@ import { createContext, useContext, useEffect } from 'react' import { createPortal } from 'react-dom' +import { useViewer } from './Slots' /** Toolbar slot provided by DocViewer; views portal their status text into it (no parent re-render). */ export const StatusContext = createContext(null) +/** The view's status line: in the viewer's top bar, and in its controller's state (a headless viewer has no bar). */ export function Status({ text, onStatus }: { text: string; onStatus?: (s: string) => void }) { const el = useContext(StatusContext) + const { ctl } = useViewer() useEffect(() => { onStatus?.(text) - }, [text, onStatus]) + ctl?.update({ status: text }) + }, [text, onStatus, ctl]) return el ? createPortal(text, el) : null } diff --git a/src/react/common/ZoomControl.tsx b/src/react/common/ZoomControl.tsx index 2e8ac0d..c90cb94 100644 --- a/src/react/common/ZoomControl.tsx +++ b/src/react/common/ZoomControl.tsx @@ -5,10 +5,14 @@ export type Zoom = number | 'fit' const STEPS = [0.25, 0.33, 0.5, 0.67, 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3] +/** the zoom step after `effective` in direction `dir`, or undefined at the end of the range */ +export function stepZoom(effective: number, dir: 1 | -1): number | undefined { + return dir > 0 ? STEPS.find((s) => s > effective + 0.001) : [...STEPS].reverse().find((s) => s < effective - 0.001) +} + export function ZoomControl({ zoom, effective, onChange }: { zoom: Zoom; effective: number; onChange: (z: Zoom) => void }) { const step = (dir: 1 | -1) => { - const cur = effective - const next = dir > 0 ? STEPS.find((s) => s > cur + 0.001) : [...STEPS].reverse().find((s) => s < cur - 0.001) + const next = stepZoom(effective, dir) if (next) onChange(next) } const t = useStrings() diff --git a/src/react/controller.ts b/src/react/controller.ts new file mode 100644 index 0000000..e7af907 --- /dev/null +++ b/src/react/controller.ts @@ -0,0 +1,227 @@ +/** + * A viewer's controller: what the shown document's view is doing (zoom, page, outline, editing, unsaved changes) and the + * commands that drive it, for a host that draws its own controls around a headless viewer + * (``). Framework-free: `subscribe` + `snapshot` (for `useSyncExternalStore` or any + * store), state replaced as a whole on every change (`rev` counts them). The viewer and its mounted view publish their + * state and register the commands they can run; a command with nobody to run it does nothing. + */ +import { useEffect, useSyncExternalStore } from 'react' +import type { DocKind } from '../core/opc' +import { stepZoom, type Zoom } from './common/ZoomControl' +import { useLatest } from './common/hooks' + +/** an entry of the outline: a document's heading, a workbook's sheet, a presentation's slide */ +export interface OutlineItem { + id: string + title: string + /** 0 for the top level (headings only go deeper) */ + level: number + /** the one in view */ + current: boolean +} + +export interface ViewerOutline { + kind: 'headings' | 'sheets' | 'slides' + items: OutlineItem[] +} + +export interface ViewerState { + /** counts the changes */ + rev: number + /** the open document's kind, null before one is open */ + kind: DocKind | null + /** loading or downloading */ + loading: boolean + editing: boolean + /** whether editing is possible (allowed, and the file is not view only) */ + canEdit: boolean + /** unsaved changes */ + dirty: boolean + saving: boolean + canUndo: boolean + canRedo: boolean + /** `value` as set ('fit' or a factor), `effective` the factor it comes to; null where the view has no zoom (spreadsheets) */ + zoom: { value: Zoom; effective: number } | null + /** the page or slide in view, from 1, and how many there are (0 while a document is still being laid out) */ + page: { current: number; count: number } | null + outline: ViewerOutline | null + /** the view's status line ("Page 2 of 7 · 1,204 words") */ + status: string +} + +/** commands a mounted view runs (each optional: a spreadsheet has no zoom) */ +export interface ViewCommands { + setZoom?(z: Zoom): void + goto?(id: string): void + gotoPage?(n: number): void + undo?(): void + redo?(): void + present?(): void +} + +/** commands the viewer runs */ +export interface ViewerCommands { + setEditing(on: boolean): void + save(): Promise + fileAction(id: string): void + toggleComments(open?: boolean): void +} + +/** the view's part of the state, cleared when a view goes */ +const VIEW_STATE = { canUndo: false, canRedo: false, zoom: null, page: null, outline: null, status: '' } as const + +/** the viewer's part of the state, cleared when the viewer goes, so a controller that outlives it shows no document */ +const VIEWER_STATE = { kind: null, loading: false, editing: false, canEdit: false, dirty: false, saving: false } as const + +const EMPTY: ViewerState = { rev: 0, ...VIEWER_STATE, ...VIEW_STATE } + +/** equal for the state's purposes: the same primitive, or the same JSON (small objects and the outline) */ +function same(a: unknown, b: unknown): boolean { + if (a === b) return true + if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false + return JSON.stringify(a) === JSON.stringify(b) +} + +export class ViewerController { + private state: ViewerState = EMPTY + private subs = new Set<() => void>() + private watchers = new Set<() => void>() + private view: ViewCommands | null = null + private viewer: ViewerCommands | null = null + + subscribe = (fn: () => void) => { + const first = this.subs.size === 0 + this.subs.add(fn) + if (first) for (const w of this.watchers) w() + return () => { + this.subs.delete(fn) + } + } + + /** whether a host reads the state: views skip work that only the controller's state needs while nobody does */ + get observed(): boolean { + return this.subs.size > 0 + } + + /** calls `fn` when the first subscriber arrives */ + watchObserved(fn: () => void): () => void { + this.watchers.add(fn) + return () => { + this.watchers.delete(fn) + } + } + + snapshot = () => this.state + + // ---------------------------------------------------------------- commands + + setEditing(on: boolean) { + this.viewer?.setEditing(on) + } + + /** builds the edited file and hands it to `onSave` (or downloads it) */ + save(): Promise { + return this.viewer?.save() ?? Promise.resolve() + } + + undo() { + this.view?.undo?.() + } + + redo() { + this.view?.redo?.() + } + + setZoom(z: Zoom) { + this.view?.setZoom?.(z) + } + + zoomIn() { + this.zoomStep(1) + } + + zoomOut() { + this.zoomStep(-1) + } + + /** shows an outline entry: scrolls to a heading, shows a sheet or a slide */ + goto(id: string) { + this.view?.goto?.(id) + } + + /** scrolls to a page or slide, from 1 */ + gotoPage(n: number) { + this.view?.gotoPage?.(n) + } + + /** a presentation as a slideshow, from the slide in view */ + present() { + this.view?.present?.() + } + + print() { + this.fileAction('print') + } + + /** a File menu action by its id: 'pdf', 'html', 'text:md', 'details', 'rename'… (see FileMenu) */ + fileAction(id: string) { + this.viewer?.fileAction(id) + } + + /** the comments panel open (true), closed (false) or the other way round */ + toggleComments(open?: boolean) { + this.viewer?.toggleComments(open) + } + + private zoomStep(dir: 1 | -1) { + const z = this.state.zoom + const next = z && stepZoom(z.effective, dir) + if (next) this.setZoom(next) + } + + // ---------------------------------------------------------------- published by the viewer and its view + + /** @internal the state changed: only what differs counts as a change */ + update(p: Partial>) { + let changed = false + for (const k of Object.keys(p) as (keyof typeof p)[]) { + if (!same(this.state[k], p[k])) { + changed = true + break + } + } + if (!changed) return + this.state = { ...this.state, ...p, rev: this.state.rev + 1 } + for (const fn of this.subs) fn() + } + + /** @internal the mounted view's commands; null when it goes (its state is cleared) */ + attachView(c: ViewCommands | null) { + this.view = c + if (!c) this.update(VIEW_STATE) + } + + /** @internal the viewer's commands; null when it goes (its state is cleared) */ + attachViewer(c: ViewerCommands | null) { + this.viewer = c + if (!c) this.update(VIEWER_STATE) + } +} + +export const createViewerController = () => new ViewerController() + +/** The controller's state, rendering again whenever it changes: for a host's own controls in React. */ +export function useViewerState(ctl: ViewerController): ViewerState { + return useSyncExternalStore(ctl.subscribe, ctl.snapshot, ctl.snapshot) +} + +/** Registers a view's commands (the latest closures each render) while it is mounted. */ +export function useViewCommands(ctl: ViewerController | null, commands: ViewCommands) { + const latest = useLatest(commands) + useEffect(() => { + if (!ctl) return + const call = (k: K) => ((...a: unknown[]) => (latest.current[k] as ((...x: unknown[]) => void) | undefined)?.(...a)) as ViewCommands[K] + ctl.attachView({ setZoom: call('setZoom'), goto: call('goto'), gotoPage: call('gotoPage'), undo: call('undo'), redo: call('redo'), present: call('present') }) + return () => ctl.attachView(null) + }, [ctl, latest]) +} diff --git a/src/react/docx/DocxEditor.ts b/src/react/docx/DocxEditor.ts index d99a918..7e5442e 100644 --- a/src/react/docx/DocxEditor.ts +++ b/src/react/docx/DocxEditor.ts @@ -204,6 +204,8 @@ export class DocxEditor implements RichHost { /** paragraphs whose look on screen may be behind their style / list: a conversion was asked, none was applied yet */ private stale = new Set() onState?: (s: FormatState | null) => void + /** whether undo / redo can run, after every change of the selection or the document (the viewer's controller) */ + onHistory?: (canUndo: boolean, canRedo: boolean) => void /** image selection changed (overlay with resize handles) */ onImage?: (img: FormatState['img'] | null) => void /** style list changed (a built-in style was added to the document, a style got another look) */ @@ -732,7 +734,18 @@ export class DocxEditor implements RichHost { return list.map((b) => (b.t === 'p' && b.pid !== undefined && cur.has(b.pid) ? cur.get(b.pid)! : b)) } + // the state published while an entry is applied comes before its move to the other stack: publish again after undo() { + this.undoStep() + this.onHistory?.(this.canUndo, this.canRedo) + } + + redo() { + this.redoStep() + this.onHistory?.(this.canUndo, this.canRedo) + } + + private undoStep() { const e = this.history.pop() if (!e) return if (e.group) { @@ -740,7 +753,7 @@ export class DocxEditor implements RichHost { for (const part of [...e.group].reverse()) { this.history.push(part) const n = this.future.length - this.undo() + this.undoStep() if (this.future.length > n) this.future.pop() } this.future.push(e) @@ -768,14 +781,14 @@ export class DocxEditor implements RichHost { this.future.push(e) } - redo() { + private redoStep() { const e = this.future.pop() if (!e) return if (e.group) { for (const part of e.group) { this.future.push(part) const n = this.history.length - this.redo() + this.redoStep() if (this.history.length > n) this.history.pop() } this.history.push(e) @@ -1882,6 +1895,7 @@ export class DocxEditor implements RichHost { const st = sel ? this.state(sel) : null this.onState?.(st) this.onImage?.(st?.img ?? null) + this.onHistory?.(this.canUndo, this.canRedo) } onSelection(sel: Sel | null) { diff --git a/src/react/docx/DocxToolbar.tsx b/src/react/docx/DocxToolbar.tsx index 719bdf4..cbb6950 100644 --- a/src/react/docx/DocxToolbar.tsx +++ b/src/react/docx/DocxToolbar.tsx @@ -101,7 +101,8 @@ export function DocxToolbar(props: { styles: StyleInfo[] onFind: () => void outline: boolean - onOutline: () => void + /** the outline panel opened / closed; no button without it (a headless viewer: the host shows the outline) */ + onOutline?: () => void painter: boolean onLink: () => void image: ImageActions @@ -302,7 +303,7 @@ export function DocxToolbar(props: { editor.insertPageBreak()} /> editor.clearFormat()} /> - + {props.onOutline && } ) diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index 4d9d137..2559af9 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -8,6 +8,7 @@ import { claimFocus, lowerIndex, useForceUpdate, useIsoLayoutEffect, useScroll, import { useFileOps, useSelectAll, useViewer } from '../common/Slots' import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' +import { useViewCommands } from '../controller' import { ContextMenu, MOD, type MenuItem } from '../common/ContextMenu' import { PromptDialog, Toast, type PromptSpec } from '../common/Dialog' import { domFromPos, getSel, opInsert, posFromDom, selPoints } from '../edit/input' @@ -751,12 +752,19 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp // eslint-disable-next-line react-hooks/exhaustive-deps [outline, version, titleId], ) - const topBlock = pages[Math.max(0, cur - 1)]?.start ?? 0 - const activeHeading = headings.reduce((acc, h, i) => (h.bi <= Math.max(topBlock, caretBi) ? i : acc), -1) + // the heading jumped to counts as current while its page is the one in view, though it may sit + // below headings further up that page + const [jumpBi, setJumpBi] = useState(-1) + const curPage = pages[Math.max(0, cur - 1)] + const topBlock = curPage?.start ?? 0 + const jumped = curPage && jumpBi >= curPage.start && jumpBi < curPage.end ? jumpBi : -1 + const atBlock = Math.max(topBlock, caretBi, jumped) + const activeHeading = headings.reduce((acc, h, i) => (h.bi <= atBlock ? i : acc), -1) const gotoBlock = (bi: number) => { const sc = scrollRef.current const pi = pages.findIndex((p) => bi >= p.start && bi < p.end) if (!sc || pi < 0) return + setJumpBi(bi) sc.scrollTop = Math.max(0, tops[pi] - 16) requestAnimationFrame(() => requestAnimationFrame(() => { @@ -767,6 +775,51 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp ) } + // ---- controller: zoom, page, headings, undo ---- + const { ctl, headless } = viewer + // the headings for the controller: read again once the document stops changing, not on every keystroke + const [ctlHeadings, setCtlHeadings] = useState<{ bi: number; lvl: number; text: string }[]>([]) + useEffect(() => { + if (!ctl) return + const id = setTimeout(() => setCtlHeadings(outlineOf(st.blocks, titleId)), 150) + return () => clearTimeout(id) + }, [ctl, version, titleId, st]) + const ctlActive = ctlHeadings.reduce((acc, h, i) => (h.bi <= atBlock ? i : acc), -1) + useEffect(() => { + ctl?.update({ zoom: { value: zoom, effective: z } }) + }, [ctl, zoom, z]) + useEffect(() => { + ctl?.update({ page: { current: cur, count: pageCount } }) + }, [ctl, cur, pageCount]) + useEffect(() => { + ctl?.update({ outline: { kind: 'headings', items: ctlHeadings.map((h, i) => ({ id: String(h.bi), title: h.text, level: h.lvl, current: i === ctlActive })) } }) + }, [ctl, ctlHeadings, ctlActive]) + // undo and redo run only while editing (below), so they are offered only then + useEffect(() => { + if (!ctl) return + const publish = (canUndo: boolean, canRedo: boolean) => ctl.update({ canUndo: isEditing && canUndo, canRedo: isEditing && canRedo }) + publish(editor.canUndo, editor.canRedo) + editor.onHistory = publish + return () => { + editor.onHistory = undefined + } + }, [ctl, editor, isEditing]) + useViewCommands(ctl, { + setZoom, + goto: (id) => gotoBlock(Number(id)), + gotoPage: (n) => { + const sc = scrollRef.current + const top = tops[Math.min(Math.max(1, n), tops.length) - 1] + if (sc && top !== undefined) sc.scrollTop = Math.max(0, top - 16) + }, + undo: () => { + if (isEditing) editor.undo() + }, + redo: () => { + if (isEditing) editor.redo() + }, + }) + return (
setFind((f) => ({ ...f, open: true }))} outline={outline} - onOutline={() => setOutline((o) => !o)} + onOutline={headless ? undefined : () => setOutline((o) => !o)} painter={painter} onLink={askLink} image={imageActions} @@ -909,7 +962,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp onNotice={setToast} /> )} - {!isEditing && done && ( + {!isEditing && done && !headless && ( @@ -922,7 +975,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp {prompt && setPrompt(null)} />} {toast && setToast(null)} />} {cmMarks.length > 0 && } - + {!headless && }
) diff --git a/src/react/pptx/PptxView.tsx b/src/react/pptx/PptxView.tsx index 31c8666..f3ddb07 100644 --- a/src/react/pptx/PptxView.tsx +++ b/src/react/pptx/PptxView.tsx @@ -6,6 +6,7 @@ import { useFileOps, useViewer, useSelectAll } from '../common/Slots' import { slidesToText } from '../file/text' import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' +import { useViewCommands } from '../controller' import { getSel } from '../edit/input' import { PptxEditor } from './PptxEditor' import { PptxToolbar, type AlignTo, type Arrange, type Rotate, type SlideCmd } from './PptxToolbar' @@ -23,21 +24,24 @@ interface SlideCache { models: Map pending: Map> listeners: Map void>> + /** told of every replaced slide, whichever its index */ + edits: Set<(index: number, m: SlideModel) => void> } const caches = new WeakMap() function cacheFor(client: DocumentClient): SlideCache { let c = caches.get(client) - if (!c) caches.set(client, (c = { models: new Map(), pending: new Map(), listeners: new Map() })) + if (!c) caches.set(client, (c = { models: new Map(), pending: new Map(), listeners: new Map(), edits: new Set() })) return c } -/** replaces a cached slide (after an edit) and notifies mounted views */ +/** replaces a cached slide (after an edit, here or a collaborator's) and notifies mounted views */ function putSlide(client: DocumentClient, index: number, m: SlideModel) { const c = cacheFor(client) c.models.set(index, m) for (const fn of c.listeners.get(index) ?? []) fn(m) + for (const fn of c.edits) fn(index, m) } /** forget every cached slide (after slides were added / removed / reordered) */ @@ -209,7 +213,7 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t const thumbRef = useRef(null) const thumbScroll = useScroll(thumbRef) const [zoom, setZoom] = useState(initialZoom) - const showThumbs = thumbnails && rootSize.w >= 720 && meta.count > 1 + const showThumbs = thumbnails && !viewer.headless && rootSize.w >= 720 && meta.count > 1 const [, bump] = useForceUpdate() const caretAt = useRef<{ x: number; y: number } | null>(null) const textRoot = useRef(null) @@ -593,6 +597,62 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t if (el) el.scrollTop = PAD + Math.max(0, Math.min(meta.count - 1, i)) * pitch - Math.max(0, (size.h - slideH) / 2) } + // ---- controller: zoom, slide, the slides as the outline, undo, slideshow ---- + const { ctl, headless } = viewer + // slide titles for the outline, read only while a host reads the controller: from the slides' XML in one call + // once the first slides are shown, then from each slide model an edit puts in the cache + const [observed, setObserved] = useState(() => !!ctl?.observed) + useEffect(() => { + if (!ctl) return + if (ctl.observed) setObserved(true) + return ctl.watchObserved(() => setObserved(true)) + }, [ctl]) + const [titles, setTitles] = useState([]) + useEffect(() => { + if (!observed) return + let live = true + const timer = setTimeout(() => { + client + .call('pptx.titles') + .then((t) => live && setTitles(t)) + .catch(() => {}) + }, 800) + return () => { + live = false + clearTimeout(timer) + } + }, [observed, client, meta.count, slidesVer]) + useEffect(() => { + if (!observed) return + const edits = cacheFor(client).edits + const on = (i: number, m: SlideModel) => setTitles((t) => (t[i] === (m.title ?? '') ? t : Object.assign([...t], { [i]: m.title ?? '' }))) + edits.add(on) + return () => { + edits.delete(on) + } + }, [observed, client]) + useEffect(() => { + ctl?.update({ zoom: { value: zoom, effective: scale } }) + }, [ctl, zoom, scale]) + useEffect(() => { + ctl?.update({ + page: { current: current + 1, count: meta.count }, + outline: { kind: 'slides', items: Array.from({ length: meta.count }, (_, i) => ({ id: String(i), title: titles[i] || `${str.pptx.slide} ${i + 1}`, level: 0, current: i === current })) }, + }) + }, [ctl, current, meta.count, titles, str]) + // as the toolbar's buttons: undo while there is a shape edit or text is being edited; redo whenever editing (no redo depth is kept) + useEffect(() => { + ctl?.update({ canUndo: viewer.editable && (undoDepth > 0 || editor.active), canRedo: viewer.editable }) + }) + useViewCommands(ctl, { + setZoom, + goto: (id) => go(Number(id)), + gotoPage: (n) => go(n - 1), + undo: () => viewer.editable && (editor.active ? editor.undo() : void undoShapes(false)), + redo: () => viewer.editable && (editor.active ? editor.redo() : void undoShapes(true)), + present: () => setPresenting(current), + }) + // ---- comments: a thread points at a point of a slide ---- const cm = useCommentsCtl() const cmState = useCommentsState(cm) @@ -788,8 +848,8 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t {slots}
- - {!viewer.editable && ( + {!headless && } + {!viewer.editable && !headless && ( ))} @@ -138,10 +138,12 @@ action: `pdf`, `html`, `text:md`, `details`, `rename`…), `toggleComments(open? for does nothing. `subscribe(fn)` returns its unsubscribe; `snapshot()` the current state. Without `react`, `mount()` returns the controller (`mounted.controller`), and `` has it as `element.controller`. -Controller actions obey `allowEdit`, `allowSave`, `allowDownload` and `allowOpen` even when the File menu is hidden. +Controller actions obey `allowSave`, `allowDownload` and `allowOpen` even when the File menu is hidden. `fileMenu={false}` hides that menu and its keyboard shortcuts; it does not disable a host's controller controls. +`allowEdit` controls the Edit/View toggle and CSV import; `editable` and `setEditing()` control edit mode, including when the toggle is hidden. +Prevent the default mouse-down action on host outline buttons (as above) to preserve the editor focus and an open XLSX formula while switching sheets. New/Open replace the document and remain available for a read-only file when `allowOpen` permits them. -Import changes a workbook and additionally requires editing permission. Controllers are created with +Import requires `allowEdit` and an editable workbook; it remains available with `allowOpen={false}`. Controllers are created with `createViewerController()`; publishing and attachment methods are internal to the engine. ### Comments diff --git a/e2e/app/main.tsx b/e2e/app/main.tsx index b142c03..fb5cfaf 100644 --- a/e2e/app/main.tsx +++ b/e2e/app/main.tsx @@ -7,7 +7,7 @@ * &components=1: the host's own Button, Separator, Dialog and Toast (`data-host-*` markers) * &headless=1: the document alone; the viewer is driven through window.__ctl (its controller) either way */ -import { useState } from 'react' +import { StrictMode, useState } from 'react' import { createRoot } from 'react-dom/client' import { createViewerController, DocViewer, type DocViewerProps, type FileMenuItem, type UIComponents, type ViewerController } from '../../src' import { de } from '../../src/locales/de' @@ -20,7 +20,7 @@ declare global { __setLanguage: (language: 'en' | 'de-DE') => void __german: typeof de __ctl: ViewerController - __overlap: (phase: number) => void + __overlap: (phase: number, props?: Partial) => void } } window.__events = [] @@ -137,13 +137,19 @@ const initial: DocViewerProps = { function App() { const [props, setProps] = useState(initial) const [phase, setPhase] = useState(0) - window.__overlap = setPhase + const [nextProps, setNextProps] = useState>({}) + window.__overlap = (phase, next) => { + if (next) setNextProps(next) + setPhase(phase) + } window.__setProps = (p) => setProps((cur) => ({ ...cur, ...p })) window.__setLanguage = (language) => setProps((cur) => ({ ...cur, strings: language === 'de-DE' ? de : undefined })) + const { undo, redo } = window.__ctl return <> + {q.has('hostControls') &&
} {phase < 2 && } - {phase > 0 && } + {phase > 0 && phase < 3 && } } -createRoot(document.getElementById('root')!).render() +createRoot(document.getElementById('root')!).render(q.has('strict') ? : ) diff --git a/e2e/collab.spec.ts b/e2e/collab.spec.ts index d3571f0..a3c83b3 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 } 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') diff --git a/e2e/controller.spec.ts b/e2e/controller.spec.ts index f45ab13..bf4073b 100644 --- a/e2e/controller.spec.ts +++ b/e2e/controller.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test' import type { ViewerController, ViewerState } from '../src' -import { fromB64, useBrowser, viewer, xlsxSheet, type Viewer } from './harness' +import { docxBlocks, fromB64, useBrowser, viewer, xlsxSheet, type Viewer } from './harness' useBrowser() @@ -99,6 +99,128 @@ describe('controller and headless mode', () => { 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 @@ -213,7 +335,7 @@ describe('controller and headless mode', () => { window.__ctl.subscribe(() => window.__xlsxHistory.publications.push(window.__ctl.snapshot())) window.__xlsxHistory.release!() }) - // Dirty is published by run after the held response resumes, so the assertion cannot pass before completion. + // 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) @@ -224,16 +346,16 @@ describe('controller and headless mode', () => { }) } - test('xlsx: an unmounted view cannot publish its delayed history over the current view', async () => { + 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(() => window.__setProps({ src: 'samples/sample.docx', onLoad: undefined })) - await v.page.locator('.de-pages').waitFor() - await until(v, "s.kind === 'docx' && !s.loading && !s.canUndo && !s.canRedo") + 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!() @@ -241,7 +363,26 @@ describe('controller and headless mode', () => { 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: 'docx', canUndo: false, canRedo: 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([]) }) @@ -258,7 +399,7 @@ describe('controller and headless mode', () => { expect(pickers).toEqual([]) expect(downloads).toEqual([]) expect(await v.events('save')).toEqual([]) - expect((await state(v)).editing).toBe(false) + 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'))) 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/xlsx.ts b/src/collab/xlsx.ts index 69a6ce4..c34098e 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, 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() { @@ -114,6 +120,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) } @@ -121,6 +128,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 }) } @@ -147,6 +155,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 af18afe..03c87f1 100644 --- a/src/core/pptx/parser.ts +++ b/src/core/pptx/parser.ts @@ -167,7 +167,7 @@ const plainTitle = (paras: string[]) => paras.join(' ').replace(/[\uF000-\uF0FF] /** 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(textOf)) : '' + 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 '' @@ -901,7 +901,7 @@ class SlideRenderer { 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.text).join(''))) + 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 diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx index dba6307..067875d 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' @@ -170,7 +170,8 @@ function Viewer(props: DocViewerProps) { 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 ctl = internalController(props.controller ?? ownCtl) + 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) @@ -204,6 +205,7 @@ function Viewer(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 @@ -403,10 +405,10 @@ function Viewer(props: DocViewerProps) { ) const selectAll = useRef<(() => void) | null>(null) // next to its source, the document is a preview: it is edited through the source - const docEditable = editing && allowEdit && canEdit && !codeShown + const docEditable = editing && canEdit && !codeShown const api = useMemo( - () => ({ bar: barEl, editable: docEditable, setDirty: setDocDirty, save, canDownload: allowDownload, client, fileOps, selectAll, ctl, headless }), - [barEl, docEditable, setDocDirty, save, allowDownload, client, ctl, headless], + () => ({ 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) => { @@ -504,7 +506,7 @@ function Viewer(props: DocViewerProps) { ext: officeExt, base: baseName, canOpen, - canImport: allowOpen && allowEdit && canEdit, + canImport: allowEdit && canEdit, canSave, canDownload: allowDownload && !!client, ops: fileOps, @@ -562,13 +564,13 @@ function Viewer(props: DocViewerProps) { 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 = allowEdit && !readOnly && !codeShown + 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 } - useEffect(() => { + useLayoutEffect(() => { return ctl.attachViewer({ setEditing: (on) => { if (!on || commands.current.editAllowed) setEditing(on) @@ -578,6 +580,7 @@ function Viewer(props: DocViewerProps) { toggleComments: (open) => commands.current.cmCtl?.toggle(open), }) }, [ctl]) + useLayoutEffect(() => viewCtl.activate(), [viewCtl]) let body: ReactNode if (error) { diff --git a/src/react/common/Slots.tsx b/src/react/common/Slots.tsx index f91f196..af72ee2 100644 --- a/src/react/common/Slots.tsx +++ b/src/react/common/Slots.tsx @@ -3,7 +3,7 @@ import { createPortal } from 'react-dom' import { ToolbarRow } from '../edit/Toolbar' import type { DocumentClient } from '../../core/worker/client' import type { Printable } from '../file/print' -import type { InternalViewerController } from '../controller' +import type { ViewController } from '../controller' /** What the active view offers to the File menu. */ export interface FileOps { @@ -35,7 +35,7 @@ export interface ViewerApi { /** set by the mounted view (see useSelectAll): Ctrl/⌘+A */ selectAll: { current: (() => void) | null } /** the viewer's controller: the view publishes its state and registers its commands there */ - ctl: InternalViewerController | null + ctl: ViewController | null /** the host draws the controls: the view shows no zoom, outline, sheet tabs or slide list of its own */ headless: boolean } diff --git a/src/react/controller.ts b/src/react/controller.ts index f876d8f..17a1167 100644 --- a/src/react/controller.ts +++ b/src/react/controller.ts @@ -67,6 +67,18 @@ export interface ViewerCommands { toggleComments(open?: boolean): void } +type ViewState = Pick +type ViewerPublication = Omit + +/** Internal, document-scoped publication and command registration. Never part of the host API. */ +export interface ViewController { + activate(): () => void + update(state: Partial): void + attachView(commands: ViewCommands): () => void + readonly observed: boolean + watchObserved(fn: () => void): () => void +} + /** the view's part of the state, cleared when a view goes */ const VIEW_STATE = { canUndo: false, canRedo: false, zoom: null, page: null, outline: null, status: '' } as const @@ -82,12 +94,17 @@ function same(a: unknown, b: unknown): boolean { return JSON.stringify(a) === JSON.stringify(b) } +const controllerBrand: unique symbol = Symbol('ViewerController') + export class InternalViewerController { + readonly [controllerBrand] = true as const private state: ViewerState = EMPTY private subs = new Set<() => void>() private watchers = new Set<() => void>() private view: ViewCommands | null = null private viewer: ViewerCommands | null = null + private owner: object | null = null + private viewOwner: object | null = null subscribe = (fn: () => void) => { const first = this.subs.size === 0 @@ -116,61 +133,62 @@ export class InternalViewerController { // ---------------------------------------------------------------- commands - setEditing(on: boolean) { + setEditing = (on: boolean) => { this.viewer?.setEditing(on) } /** builds the edited file and hands it to `onSave` (or downloads it) */ - save(): Promise { + save = (): Promise => { return this.viewer?.save() ?? Promise.resolve() } - undo() { + undo = () => { this.view?.undo?.() } - redo() { + redo = () => { this.view?.redo?.() } - setZoom(z: Zoom) { - this.view?.setZoom?.(z) + setZoom = (z: Zoom) => { + if (z === 'fit') this.view?.setZoom?.(z) + else if (Number.isFinite(z)) this.view?.setZoom?.(Math.min(3, Math.max(0.25, z))) } - zoomIn() { + zoomIn = () => { this.zoomStep(1) } - zoomOut() { + zoomOut = () => { this.zoomStep(-1) } /** shows an outline entry: scrolls to a heading, shows a sheet or a slide */ - goto(id: string) { + goto = (id: string) => { this.view?.goto?.(id) } /** scrolls to a page or slide, from 1 */ - gotoPage(n: number) { + gotoPage = (n: number) => { this.view?.gotoPage?.(n) } /** a presentation as a slideshow, from the slide in view */ - present() { + present = () => { this.view?.present?.() } - print() { + print = () => { this.fileAction('print') } /** a File menu action by its id: 'pdf', 'html', 'text:md', 'details', 'rename'… (see FileMenu) */ - fileAction(id: string) { + fileAction = (id: string) => { this.viewer?.fileAction(id) } /** the comments panel open (true), closed (false) or the other way round */ - toggleComments(open?: boolean) { + toggleComments = (open?: boolean) => { this.viewer?.toggleComments(open) } @@ -183,7 +201,7 @@ export class InternalViewerController { // ---------------------------------------------------------------- published by the viewer and its view /** @internal the state changed: only what differs counts as a change */ - update(p: Partial>) { + private update(p: Partial>) { let changed = false for (const k of Object.keys(p) as (keyof typeof p)[]) { if (!same(this.state[k], p[k])) { @@ -196,38 +214,78 @@ export class InternalViewerController { for (const fn of this.subs) fn() } - /** @internal releases only this registration, so an exiting viewer cannot detach its successor. */ - attachView(c: ViewCommands): () => void { - this.view = c - return () => { - if (this.view !== c) return - this.view = null - this.update(VIEW_STATE) - } - } - - /** @internal releases only this registration. */ - attachViewer(c: ViewerCommands): () => void { - this.viewer = c - return () => { - if (this.viewer !== c) return - this.viewer = null - this.update(VIEWER_STATE) + /** A viewer claims ownership when it mounts, before any async document can finish loading. + * A later document attach/update can only use that claim; it cannot take ownership back. + * Each document also gets a separate publication scope, invalidated on replacement. + */ + createBinding() { + const controller = this + const owner = {} + const owns = () => this.owner === owner + return { + attachViewer: (commands: ViewerCommands) => { + this.owner = owner + this.viewer = commands + this.viewOwner = null + this.view = null + this.update({ ...VIEWER_STATE, ...VIEW_STATE }) + return () => { + if (!owns() || this.viewer !== commands) return + this.owner = this.viewOwner = null + this.viewer = this.view = null + this.update({ ...VIEWER_STATE, ...VIEW_STATE }) + } + }, + update: (state: Partial) => { + if (owns()) this.update(state) + }, + createView: (): ViewController => { + const viewOwner = {} + const current = () => owns() && this.viewOwner === viewOwner + return { + activate: () => { + if (!owns()) return () => {} + this.viewOwner = viewOwner + this.view = null + this.update(VIEW_STATE) + return () => { + if (!current()) return + this.viewOwner = null + this.view = null + this.update(VIEW_STATE) + } + }, + update: (state) => { if (current()) this.update(state) }, + attachView: (commands) => { + if (!current()) return () => {} + this.view = commands + return () => { + if (!current() || this.view !== commands) return + this.view = null + } + }, + get observed() { return controller.observed }, + watchObserved: (fn) => this.watchObserved(fn), + } + }, } } } /** Host API; publishing and lifecycle methods belong to the engine. */ -export type ViewerController = Pick export const createViewerController = (): ViewerController => new InternalViewerController() /** @internal controllers supplied to viewers originate from createViewerController(). */ -export const internalController = (ctl: ViewerController): InternalViewerController => ctl as InternalViewerController +export const internalController = (ctl: ViewerController): InternalViewerController => { + if (!(ctl instanceof InternalViewerController)) throw new TypeError('DocViewer controller must be created by createViewerController()') + return ctl +} /** @internal follows both subscription transitions, including a replacement controller. */ -export function useControllerObserved(ctl: InternalViewerController | null): boolean { +export function useControllerObserved(ctl: ViewController | null): boolean { return useSyncExternalStore( (fn) => ctl?.watchObserved(fn) ?? (() => {}), () => !!ctl?.observed, @@ -241,7 +299,7 @@ export function useViewerState(ctl: ViewerController): ViewerState { } /** Registers a view's commands (the latest closures each render) while it is mounted. */ -export function useViewCommands(ctl: InternalViewerController | null, commands: ViewCommands) { +export function useViewCommands(ctl: ViewController | null, commands: ViewCommands) { const latest = useLatest(commands) useEffect(() => { if (!ctl) return diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index 2559af9..d87c3d1 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -8,7 +8,7 @@ import { claimFocus, lowerIndex, useForceUpdate, useIsoLayoutEffect, useScroll, import { useFileOps, useSelectAll, useViewer } from '../common/Slots' import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' -import { useViewCommands } from '../controller' +import { useViewCommands, useControllerObserved } from '../controller' import { ContextMenu, MOD, type MenuItem } from '../common/ContextMenu' import { PromptDialog, Toast, type PromptSpec } from '../common/Dialog' import { domFromPos, getSel, opInsert, posFromDom, selPoints } from '../edit/input' @@ -778,12 +778,13 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp // ---- controller: zoom, page, headings, undo ---- const { ctl, headless } = viewer // the headings for the controller: read again once the document stops changing, not on every keystroke + const observed = useControllerObserved(ctl) const [ctlHeadings, setCtlHeadings] = useState<{ bi: number; lvl: number; text: string }[]>([]) useEffect(() => { - if (!ctl) return + if (!observed) return const id = setTimeout(() => setCtlHeadings(outlineOf(st.blocks, titleId)), 150) return () => clearTimeout(id) - }, [ctl, version, titleId, st]) + }, [observed, version, titleId, st]) const ctlActive = ctlHeadings.reduce((acc, h, i) => (h.bi <= atBlock ? i : acc), -1) useEffect(() => { ctl?.update({ zoom: { value: zoom, effective: z } }) diff --git a/src/react/file/FileMenu.tsx b/src/react/file/FileMenu.tsx index 9c649f8..4f9fb24 100644 --- a/src/react/file/FileMenu.tsx +++ b/src/react/file/FileMenu.tsx @@ -134,9 +134,9 @@ export function useFileActions(o: FileActionsOptions): FileActions { return } case 'rename': - return c.rename?.() + return c.kind ? c.rename?.() : undefined case 'details': - return c.details?.() + return c.kind ? c.details?.() : undefined case 'close': return c.close?.() case 'save': diff --git a/src/react/xlsx/XlsxView.tsx b/src/react/xlsx/XlsxView.tsx index 218b8ae..3216390 100644 --- a/src/react/xlsx/XlsxView.tsx +++ b/src/react/xlsx/XlsxView.tsx @@ -7,7 +7,7 @@ import { closeFormula, formulaContext, isFormula, rangeText, type FormulaContext import { argSlot, functionInfo, suggestFunctions, type FnInfo } from '../../core/xlsx/formula/catalog' import { MAX_COL, MAX_ROW } from '../../core/xlsx/formula/types' import type { DocumentClient } from '../../core/worker/client' -import { getPeers, publishLocal, subscribePeers } from '../../collab/hosts' +import { getPeers, publishLocal, subscribePeers, getLocalHistory, subscribeLocalHistory } from '../../collab/hosts' import { claimFocus, useForceUpdate, useScroll, useSize } from '../common/hooks' import { useFileOps, useViewer, useSelectAll } from '../common/Slots' import { useViewCommands } from '../controller' @@ -88,12 +88,21 @@ class XlsxStore { /** focus the grid when the next sheet grid mounts */ focusGrid = false /** edits that undo / redo can still take back (counted here: the worker's history says nothing until asked) */ - history = { undo: 0, redo: 0 } + private standaloneHistory = { undo: 0, redo: 0 } + get history() { return getLocalHistory(this.client) ?? this.standaloneHistory } + set history(history: { undo: number; redo: number }) { + if (!getLocalHistory(this.client)) this.standaloneHistory = history + } private listeners = new Set<() => void>() + private editListeners = new Set<() => void>() private off: () => void constructor(private client: DocumentClient) { const offs = [ + subscribeLocalHistory(client, () => { + this.standaloneHistory = { undo: 0, redo: 0 } + this.emit() + }), client.on('xlsx:progress', (p) => this.onProgress(p)), // edits of collaborators (src/collab) client.on('collab:xlsx', (res) => this.applied(res, client.info.xlsx as WorkbookMeta)), @@ -108,6 +117,16 @@ class XlsxStore { } } + onEdit(fn: () => void) { + this.editListeners.add(fn) + return () => { this.editListeners.delete(fn) } + } + + edited() { + for (const fn of this.editListeners) fn() + this.emit() + } + emit() { for (const fn of this.listeners) fn() } @@ -270,6 +289,9 @@ export function XlsxView({ client, onStatus, initialSheet }: XlsxViewProps) { : `${str.xlsx.status(state.rows, state.cols, str.locale)}${state.done ? '' : str.xlsx.statusLoading}${state.rows > MAX_ROWS ? str.xlsx.overLimit(MAX_ROWS, str.locale) : ''}` const viewer = useViewer() + // The workbook owns completion publication even when the grid that began the edit changed sheets. + // Layout cleanup removes this listener before a replacement document can receive late dirty state. + useLayoutEffect(() => store.onEdit(() => viewer.setDirty(true)), [store, viewer.setDirty]) useFileOps({ printable: () => sheetPrintable(client, cur, store.sheet(cur), meta, str), text: (format) => client.call('xlsx.text', cur, format === 'tsv' ? '\t' : ','), @@ -406,7 +428,8 @@ export function XlsxView({ client, onStatus, initialSheet }: XlsxViewProps) { const gridCommands = useRef<{ undo: () => void; redo: () => void } | null>(null) const sheetItems = meta.sheets.filter((s) => !s.hidden).map((s) => ({ id: String(s.index), title: s.name, level: 0, current: s.index === cur })) useEffect(() => { - ctl?.update({ outline: { kind: 'sheets', items: sheetItems } }) + const h = store.history + ctl?.update({ outline: { kind: 'sheets', items: sheetItems }, canUndo: viewer.editable && h.undo > 0, canRedo: viewer.editable && h.redo > 0 }) }) useViewCommands(ctl, { goto: (id) => { @@ -590,12 +613,6 @@ export function withMerges(r: Range, merges: Merge[]): Range { function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, gridCommands }: GridProps) { const viewer = useViewer() - // Async edits may outlive this grid, its document, or the controller / edit mode that started them. - const currentViewer = useRef(null) - useLayoutEffect(() => { - currentViewer.current = viewer - return () => { currentViewer.current = null } - }, [viewer]) const str = useStrings() const editable = viewer.editable const s = store.sheet(sheet) @@ -1005,7 +1022,6 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g store.applied(res, meta) const h = store.history if (res) { - viewer.setDirty(true) if (kind === 'edit') store.history = { undo: h.undo + 1, redo: 0 } else if (kind === 'undo') store.history = { undo: Math.max(0, h.undo - 1), redo: h.redo + 1 } else store.history = { undo: h.undo + 1, redo: Math.max(0, h.redo - 1) } @@ -1013,10 +1029,9 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g // nothing to undo or redo: the worker's history is shorter than counted (it keeps the last 200 edits) else if (kind === 'undo') store.history = { ...h, undo: 0 } else if (kind === 'redo') store.history = { ...h, redo: 0 } - const current = currentViewer.current - if (current?.client === client) { - current.ctl?.update({ canUndo: current.editable && store.history.undo > 0, canRedo: current.editable && store.history.redo > 0 }) - } + // The current workbook view publishes dirty/history; a detached store has no listeners. + if (res) store.edited() + else store.emit() setDetailTick((t) => t + 1) } catch (e) { console.error('[office-engine]', e) @@ -1220,8 +1235,6 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g // the controller's undo / redo: this sheet's grid runs them while it is shown useEffect(() => { gridCommands.current = { undo: () => editable && undo(), redo: () => editable && redo() } - const h = store.history - viewer.ctl?.update({ canUndo: editable && h.undo > 0, canRedo: editable && h.redo > 0 }) }) /** the selection as clipboard text, when all its rows are at hand (else null: the worker has them) */ diff --git a/test/collab-xlsx.test.ts b/test/collab-xlsx.test.ts index 7197d18..624f5ca 100644 --- a/test/collab-xlsx.test.ts +++ b/test/collab-xlsx.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from 'bun:test' +import { getLocalHistory, subscribeLocalHistory } from '../src/collab/hosts' import { DocumentClient } from '../src/core/worker/client' import { CollabHub } from '../src/collab/hub' import { startCollab, type Collab } from '../src/collab' @@ -44,6 +45,34 @@ async function dump(client: DocumentClient) { } describe('collab xlsx', () => { + test('local history reports the session stack across rename, new edits and undo/redo', async () => { + const hub = new CollabHub() + const a = await open(hub, 'Ann', () => 0) + await settle([a.collab]) + let notifications = 0 + const off = subscribeLocalHistory(a.client, () => notifications++) + await a.client.call('xlsx.set', 0, [{ r: 11, c: 9, input: 'before rename' }]) + await settle([a.collab]) + expect(getLocalHistory(a.client)).toEqual({ undo: 1, redo: 0 }) + await a.client.call('xlsx.bookOp', { op: 'rename', index: 0, name: 'Renamed' }) + await settle([a.collab]) + // Sheet-list operations invalidate the worker's shared undo records as well as its local history. + expect(getLocalHistory(a.client)).toEqual({ undo: 0, redo: 0 }) + expect(await a.client.call('xlsx.undo')).toBeNull() + await a.client.call('xlsx.set', 0, [{ r: 11, c: 9, input: 'after rename' }]) + await settle([a.collab]) + expect(getLocalHistory(a.client)).toEqual({ undo: 1, redo: 0 }) + await a.client.call('xlsx.undo') + expect(getLocalHistory(a.client)).toEqual({ undo: 0, redo: 1 }) + expect((await a.client.call('xlsx.cell', 0, 11, 9))?.value).toBe('before rename') + await a.client.call('xlsx.redo') + expect(getLocalHistory(a.client)).toEqual({ undo: 1, redo: 0 }) + expect((await a.client.call('xlsx.cell', 0, 11, 9))?.value).toBe('after rename') + expect(notifications).toBeGreaterThan(4) + off(); a.collab.close(); a.client.destroy() + expect(getLocalHistory(a.client)).toBeUndefined() + }) + for (const start of [7, 11, 23, 42, 99]) test(`concurrent cell edits, formatting, structure and undo converge (seed ${start})`, async () => { let seed = start const rand = () => ((seed = (seed * 1664525 + 1013904223) % 4294967296) / 4294967296) diff --git a/test/controller.test.ts b/test/controller.test.ts index eca6406..abc2ad0 100644 --- a/test/controller.test.ts +++ b/test/controller.test.ts @@ -1,110 +1,135 @@ import { describe, expect, test } from 'bun:test' -import { InternalViewerController } from '../src/react/controller' +import { createViewerController, internalController, InternalViewerController, type ViewerCommands, type ViewerController } from '../src/react/controller' -describe('viewer controller', () => { - test('observed once a host subscribes; watchers hear the first subscriber only', () => { - const ctl = new InternalViewerController() - let heard = 0 - const stop = ctl.watchObserved(() => heard++) - expect(ctl.observed).toBe(false) - const off = ctl.subscribe(() => {}) - ctl.subscribe(() => {}) - expect(ctl.observed).toBe(true) - expect(heard).toBe(1) - off() - stop() - }) +const emptyCommands: ViewerCommands = { setEditing() {}, async save() {}, fileAction() {}, toggleComments() {} } +function mount(ctl: InternalViewerController, commands = emptyCommands) { + const viewer = ctl.createBinding() + const release = viewer.attachViewer(commands) + const view = viewer.createView() + const detach = view.activate() + return { viewer, view, release, detach } +} - test('state changes count once each; an equal update is no change', () => { +describe('viewer controller', () => { + test('state changes count once each; equal updates preserve the snapshot', () => { const ctl = new InternalViewerController() + const { viewer, view } = mount(ctl) let calls = 0 ctl.subscribe(() => calls++) - ctl.update({ kind: 'docx', zoom: { value: 'fit', effective: 0.8 } }) - expect(ctl.snapshot()).toMatchObject({ rev: 1, kind: 'docx', zoom: { value: 'fit', effective: 0.8 } }) - ctl.update({ kind: 'docx', zoom: { value: 'fit', effective: 0.8 } }) - ctl.update({ outline: { kind: 'headings', items: [{ id: '3', title: 'Intro', level: 0, current: true }] } }) - ctl.update({ outline: { kind: 'headings', items: [{ id: '3', title: 'Intro', level: 0, current: true }] } }) + viewer.update({ kind: 'docx' }) + view.update({ zoom: { value: 'fit', effective: 0.8 } }) + const before = ctl.snapshot() + viewer.update({ kind: 'docx' }) + view.update({ zoom: { value: 'fit', effective: 0.8 } }) + expect(ctl.snapshot()).toBe(before) expect(calls).toBe(2) - expect(ctl.snapshot().rev).toBe(2) + expect(before.rev).toBe(2) }) - test('commands go to the view and the viewer that registered them; without them they do nothing', async () => { - const ctl = new InternalViewerController() - ctl.goto('1') - ctl.setEditing(true) - await ctl.save() - const log: string[] = [] - ctl.attachView({ setZoom: (z) => log.push(`zoom ${z}`), goto: (id) => log.push(`goto ${id}`), gotoPage: (n) => log.push(`page ${n}`), undo: () => log.push('undo') }) - ctl.attachViewer({ setEditing: (on) => log.push(`edit ${on}`), save: async () => void log.push('save'), fileAction: (id) => log.push(`file ${id}`), toggleComments: () => log.push('comments') }) - ctl.goto('7') - ctl.gotoPage(2) - ctl.undo() - ctl.redo() - ctl.setEditing(true) - await ctl.save() - ctl.print() - expect(log).toEqual(['goto 7', 'page 2', 'undo', 'edit true', 'save', 'file print']) + test('all host commands remain bound when destructured; absent commands are harmless', async () => { + const ctl = createViewerController() + const { setEditing, save, undo, redo, setZoom, zoomIn, zoomOut, goto, gotoPage, present, print, fileAction, toggleComments } = ctl + undo(); redo(); setEditing(true); await save(); setZoom(1); zoomIn(); zoomOut(); goto('1'); gotoPage(1); present(); print(); fileAction('pdf'); toggleComments() + const log: unknown[] = [] + const { view } = mount(internalController(ctl), { + setEditing: (v) => log.push(v), save: async () => void log.push('save'), fileAction: (id) => log.push(id), toggleComments: (v) => log.push(v), + }) + view.attachView({ undo: () => log.push('undo'), redo: () => log.push('redo'), setZoom: (v) => log.push(v), goto: (v) => log.push(v), gotoPage: (v) => log.push(v), present: () => log.push('present') }) + view.update({ zoom: { value: 'fit', effective: 0.8 } }) + undo(); redo(); setEditing(true); await save(); setZoom(1.25); zoomIn(); zoomOut(); goto('sheet'); gotoPage(2); present(); print(); fileAction('pdf'); toggleComments(false) + expect(log).toEqual(['undo', 'redo', true, 'save', 1.25, 0.9, 0.75, 'sheet', 2, 'present', 'print', 'pdf', false]) }) - test('zoom steps from the effective zoom: in from a fitted 0.8 is 0.9, out from 0.25 is nothing', () => { + test('zoom accepts fit and finite factors clamped to the built-in range', () => { const ctl = new InternalViewerController() - const set: unknown[] = [] - ctl.attachView({ setZoom: (z) => set.push(z) }) - ctl.update({ zoom: { value: 'fit', effective: 0.8 } }) - ctl.zoomIn() - ctl.update({ zoom: { value: 0.25, effective: 0.25 } }) - ctl.zoomOut() - expect(set).toEqual([0.9]) - // a view without zoom (a spreadsheet) - ctl.update({ zoom: null }) - ctl.zoomIn() - expect(set).toEqual([0.9]) + const { view } = mount(ctl) + const values: unknown[] = [] + view.attachView({ setZoom: (z) => values.push(z) }) + for (const z of ['fit', 0, 150, NaN, Infinity, -Infinity, -1, 0.8] as const) ctl.setZoom(z) + expect(values).toEqual(['fit', 0.25, 3, 0.25, 0.8]) + view.update({ zoom: { value: 0.25, effective: 0.25 } }); ctl.zoomOut() + view.update({ zoom: null }); ctl.zoomIn() + expect(values).toHaveLength(5) }) - test('the view going clears its part of the state', () => { + for (const kind of ['docx', 'xlsx', 'pptx'] as const) { + test(`a slow older view cannot steal a newer ${kind} viewer's state or commands`, () => { + const ctl = new InternalViewerController() + const old = mount(ctl) + old.viewer.update({ loading: true }) + old.view.update({ zoom: { value: 1, effective: 1 }, page: { current: 3, count: 7 } }) + const log: string[] = [] + const current = mount(ctl, { ...emptyCommands, setEditing: () => log.push('edit') }) + current.viewer.update({ kind, loading: false }) + current.view.attachView({ goto: () => log.push('goto'), undo: () => log.push('undo'), setZoom: () => log.push('zoom') }) + current.view.update({ outline: { kind: 'sheets', items: [] }, status: 'new' }) + const snapshot = ctl.snapshot() + const lateView = old.viewer.createView() + const off = lateView.activate() + lateView.attachView({ goto: () => log.push('stale') }) + lateView.update({ page: { current: 3, count: 7 }, status: 'late' }) + old.viewer.update({ kind: 'docx', loading: false, dirty: true }) + off(); old.detach(); old.release() + ctl.goto('1'); ctl.undo(); ctl.setZoom(1); ctl.setEditing(true) + expect(log).toEqual(['goto', 'undo', 'zoom', 'edit']) + expect(ctl.snapshot()).toBe(snapshot) + expect(snapshot).toMatchObject({ kind, page: null, zoom: null, dirty: false, status: 'new' }) + }) + } + + test('document replacement clears view fields and rejects late publications and cleanup', () => { const ctl = new InternalViewerController() - const detach = ctl.attachView({}) - ctl.update({ kind: 'pptx', page: { current: 2, count: 9 }, canUndo: true, status: 'Slide 2 of 9' }) - detach() - expect(ctl.snapshot()).toMatchObject({ kind: 'pptx', page: null, canUndo: false, status: '', outline: null, zoom: null }) + const { viewer, view, detach } = mount(ctl) + viewer.update({ kind: 'docx' }) + view.update({ zoom: { value: 1, effective: 1 }, page: { current: 3, count: 7 }, canUndo: true }) + const next = viewer.createView() + next.activate() + viewer.update({ kind: 'xlsx' }) + next.update({ status: 'sheet' }) + view.update({ canUndo: true, status: 'stale' }); detach() + expect(ctl.snapshot()).toMatchObject({ kind: 'xlsx', zoom: null, page: null, canUndo: false, status: 'sheet' }) }) - test('the viewer going clears its part of the state', () => { + test('StrictMode setup-cleanup-setup restores the same scope and cleanup clears all state', () => { const ctl = new InternalViewerController() - const detach = ctl.attachViewer({ setEditing: () => {}, save: async () => {}, fileAction: () => {}, toggleComments: () => {} }) - ctl.update({ kind: 'docx', loading: true, editing: true, canEdit: true, dirty: true, saving: true }) - detach() - expect(ctl.snapshot()).toMatchObject({ kind: null, loading: false, editing: false, canEdit: false, dirty: false, saving: false }) + const viewer = ctl.createBinding(), view = viewer.createView() + for (let i = 0; i < 2; i++) { + const release = viewer.attachViewer(emptyCommands), detach = view.activate() + const off = view.attachView({}) + viewer.update({ kind: 'pptx', editing: true, dirty: true }) + view.update({ canUndo: true, page: { current: 2, count: 9 }, status: 'Slide 2' }) + expect(ctl.snapshot().kind).toBe('pptx') + release(); detach(); off() + view.update({ status: 'late' }); viewer.update({ dirty: true }) + expect(ctl.snapshot()).toMatchObject({ kind: null, loading: false, editing: false, dirty: false, saving: false, canUndo: false, canRedo: false, zoom: null, page: null, outline: null, status: '' }) + } }) - test('an exiting viewer cannot detach the newer viewer or view', () => { - const ctl = new InternalViewerController() - const log: string[] = [] - const commands = (id: string) => ({ setEditing: () => log.push(id), save: async () => {}, fileAction: () => {}, toggleComments: () => {} }) - const oldViewer = ctl.attachViewer(commands('old')) - const oldView = ctl.attachView({ undo: () => log.push('old undo') }) - const newViewer = ctl.attachViewer(commands('new')) - const newView = ctl.attachView({ undo: () => log.push('new undo') }) - ctl.update({ kind: 'xlsx', canUndo: true, status: 'new' }) - oldView(); oldViewer() - ctl.setEditing(true); ctl.undo() - expect(log).toEqual(['new', 'new undo']) - expect(ctl.snapshot()).toMatchObject({ kind: 'xlsx', canUndo: true, status: 'new' }) - newView(); newViewer() - expect(ctl.snapshot()).toMatchObject({ kind: null, canUndo: false, status: '' }) + + test('an unmounted older command registration cannot clear newer commands', () => { + const ctl = new InternalViewerController(), { view } = mount(ctl) + let calls = 0 + const old = view.attachView({ undo() { throw Error('stale') } }) + view.attachView({ undo() { calls++ } }) + old(); ctl.undo() + expect(calls).toBe(1) }) - test('observation follows the last unsubscribe, resubscribe and duplicate callbacks', () => { - const ctl = new InternalViewerController() + test('observation follows first/last subscriptions, duplicate callbacks and resubscription', () => { + const ctl = new InternalViewerController(), { view } = mount(ctl) const observed: boolean[] = [] - const stop = ctl.watchObserved(() => observed.push(ctl.observed)) + const stop = view.watchObserved(() => observed.push(view.observed)) const fn = () => {} const a = ctl.subscribe(fn), b = ctl.subscribe(fn) - a(); a() - expect(ctl.observed).toBe(true) - b() - const c = ctl.subscribe(fn) - c(); stop() + a(); a(); expect(view.observed).toBe(true) + b(); const c = ctl.subscribe(fn); c(); stop() expect(observed).toEqual([true, false, true, false]) }) + test('structural mocks and wrappers fail clearly before mounting', () => { + const real = createViewerController() + const fake: Pick> = { ...real } + // @ts-expect-error host API is intentionally branded + expect(() => internalController(fake)).toThrow('must be created by createViewerController()') + expect(internalController(real)).toBeInstanceOf(InternalViewerController) + }) }) diff --git a/test/core.test.ts b/test/core.test.ts index 79453dc..334cbef 100644 --- a/test/core.test.ts +++ b/test/core.test.ts @@ -4,6 +4,11 @@ import { Engine } from '../src/core/worker/engine' import type { Block, DocxMeta, Paragraph } from '../src/core/docx/types' import type { SheetProgress } from '../src/core/xlsx/types' import { formatValue } from '../src/core/xlsx/numfmt' +import { OpcPackage } from '../src/core/opc' +import { ZipArchive } from '../src/core/zip' +import { openSource } from '../src/core/source' +import type { SlideModel } from '../src/core/pptx/types' +import { rebuildZip } from '../src/core/zipwrite' import { SaxParser, TreeBuilder } from '../src/core/xml' const S = (n: string) => `${import.meta.dir}/../playground/public/samples/${n}` @@ -217,6 +222,16 @@ describe('xlsx', () => { }) describe('pptx', () => { + test('slide title line breaks separate words in both the outline and rendered model', async () => { + const pkg = new OpcPackage(await ZipArchive.open(await openSource(file('sample.pptx')))) + const xml = (await pkg.text('ppt/slides/slide1.xml')).replace('office-engine', 'Annual ReportQ3 Results') + const blob = await rebuildZip(pkg.zip, new Map([['ppt/slides/slide1.xml', xml]])) + const { engine } = collect() + await engine.open(blob, {}) + expect((await engine.call('pptx.titles', []) as string[])[0]).toBe('Annual Report Q3 Results') + expect((await engine.call('pptx.slide', [0]) as SlideModel).title).toBe('Annual Report Q3 Results') + }) + test('sample.pptx slides', async () => { const { engine } = collect() const info = await engine.open(file('sample.pptx'), {}) From e82eedaecfea4fe003fe3a1cb6f71c3dd45522f1 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:14:03 +0100 Subject: [PATCH 16/20] test(controller): verify production locale UI and ownership integration --- e2e/controller-built.spec.ts | 65 ++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 e2e/controller-built.spec.ts diff --git a/e2e/controller-built.spec.ts b/e2e/controller-built.spec.ts new file mode 100644 index 0000000..c38c3c1 --- /dev/null +++ b/e2e/controller-built.spec.ts @@ -0,0 +1,65 @@ +/** Controller + locale + host UI integration against emitted production modules. */ +import { expect, test } from 'bun:test' +import { fromB64, useBrowser, viewer, xlsxSheet } from './harness' + +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: `/@fs${process.cwd()}/dist/index.js`, german: `/@fs${process.cwd()}/dist/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([]) +}) From 20befa29db23c323388a69ed17c7178b58df27d3 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:46:08 +0100 Subject: [PATCH 17/20] test(controller): enforce the shared production build guard --- e2e/controller-built.spec.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/e2e/controller-built.spec.ts b/e2e/controller-built.spec.ts index c38c3c1..00b6ef3 100644 --- a/e2e/controller-built.spec.ts +++ b/e2e/controller-built.spec.ts @@ -2,6 +2,9 @@ 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 () => { @@ -35,7 +38,7 @@ test('built controller uses current callbacks across locale/UI updates, replacem ;(window as any).__builtUpdate = (p: any) => { current = { ...current, ...p }; generation = 'updated'; render() } ;(window as any).__builtUnmount = () => root.unmount() render() - }, { pkg: `/@fs${process.cwd()}/dist/index.js`, german: `/@fs${process.cwd()}/dist/locales/de.js` }) + }, { 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')) From e21a9fb00461fc8cc7bdd41025ae18af4b969c4e Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 22:03:09 +0100 Subject: [PATCH 18/20] fix(i18n): remove unused toolbar label as reviewed --- src/react/strings/de.ts | 1 - src/react/strings/en.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/src/react/strings/de.ts b/src/react/strings/de.ts index 68369cd..8f12b99 100644 --- a/src/react/strings/de.ts +++ b/src/react/strings/de.ts @@ -136,7 +136,6 @@ export const de: Strings = { fontSize: 'Schriftgrad', fontSizeDown: 'Schriftgrad verkleinern', fontSizeUp: 'Schriftgrad vergrößern', - more: 'Mehr', moreTools: 'Weitere Werkzeuge', custom: 'Benutzerdefiniert', customColor: 'Benutzerdefinierte Farbe', diff --git a/src/react/strings/en.ts b/src/react/strings/en.ts index b282f41..87158f0 100644 --- a/src/react/strings/en.ts +++ b/src/react/strings/en.ts @@ -140,7 +140,6 @@ export const en = { fontSize: 'Font size', fontSizeDown: 'Decrease font size', fontSizeUp: 'Increase font size', - more: 'More', moreTools: 'More tools', custom: 'Custom', customColor: 'Custom color', From 74d0aa74398997b147219bd5727ff22f35ab303a Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:55:52 +0100 Subject: [PATCH 19/20] docs(controller): clarify mounted viewer ownership and icons --- docs/api.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/api.md b/docs/api.md index f1911a9..71c2d72 100644 --- a/docs/api.md +++ b/docs/api.md @@ -85,7 +85,6 @@ CSS is auto-injected, no import needed (or import `@p10node/office-engine/styles | `onError` | `(error) => void` | – | | | `controller` | `ViewerController` | its own | The viewer's state and commands for the host, see [headless mode](#headless-mode) | | `headless` | `boolean` | `false` | The document alone: no top bar, zoom control, outline panel, sheet tabs or slide list | -| `icons` | `Partial>` | – | The host's icons by name (`ICON_NAMES`), sized by font-size (1em), instead of the built-in ones | ### Headless mode @@ -146,6 +145,10 @@ New/Open replace the document and remain available for a read-only file when `al Import requires `allowEdit` and an editable workbook; it remains available with `allowOpen={false}`. Controllers are created with `createViewerController()`; publishing and attachment methods are internal to the engine. +Use one controller per mounted viewer. Give a modal or fullscreen viewer its own controller, even when it shows the same file. +During a temporary overlap, the latest mounted viewer owns a shared controller. Releasing it clears the controller; +an older viewer that remains mounted does not automatically regain ownership. + ### Comments ```tsx From 04406ad91ea300d18cb90eb3e0e05b05f4487636 Mon Sep 17 00:00:00 2001 From: Markus Date: Thu, 19 Nov 2026 11:41:09 +0100 Subject: [PATCH 20/20] fix(xlsx): fitting a column after an edit stops once the document is closed The column fit runs after the edit's result. When the viewer was given a new document meanwhile, its worker calls failed with "Document closed", uncaught. The client now tells that it is closed (`closed`), and the fit does nothing more once it is. Co-Authored-By: Claude Opus 5.5 --- src/core/worker/client.ts | 5 +++++ src/react/xlsx/XlsxView.tsx | 15 ++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) 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/react/xlsx/XlsxView.tsx b/src/react/xlsx/XlsxView.tsx index 4eb0df0..c9d5858 100644 --- a/src/react/xlsx/XlsxView.tsx +++ b/src/react/xlsx/XlsxView.tsx @@ -1532,10 +1532,16 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g /** columns that show #### for the numbers written in `range` are widened, as Excel does (a width set by hand stays) */ const widen = async (range: Range, at = sheet) => { - if (!editable || at !== sheet) return + // it runs after the edit's result: the document may have been closed (a new one opened) meanwhile + if (!editable || at !== sheet || client.closed) return const live = store.sheet(sheet) const need = new Map() - for (const [, cells] of await rowsOf(range.r0, Math.min(range.r1, range.r0 + 999))) { + const rows = await rowsOf(range.r0, Math.min(range.r1, range.r0 + 999)).catch((e: Error) => { + if (client.closed) return null + throw e + }) + if (!rows) return + for (const [, cells] of rows) { for (const [c, text, si, kind] of cells) { if (c < range.c0 || c > range.c1 || kind !== 1 || !text || (meta.formats[si] ?? 'General') === 'General' || live.colAxis.size(c) !== live.colAxis.def) continue const css = (styles[si] ?? {}) as Record @@ -1548,7 +1554,10 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g need.set(c, Math.max(need.get(c) ?? 0, w)) } } - for (const [c, px] of need) await sheetOp({ op: 'colWidth', c0: c, c1: c, px: Math.min(px, 400) }) + for (const [c, px] of need) { + if (client.closed) return + await sheetOp({ op: 'colWidth', c0: c, c1: c, px: Math.min(px, 400) }) + } } /** a column as wide as its longest text (double click on its edge) */