From 4caec8dae99397688ace5d21d178f2ab4fe099f0 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:04:43 +0100 Subject: [PATCH 01/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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 e21a9fb00461fc8cc7bdd41025ae18af4b969c4e Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 22:03:09 +0100 Subject: [PATCH 12/12] 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',