diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 34d3396..3f4d46c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,4 +64,5 @@ jobs: pip install python-pptx Pillow python scripts/fixtures.py --large-deck + - run: bun run build - run: bun run test:e2e diff --git a/README.md b/README.md index c65288b..134271c 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ Also online at [p10node.github.io/office-engine](https://p10node.github.io/offic - **Comments**: threads with replies, resolve, edit / delete, @mentions; on DOCX text, XLSX cells and PPTX slides, stored in the file the way Word, Excel and PowerPoint store them - **Real-time collaboration**: live edits, avatars, collaborators' cursors, offline edits sync on reconnect - **Dark mode and theming**: `theme="dark"` or `"auto"` (follows the OS), or a theme object with design tokens for colors, type and shape ([Theming](docs/theming.md)); documents keep their own colors +- **Translatable UI**: every text of the bars, menus and dialogs from one typed table; only English bundled by default; German available through an optional import with `de-DE` formatting (see [UI texts](docs/api.md#ui-texts)); any text replaceable through `strings` - **Embed anywhere**: React component, hook, vanilla `mount()`, `` web component, single ` + + +``` + +Document content stays in its original language. Default new sheet names, the author "Me" and new text box content also stay unchanged; the “Page 1 of 5” header/footer preset inserts text in the UI language. Font names, formula names and help, number format previews, host-provided labels and engine/transport errors (including main-thread fetch errors such as `HTTP 404 while fetching …`, collaboration errors such as `Document is still syncing`, and parsing-worker messages) are not translated by the table. Print, PDF and HTML export inherit the active UI table for viewer-generated labels; document content remains unchanged. + ## Without a React build ```html @@ -205,7 +296,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/docs/theming.md b/docs/theming.md index ef89f4b..688df4e 100644 --- a/docs/theming.md +++ b/docs/theming.md @@ -69,9 +69,81 @@ gives the class name and style their root needs: ```tsx const root = useThemeRoot(theme) -return
+return ( + +
+
+) ``` +`OfficeUIProvider` carries what `DocViewer` takes as `icons`, `components`, `locale` and `strings` to views mounted on +their own. Nested providers inherit the outer texts, icons and components. Local `strings` merge key by key; +an explicit `locale` changes number/date formatting while preserving the inherited texts. Omitted or `undefined` +components and string entries preserve the outer values. + +## Your own components + +Where tokens are not enough, the toolbars and dialogs render the host's own components: a design system's buttons, +selects and dialogs instead of the built-in ones. Each one left out keeps the built-in one. + +```tsx +import { DocViewer, type ButtonProps, type UIComponents } from '@p10node/office-engine' + +// Define component types outside the host's render so toolbar controls stay mounted. +function ViewerButton({ title, icon, label, children, active, expanded, disabled, onClick, onMouseDown }: ButtonProps) { + return ( + + {icon}{label}{children} + + ) +} + +function ViewerSeparator() { + return +} + +const components: Partial = { Button: ViewerButton, Separator: ViewerSeparator } + + +``` + +| Component | Used for | Props | +| ----------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Button` | every toolbar button, the toggles that open color, table and border pickers, the overflow button | `ButtonProps`: `title`, `icon` (resolved through `icons`), `iconName`, `label`, `children`, `active`, `expanded`, `disabled`, `wide`, `onClick`, `onMouseDown`, `className` (the built-in classes) | +| `Select` | font, style, format and menu dropdowns | `SelectProps`: `title`, `options` (`DropOption`: `value`, `label`, `hint`, `icon`, `disabled`, `sep`, `head`, `style`), `value` (undefined for a command menu), `onChange`, `label` (`null` hides the label for an icon-only trigger), `icon` (an `IconName`, not a resolved node), `className` (extra trigger class), `placeholder`, `width`, `menuWidth`, `disabled`, `alignRight` | +| `Separator` | between toolbar groups | none | +| `Dialog` | prompts (link, rename, …) and confirmations | `DialogProps`: `title`, `kind` (`'alert'` for a question), `children` (the body), `actions` (`label`, `onClick`, `extra` for an auxiliary action such as Remove link, `primary`, `submit`, `autoFocus`), `onSubmit` (the body is a form), `onClose` (Escape, backdrop) | +| `Toast` | short messages at the bottom | `text` (the viewer removes it after a few seconds) | + +The font-size input and its list (`SizeBox`), Page setup, Header / footer and Details dialogs, and the buttons +inside border pickers retain the built-in markup. `components` replaces the controls listed above. + +A host Dialog can put its footer outside the form: call the action's `onClick` from a regular button. Inside +a form, render `submit` actions as submit buttons and let `onSubmit` run them; do not also call their `onClick`, +which would submit twice. Keep `onClick` for the other actions. + +The document must keep the focus while a toolbar control is used, or the command loses its selection: + +- `Button`: pass `onMouseDown` to the element. It prevents the default, which keeps the focus. +- `Select`: open on mouse down with the default prevented, and handle its keys without moving the focus into the list. + The built-in one captures the keys at the window while open. + +The overflow menu measures each toolbar item from a wrapper of its own, so a host component needs no ref. +It measures the More button in the same pass and remeasures when Button, Select or Separator is replaced. + +Host Select lists rendered with React's `createPortal` remain inside their surrounding overflow menu or popover +for outside-click handling. The portal must belong to the same React tree as the Select. An independently +mounted React root or a non-React overlay has no such ownership path; render that list inside the Select's DOM +subtree instead. + +A host `Select` can render its trigger and option icons with the exported `Icon`: `` +(when `option.icon` is set). It uses the viewer's `icons` overrides and falls back to the built-in SVGs. + ## Tokens | Group | Tokens | diff --git a/e2e/app/built-locale.html b/e2e/app/built-locale.html new file mode 100644 index 0000000..af1df32 --- /dev/null +++ b/e2e/app/built-locale.html @@ -0,0 +1,10 @@ + + +
+ + diff --git a/e2e/app/embed.html b/e2e/app/embed.html index 4608cef..a066139 100644 --- a/e2e/app/embed.html +++ b/e2e/app/embed.html @@ -9,6 +9,8 @@
+ diff --git a/e2e/app/ui.tsx b/e2e/app/ui.tsx new file mode 100644 index 0000000..178a872 --- /dev/null +++ b/e2e/app/ui.tsx @@ -0,0 +1,53 @@ +import { useEffect, useState } from 'react' +import { createRoot } from 'react-dom/client' +import { createPortal } from 'react-dom' +import { PromptDialog } from '../../src/react/common/Dialog' +import { Btn, Dropdown, Pop, ToolbarRow } from '../../src/react/edit/Toolbar' +import { OfficeUIProvider, type ButtonProps, type DialogProps, type SelectProps } from '../../src/react/ui' +import '../../src/react/styles.css' + +window.__events = [] +const noop = () => {} +function Button(p: ButtonProps) { + return +} +function WideButton(p: ButtonProps) { + return )} + +} +function PortalSelect(p: SelectProps) { + const [open, setOpen] = useState(false) + return <> + + {open && createPortal(
+ {p.options.map((o) => )} +
, document.body)} + +} +const picker = (title: string) => window.__events.push({ type: 'pick', value, title })} /> +function App() { + const [wide, setWide] = useState(false) + const [tick, setTick] = useState(0) + return +
+ + + + {Array.from({ length: 17 }, (_, i) => )} +
+ {Array.from({ length: 8 }, (_, i) => )} + {picker('Overflow picker')} +
+ {() => picker('Popover picker')} + window.__events.push({ type: 'submit', value }) }} onClose={() => window.__events.push({ type: 'close' })} /> +
+
+} +createRoot(document.getElementById('root')!).render() diff --git a/e2e/built-package.ts b/e2e/built-package.ts new file mode 100644 index 0000000..346bce8 --- /dev/null +++ b/e2e/built-package.ts @@ -0,0 +1,32 @@ +/** Emitted-package suites require a complete, fresh production build. */ +import { beforeAll } from 'bun:test' +import { existsSync, readdirSync, statSync } from 'node:fs' +import { resolve } from 'node:path' + +export const packageRoot = resolve(process.env.BUILT_PACKAGE_ROOT ?? process.cwd()) +export const builtModule = (file: string) => `/@fs${packageRoot}/dist/${file}` + +function newestSource(path: string): number { + if (!existsSync(path)) return 0 + if (!statSync(path).isDirectory()) return statSync(path).mtimeMs + return Math.max(0, ...readdirSync(path).map((name) => newestSource(`${path}/${name}`))) +} + +/** An external package without sources is checked for completeness only. */ +export function useBuiltPackage() { + beforeAll(() => { + const outputs = ['index.js', 'locales/de.js', 'office-engine.worker.js', 'office-engine.embed.js', 'styles.css'] + for (const file of outputs) { + if (!existsSync(`${packageRoot}/dist/${file}`)) throw new Error(`Missing dist/${file} in ${packageRoot}; run bun run build before browser tests`) + } + const inputs = ['src', 'package.json', 'bun.lock', 'vite.config.ts', 'vite.embed.config.ts', 'vite.worker.config.ts', 'tsconfig.build.json'] + // Published packages do not include source/build inputs; a checkout must always be fresh, + // including when explicitly selected through BUILT_PACKAGE_ROOT. + if (existsSync(`${packageRoot}/src`)) { + const newest = Math.max(...inputs.map((file) => newestSource(`${packageRoot}/${file}`))) + for (const file of outputs) { + if (statSync(`${packageRoot}/dist/${file}`).mtimeMs < newest) throw new Error(`Stale dist/${file} in ${packageRoot}; run bun run build before browser tests`) + } + } + }) +} diff --git a/e2e/components.spec.ts b/e2e/components.spec.ts new file mode 100644 index 0000000..1e7a9da --- /dev/null +++ b/e2e/components.spec.ts @@ -0,0 +1,92 @@ +import { describe, expect, test } from 'bun:test' +import { docxParas, paraText, runsOf, useBrowser, viewer } from './harness' + +useBrowser() + +const open = async (viewport?: { width: number; height: number }) => { + const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true, components: true }, { viewport }) + await v.page.locator('.de-ebar').waitFor() + return v +} + +describe('host UI components', () => { + test('docx: every toolbar button is the host Button, and it keeps the selection for formatting', async () => { + const v = await open() + const counts = await v.page.evaluate(() => { + const bar = document.querySelector('.de-ebar')! + return { + host: bar.querySelectorAll('button[data-host-button]').length, + engine: bar.querySelectorAll('button.de-tb').length, + seps: bar.querySelectorAll('[data-host-sep]').length, + engineSeps: bar.querySelectorAll('.de-tb-sep').length, + } + }) + expect(counts.host).toBeGreaterThan(10) + expect(counts.engine).toBe(0) + expect(counts.seps).toBeGreaterThan(0) + expect(counts.engineSeps).toBe(0) + + await v.selectText('document') + await v.btn('Bold').click() + await v.page.waitForFunction(() => document.querySelector('button[data-host-button][aria-label^="Bold"]')?.hasAttribute('data-active')) + const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text.includes('document'))!.s.b).toBe(true) + expect(v.errors).toEqual([]) + }) + + test('docx: a narrow toolbar still moves what does not fit under the host More button', async () => { + const v = await open({ width: 640, height: 900 }) + const more = v.page.locator('.de-ebar button[data-host-button][aria-label="More tools"]') + await more.waitFor() + // Hosts can use a wide text button: reserve its actual width, not the engine's icon width. + await v.page.waitForFunction(() => { + const bar = document.querySelector('.de-ebar')! + const right = bar.getBoundingClientRect().right + return [...bar.querySelectorAll(':scope > span')].every((el) => el.getBoundingClientRect().right <= right) + }, null, { timeout: 5000 }) + await more.click() + expect(await v.page.locator('.de-ebar-more button[data-host-button]').count()).toBeGreaterThan(0) + expect(v.errors).toEqual([]) + }) + + test('docx: the link prompt is the host Dialog and submits', async () => { + const v = await open() + await v.selectText('document') + await v.page.keyboard.press('Control+k') + const dialog = v.page.locator('[data-host-dialog][role="dialog"]') + await dialog.waitFor() + expect(await v.page.locator('.de-dialog').count()).toBe(0) + await dialog.locator('input').fill('https://example.org/docs') + await v.page.keyboard.press('Enter') + await dialog.waitFor({ state: 'detached' }) + const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text.includes('document'))!.href).toBe('https://example.org/docs') + expect(v.errors).toEqual([]) + }) + + test('docx: the built-in edit-link prompt keeps Remove link on the left and removes the link', async () => { + const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true }) + await v.selectText('document') + await v.page.keyboard.press('Control+k') + const dialog = v.page.locator('.de-dialog') + await dialog.locator('input').fill('https://example.org/docs') + await v.page.keyboard.press('Enter') + await dialog.waitFor({ state: 'detached' }) + await v.selectText('document') + await v.page.keyboard.press('Control+k') + const extra = dialog.locator('button.de-dialog-extra') + await extra.waitFor() + expect(await extra.innerText()).toBe('Remove') + const bounds = await dialog.locator('.de-dialog-btns').evaluate((row) => { + const [extra, cancel] = row.querySelectorAll('button') + return { left: row.getBoundingClientRect().left, extra: extra.getBoundingClientRect().left, gap: cancel.getBoundingClientRect().left - extra.getBoundingClientRect().right } + }) + expect(bounds.extra).toBe(bounds.left) + expect(bounds.gap).toBeGreaterThan(20) + await extra.click() + await dialog.waitFor({ state: 'detached' }) + const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text.includes('document'))!.href).toBeUndefined() + expect(v.errors).toEqual([]) + }) +}) diff --git a/e2e/embed.spec.ts b/e2e/embed.spec.ts index d7d38f3..2a59833 100644 --- a/e2e/embed.spec.ts +++ b/e2e/embed.spec.ts @@ -51,4 +51,34 @@ describe('embedding without React', () => { await v.page.evaluate(() => (window as any).__mounted.destroy()) expect(await host.innerHTML()).toBe('') }) + + test('locale and strings update live through mount() and the web component', async () => { + const v = await viewer({}, { page: 'embed.html' }) + const wc = v.page.locator('#wc') + const host = v.page.locator('#mounted') + await wc.locator('.de-page-inner').first().waitFor() + await host.locator('.de-grid').waitFor() + await v.page.evaluate(() => { + const el = document.getElementById('wc') as HTMLElement & { strings?: { file?: { menu?: string } } } + el.setAttribute('file-menu', 'true') + const de = window.__german + el.strings = { ...de, file: { ...de.file, menu: 'Ablage' } } + ;(window as any).__mounted.update({ toolbar: true, strings: { ...de, file: { ...de.file, menu: 'Dateien' } } }) + }) + await wc.getByRole('button', { name: 'Ablage', exact: true }).waitFor() + await host.getByRole('button', { name: 'Dateien', exact: true }).waitFor() + await wc.getByRole('button', { name: 'Ablage', exact: true }).click() + expect(await wc.locator('.de-dd-pop').innerText()).toContain('Öffnen…') + await v.page.keyboard.press('Escape') + await v.page.evaluate(() => { + const el = document.getElementById('wc') as HTMLElement & { strings?: object } + el.strings = undefined + el.setAttribute('locale', 'fr-FR') + ;(window as any).__mounted.update({ locale: 'en', strings: undefined }) + }) + await wc.getByRole('button', { name: 'File', exact: true }).waitFor() + await host.getByRole('button', { name: 'File', exact: true }).waitFor() + expect((await v.page.evaluate(() => (window as any).__wcEvents)).length).toBe(1) + expect(v.errors).toEqual([]) + }) }) diff --git a/e2e/harness.ts b/e2e/harness.ts index c2e8ce6..99ccf4f 100644 --- a/e2e/harness.ts +++ b/e2e/harness.ts @@ -56,9 +56,9 @@ export function useBrowser() { export type Params = Record /** Opens the fixture with DocViewer props from `params` and waits for the document. */ -export async function viewer(params: Params, opts: { wait?: boolean; page?: string; viewport?: { width: number; height: number } } = {}) { +export async function viewer(params: Params, opts: { wait?: boolean; page?: string; viewport?: { width: number; height: number }; locale?: string } = {}) { if (!shared) throw new Error('useBrowser() missing') - const ctx = await shared.browser.newContext({ viewport: opts.viewport ?? { width: 1600, height: 1000 }, acceptDownloads: true }) + const ctx = await shared.browser.newContext({ viewport: opts.viewport ?? { width: 1600, height: 1000 }, acceptDownloads: true, locale: opts.locale }) open.add(ctx) const page = await ctx.newPage() const v = new Viewer(page, ctx) diff --git a/e2e/locale-built.spec.ts b/e2e/locale-built.spec.ts new file mode 100644 index 0000000..46905a5 --- /dev/null +++ b/e2e/locale-built.spec.ts @@ -0,0 +1,301 @@ +/** Production-artifact checks: run `bun run build` first, as CI does before browser tests. */ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { parasToDocx, rowsToXlsx } from '../src/core/convert' +import { unzipSync, zipSync, strFromU8, strToU8 } from 'fflate' +import { useBrowser, viewer, type Viewer, SAMPLES } from './harness' + +import { builtModule, useBuiltPackage } from './built-package' + +useBuiltPackage() +useBrowser() +const pkg = builtModule('index.js') +const german = builtModule('locales/de.js') + +/** Load the emitted package in a real browser, sharing the fixture's React runtime. */ +async function mount(v: Viewer, props: Record = {}, outerGerman = false) { + await v.page.waitForFunction(() => !!(window as any).__builtRuntime) + await v.page.evaluate(async ({ pkg, german, props, outerGerman }) => { + const { React, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + const de = outerGerman ? (await import(/* @vite-ignore */ german)).de : undefined + const root = createRoot(document.getElementById('built')!) + let current = props + const onLoad = (c: any) => { (window as any).__builtClient = c; window.__events.push({ type: 'load', kind: c.kind, name: c.name }) } + const onError = (e: Error) => window.__events.push({ type: 'error', message: e.message }) + const render = () => { + const view = React.createElement(api.DocViewer, { + ...current, + onLoad, + onError, + }) + root.render(outerGerman ? React.createElement(api.StringsProvider, { strings: de }, view) : view) + } + ;(window as any).__builtUpdate = (next: any) => { current = { ...current, ...next }; render() } + ;(window as any).__builtApi = api + render() + }, { pkg, german, props, outerGerman }) + if (props.src) await v.ready() + else await v.page.locator('.de-file').waitFor() +} + +async function open(props: Record, locale = 'en-GB', outerGerman = false) { + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale }) + await mount(v, props, outerGerman) + return v +} + +async function update(v: Viewer, props: Record) { + await v.page.evaluate((props) => (window as any).__builtUpdate(props), props) +} + +function emfDeck() { + const files = unzipSync(readFileSync(`${SAMPLES}/sample.pptx`)) + const slide = 'ppt/slides/slide1.xml' + files[slide] = strToU8(strFromU8(files[slide]).replace('', ``)) + const rel = 'ppt/slides/_rels/slide1.xml.rels' + files[rel] = strToU8(strFromU8(files[rel]).replace('', '')) + files['ppt/media/regression.emf'] = new Uint8Array([1, 0, 0, 0]) + files['[Content_Types].xml'] = strToU8(strFromU8(files['[Content_Types].xml']).replace('', '')) + return Buffer.from(zipSync(files)) +} + +describe('built package localization', () => { + for (const locale of ['en-GB', 'vi-VN', 'de-DE', 'ar-EG']) { + test(`default formatting follows the ${locale} browser; invalid tags fall back`, async () => { + const v = await open({ src: 'samples/sample.docx' }, locale) + const read = () => v.page.evaluate(() => { + const api = (window as any).__builtApi + const s = api.resolveStrings() + const date = new Date('2026-03-05T14:00:00Z') + return { locale: s.locale, date: date.toLocaleString(s.locale), browserDate: date.toLocaleString(), count: s.docx.status(1, 2, 1234567, s.locale), browserCount: (1234567).toLocaleString() } + }) + const initial = await read() + const optionalGermanRequests = await v.page.evaluate(() => performance.getEntriesByType('resource').filter((e) => e.name.includes('/locales/de.js')).length) + expect(optionalGermanRequests).toBe(0) + const created = await v.page.evaluate(async () => { + const xml = await (await (window as any).__builtClient.call('part', 'docProps/core.xml')).text() + const value = new DOMParser().parseFromString(xml, 'application/xml').getElementsByTagNameNS('*', 'created')[0]!.textContent! + return new Date(value).toLocaleString() + }) + await v.menu('Document details') + await v.page.locator('[role=dialog] dd', { hasText: created }).first().waitFor() + expect(await v.page.locator('[role=dialog]').innerText()).toContain('8.5 × 11 in') + expect(await v.status()).toMatch(/^Page 1 of [0-9]+/) + await v.page.locator('[role=dialog] button', { hasText: 'Close' }).click() + expect(initial.locale).toBeUndefined() + expect(initial.date).toBe(initial.browserDate) + expect(initial.count).toContain(initial.browserCount) + expect(await v.page.locator('.de-file').innerText()).toBe('File') + for (const malformed of [{ locale: 'de_DE' }, { locale: '__proto__' }, { locale: undefined, strings: { locale: 'de_DE' } }]) { + await update(v, malformed) + await v.page.locator('.de-page-inner').first().waitFor() + expect(await v.page.locator('.de-file').innerText()).toBe('File') + await v.menu('Document details') + await v.page.locator('[role=dialog] dd', { hasText: created }).first().waitFor() + await v.page.locator('[role=dialog] button', { hasText: 'Close' }).click() + expect(v.errors).toEqual([]) + } + // Render date/count consumers inside the actual provider, not only the resolver. + const rendered = await v.page.evaluate(async ({ pkg }) => { + const { React, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + const host = document.createElement('div'); document.body.append(host) + const root = createRoot(host) + function Probe() { + const s = api.useStrings() + return React.createElement('span', null, `${new Date('2026-03-05T14:00:00Z').toLocaleString(s.locale)}|${s.docx.status(1, 2, 1234567, s.locale)}`) + } + root.render(React.createElement(api.StringsProvider, { locale: 'de_DE' }, React.createElement(Probe))) + await new Promise((r) => setTimeout(r, 100)) + const text = host.textContent; root.unmount(); host.remove() + return text + }, { pkg }) + expect(rendered).toContain(initial.browserDate) + expect(rendered).toContain(initial.browserCount) + }) + } + + + test('standalone production embed loads English and explicitly imported German', async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'vi-VN' }) + await v.page.addScriptTag({ url: builtModule('office-engine.embed.js') }) + await v.page.evaluate(() => { + const el = document.createElement('office-viewer') + el.setAttribute('src', '/samples/sample.docx') + el.setAttribute('locale', 'de_DE') + el.addEventListener('load', (e: any) => window.__events.push({ type: 'load', ...e.detail })) + el.addEventListener('error', (e: any) => window.__events.push({ type: 'error', message: e.detail?.message })) + document.getElementById('built')!.append(el) + }) + await v.ready('docx') + expect(await v.page.locator('office-viewer .de-file').innerText()).toBe('File') + await v.page.evaluate(async ({ german }) => { + const el = document.querySelector('office-viewer')! as any + el.strings = (await import(/* @vite-ignore */ german)).de + el.setAttribute('locale', 'en-GB') + }, { german }) + await v.page.locator('office-viewer .de-file', { hasText: 'Datei' }).waitFor() + await v.page.locator('office-viewer .de-file').click() + await v.page.locator('office-viewer .de-dd-text', { hasText: 'Dokumenteigenschaften' }).click() + await v.page.locator('office-viewer [role=dialog][aria-label="Dokumenteigenschaften"]').waitFor() + expect((await v.events('load')).length).toBe(1) + expect(v.errors).toEqual([]) + }) + + test('opt-in German, outer provider, partial overrides, pluralization and live switching', async () => { + const v = await open({ src: 'samples/sample.xlsx', editable: true, comments: { open: true } }, 'en-GB', true) + expect(await v.page.locator('.de-file').innerText()).toBe('Datei') + await v.page.locator('.de-cm-empty', { hasText: 'Zelle' }).waitFor() + await v.page.evaluate(async ({ german }) => { + const { React, createRoot } = (window as any).__builtRuntime + const api = (window as any).__builtApi + const de = (await import(/* @vite-ignore */ german)).de + const host = document.createElement('div'); host.id = 'plural-probe'; document.body.append(host) + function Probe() { + const s = api.useStrings() + return React.createElement('span', null, [s.docx.status(1, 1, 1, s.locale), s.xlsx.status(1, 1, s.locale), s.xlsx.usedRangeValue(2, 3, s.locale), s.pptx.status(1, 2, s.locale)].join('|')) + } + createRoot(host).render(React.createElement(api.StringsProvider, { strings: de }, React.createElement(Probe))) + return { loaded: performance.getEntriesByType('resource').map((e) => e.name).filter((x) => x.includes('/locales/de.js')) } + }, { german }) + await v.page.locator('#plural-probe', { hasText: '1 Wort|1 Zeile × 1 Spalte|2 Zeilen × 3 Spalten|Folie 1 von 2' }).waitFor() + expect(await v.page.evaluate(() => performance.getEntriesByType('resource').some((e) => e.name.includes('/locales/de.js')))).toBe(true) + await update(v, { strings: { file: { menu: 'Ablage' } } }) + await v.page.locator('.de-file', { hasText: 'Ablage' }).waitFor() + expect(await v.barButton('Ansicht').count()).toBe(1) + // Override the inherited German table with the emitted English table and switch back without reopening. + await v.page.evaluate(() => (window as any).__builtUpdate({ strings: (window as any).__builtApi.en })) + await v.page.locator('.de-file', { hasText: 'File' }).waitFor() + await v.page.locator('.de-cm-empty', { hasText: 'cell' }).waitFor() + await update(v, { strings: undefined }) + await v.page.locator('.de-file', { hasText: 'Datei' }).waitFor() + await v.page.locator('.de-cm-empty', { hasText: 'Zelle' }).waitFor() + expect((await v.events('load')).length).toBe(1) + expect(v.errors).toEqual([]) + }) + + + test('running DOCX/XLSX status receives numeric counts and renders singular German', async () => { + const docx = Buffer.from(await (await parasToDocx([{ runs: [{ text: 'Wort' }] }])).arrayBuffer()) + const xlsx = Buffer.from(await (await rowsToXlsx([['Wert']], 'Blatt')).arrayBuffer()) + const statuses: Record = {} + for (const [kind, bytes] of [['docx', docx], ['xlsx', xlsx]] as const) { + const v = await viewer({}, { page: 'built-locale.html', wait: false }) + await v.page.route(`**/singular.${kind}`, (route) => route.fulfill({ body: bytes })) + await mount(v, { src: `/singular.${kind}` }, true) + const expected = kind === 'docx' ? 'Seite 1 von 1 · 1 Wort' : '1 Zeile × 1 Spalte' + await v.page.locator('.de-bar .de-status', { hasText: expected }).waitFor() + statuses[kind] = await v.page.locator('.de-bar .de-status').first().innerText() + expect(statuses[kind]).toBe(expected) + if (kind === 'docx') { + await v.page.evaluate(() => (window as any).__builtUpdate({ strings: { docx: { status: (p: number, ps: number, words: number) => `${typeof p}/${typeof ps}/${typeof words}:${words === 1 ? 'one' : 'many'}` } } })) + await v.page.locator('.de-bar .de-status', { hasText: 'number/number/number:one' }).waitFor() + } + expect(v.errors).toEqual([]) + } + }) + + test('comment navigation survives fresh strings identities on the same sheet', async () => { + const v = await open({ src: 'samples/sample.xlsx', editable: true, comments: { open: true } }) + await v.clickCell('B3') + await v.page.locator('.de-cm-new').click() + await v.page.locator('.de-cm-draft textarea').fill('Navigation regression') + await v.page.locator('.de-cm-draft button', { hasText: 'Comment' }).click() + const card = v.page.locator('.de-cm-card').first() + await card.waitFor() + await v.clickCell('A1') + await card.click() + await v.page.waitForFunction(() => document.querySelector('.de-fx-ref')?.textContent === 'B3') + await v.clickCell('A1') + await update(v, { strings: { file: { menu: 'Fresh identity' } } }) + await v.page.locator('.de-file', { hasText: 'Fresh identity' }).waitFor() + await card.click() + await v.page.waitForFunction(() => document.querySelector('.de-fx-ref')?.textContent === 'B3', null, { timeout: 3000 }) + expect(await v.page.locator('.de-fx-ref').innerText()).toBe('B3') + expect(v.errors).toEqual([]) + }) + + test('German clipboard failures and paste limits use the active strings', async () => { + const bytes = Buffer.from(await (await rowsToXlsx(Array.from({ length: 6000 }, (_, i) => [String(i)]), 'Data')).arrayBuffer()) + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'de-DE' }) + await v.page.route('**/clipboard.xlsx', (route) => route.fulfill({ body: bytes })) + await mount(v, { src: '/clipboard.xlsx', editable: true }, true) + await v.clickCell('A1') + await v.page.keyboard.press('ControlOrMeta+a') + await v.page.evaluate(() => { + Object.defineProperty(navigator.clipboard, 'writeText', { + configurable: true, + value: async () => { throw new DOMException('Clipboard denied', 'NotAllowedError') }, + }) + const data = new DataTransfer() + document.activeElement!.dispatchEvent(new ClipboardEvent('copy', { clipboardData: data, bubbles: true, cancelable: true })) + }) + await v.page.locator('.de-toast', { hasText: 'Der Browser hat den Zugriff auf die Zwischenablage blockiert. Zum Kopieren weniger Zeilen auswählen.' }).waitFor() + await v.clickCell('A1') + await v.page.evaluate(() => { + const client = (window as any).__builtClient + const call = client.call.bind(client) + client.call = (op: string, ...args: any[]) => { + const result = call(op, ...args) + if (op === 'xlsx.set') (window as any).__pasteDone = result + return result + } + const data = new DataTransfer() + data.setData('text/plain', Array.from({ length: 100001 }, (_, i) => String(i)).join('\n')) + document.activeElement!.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true })) + }) + await v.page.locator('.de-toast', { hasText: 'Nur die ersten 100.000 von 100.001 Zellen wurden eingefügt' }).waitFor() + await v.page.evaluate(() => (window as any).__pasteDone) + expect(v.errors).toEqual([]) + }) + + test('Visio labels use the active table and main keeps the drawing read-only', async () => { + const v = await open({ src: 'samples/sample.vsdx', editable: true }, 'en-GB', true) + await v.menu('Dokumenteigenschaften') + const germanLabel = await v.page.locator('[role=dialog]').innerText() + expect(germanLabel).toContain('Microsoft-Visio-Zeichnung') + expect(await v.barButton('Ansicht').count()).toBe(0) + await v.page.locator('[role=dialog] button', { hasText: 'Schließen' }).click() + await v.page.evaluate(() => (window as any).__builtUpdate({ strings: (window as any).__builtApi.en })) + await v.page.locator('.de-file', { hasText: 'File' }).waitFor() + await v.menu('Document details') + const englishLabel = await v.page.locator('[role=dialog]').innerText() + expect(englishLabel).toContain('Microsoft Visio drawing') + expect(v.errors).toEqual([]) + }) + + test('German EMF label survives HTML export/reopen and print/PDF separate roots', async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false }) + await v.page.route('**/locale-emf.pptx', (route) => route.fulfill({ body: emfDeck(), contentType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' })) + // Avoid opening the native dialog, while retaining the actual production print preparation and root. + await v.page.addInitScript(() => { + window.print = () => {} + Document.prototype.execCommand = () => true + }) + await mount(v, { src: '/locale-emf.pptx' }, true) + await v.page.locator('.de-slide-inner .de-ph', { hasText: 'EMF-Bild' }).first().waitFor() + const html = await v.downloadAs('Webseite') + expect(html.text.includes('EMF-Bild')).toBe(true) + expect(html.text.includes('EMF image')).toBe(false) + const reopened = await v.ctx.newPage() + await reopened.setContent(html.text) + expect(await reopened.locator('.de-ph', { hasText: 'EMF-Bild' }).count()).toBeGreaterThan(0) + for (const action of ['Drucken', 'PDF-Dokument']) { + await v.menu(action) + const captured = await v.page.waitForFunction(() => { + const frame = [...document.querySelectorAll('iframe')].find((f) => !f.hasAttribute('data-captured') && f.contentDocument?.querySelector('.de-print')?.textContent?.includes('EMF-Bild')) + if (!frame) return false + frame.setAttribute('data-captured', '') + return frame.contentDocument!.documentElement.outerHTML + }) + const prepared = await captured.jsonValue() as string + expect(prepared).not.toContain('EMF image') + if (action === 'PDF-Dokument') { + await reopened.setContent(prepared) + expect((await reopened.pdf({ preferCSSPageSize: true })).subarray(0, 4).toString()).toBe('%PDF') + } + } + expect(v.errors).toEqual([]) + }) +}) diff --git a/e2e/locale-docx.spec.ts b/e2e/locale-docx.spec.ts new file mode 100644 index 0000000..c93fd40 --- /dev/null +++ b/e2e/locale-docx.spec.ts @@ -0,0 +1,23 @@ +import { describe, expect, test } from 'bun:test' +import { de } from '../src/locales/de' +import { useBrowser, viewer } from './harness' + +useBrowser() + +describe('locale: DOCX', () => { + test('status, toolbar and page setup in German', async () => { + const v = await viewer({ src: 'samples/sample.docx', locale: 'de-DE', editable: true }) + await v.page.locator('.de-ebar').first().waitFor() + expect(await v.status()).toMatch(/Seite 1 von \d+/) + expect(await v.btn('Fett').count()).toBe(1) + expect(await v.btn('Rückgängig').count()).toBe(1) + + await v.btn(de.docx.pageSetup).click() + const ps = v.page.locator('[role=dialog][aria-label="Seite einrichten"]') + await ps.waitFor() + expect(await ps.innerText()).toContain('Querformat') + await ps.locator('button', { hasText: 'Abbrechen' }).click() + await ps.waitFor({ state: 'detached' }) + expect(v.errors).toEqual([]) + }) +}) diff --git a/e2e/locale-xlsx.spec.ts b/e2e/locale-xlsx.spec.ts new file mode 100644 index 0000000..ec1f076 --- /dev/null +++ b/e2e/locale-xlsx.spec.ts @@ -0,0 +1,21 @@ +import { describe, expect, test } from 'bun:test' +import { useBrowser, viewer } from './harness' + +useBrowser() + +describe('locale: XLSX', () => { + test('status, toolbar and sheet tab menu in German', async () => { + const v = await viewer({ src: 'samples/sample.xlsx', locale: 'de-DE', editable: true }) + await v.page.locator('.de-ebar').first().waitFor() + expect(await v.status()).toMatch(/Zeilen × \d+ Spalten/) + expect(await v.btn('Fett').count()).toBe(1) + expect(await v.btn('Rahmenlinien').count()).toBe(1) + + await v.page.locator('.de-tab[role=tab]').first().click({ button: 'right' }) + const menu = v.page.locator('.de-ctx') + await menu.waitFor() + expect(await menu.innerText()).toContain('Blatt löschen') + await v.page.keyboard.press('Escape') + expect(v.errors).toEqual([]) + }) +}) diff --git a/e2e/locale.spec.ts b/e2e/locale.spec.ts new file mode 100644 index 0000000..1d19424 --- /dev/null +++ b/e2e/locale.spec.ts @@ -0,0 +1,85 @@ +import { describe, expect, test } from 'bun:test' +import { en } from '../src/react/strings' +import { de } from '../src/locales/de' +import { useBrowser, viewer } from './harness' + +useBrowser() + +describe('locale', () => { + test('bar, File menu and details dialog in German', async () => { + const v = await viewer({ src: 'samples/sample.docx', locale: 'de-DE' }) + expect(await v.page.locator('.de-bar .de-file').innerText()).toContain('Datei') + expect(await v.barButton('Bearbeiten').count()).toBe(1) + + const labels = await v.menuLabels() + expect(labels).toContain('Öffnen…') + expect(labels).toContain('PDF-Dokument') + expect(labels).toContain('Dokumenteigenschaften') + + await v.menu('Dokumenteigenschaften') + const dlg = v.page.locator('[role=dialog][aria-label="Dokumenteigenschaften"]') + await dlg.waitFor() + expect(await dlg.innerText()).toContain('Dateigröße') + await dlg.locator('button', { hasText: 'Schließen' }).click() + await dlg.waitFor({ state: 'detached' }) + + await v.barButton('Bearbeiten').click() + expect(await v.barButton('Ansicht').count()).toBe(1) + expect(v.errors).toEqual([]) + }) + + test('PPTX in German: status, zoom, present', async () => { + const v = await viewer({ src: 'samples/sample.pptx', locale: 'de-DE' }) + expect(await v.status()).toMatch(/Folie 1 von \d+/) + expect(await v.page.locator('.de-zoom[aria-label="Zoom"] button[aria-label="Vergrößern"]').count()).toBe(1) + expect(await v.page.locator('.de-present-btn').innerText()).toContain('Bildschirmpräsentation') + expect(v.errors).toEqual([]) + }) + + test('a partial override keeps the other texts', async () => { + const v = await viewer({ src: 'samples/sample.docx', locale: 'de-DE', fileLabel: 'Ablage' }) + expect(await v.page.locator('.de-bar .de-file').innerText()).toContain('Ablage') + expect(await v.barButton('Bearbeiten').count()).toBe(1) + }) + + test('English stays the default', async () => { + const v = await viewer({ src: 'samples/sample.pptx' }) + expect(await v.page.locator('.de-bar .de-file').innerText()).toContain('File') + expect(await v.status()).toMatch(/Slide 1 of \d+/) + }) + + for (const kind of ['docx', 'xlsx', 'pptx'] as const) { + test(`${kind}: switching locale updates comment hints without reopening the document`, async () => { + const v = await viewer({ src: `samples/sample.${kind}`, editable: true, cmOpen: true }) + const empty = v.page.locator('.de-cm-empty') + await empty.filter({ hasText: en[kind].commentHint }).waitFor() + await v.page.evaluate(() => window.__setLanguage('de-DE')) + await empty.filter({ hasText: de[kind].commentHint }).waitFor() + expect(await v.page.locator('.de-cm-panel').getAttribute('aria-label')).toBe('Kommentare') + expect((await v.events('load')).length).toBe(1) + expect(v.errors).toEqual([]) + }) + } + + test('PPTX comment locations follow the UI language', async () => { + const v = await viewer({ src: 'samples/sample.pptx', locale: 'de-DE', editable: true, cmOpen: true }) + await v.page.locator('.de-cm-new').click() + const draft = v.page.locator('.de-cm-draft') + await draft.waitFor() + expect(await draft.locator('.de-cm-quote').innerText()).toBe('Folie 1') + await draft.locator('textarea').fill('Kommentar') + await draft.locator('button', { hasText: 'Kommentieren' }).click() + const quote = v.page.locator('.de-cm-card .de-cm-quote') + await quote.filter({ hasText: 'Folie 1' }).waitFor() + await v.page.evaluate(() => window.__setLanguage('en')) + await quote.filter({ hasText: 'Slide 1' }).waitFor() + expect(v.errors).toEqual([]) + }) + + test('unknown locales fall back to English, including prototype property names', async () => { + const v = await viewer({ src: 'samples/sample.docx', locale: 'constructor' }) + expect(await v.page.locator('.de-file').innerText()).toContain('File') + expect(await v.status()).toMatch(/Page 1 of /) + expect(v.errors).toEqual([]) + }) +}) diff --git a/e2e/ui-built.spec.ts b/e2e/ui-built.spec.ts new file mode 100644 index 0000000..d2ad794 --- /dev/null +++ b/e2e/ui-built.spec.ts @@ -0,0 +1,49 @@ +/** Exercise host UI/provider composition against emitted ESM, after `bun run build`. */ +import { expect, test } from 'bun:test' +import { docxParas, paraText, runsOf, useBrowser, viewer } from './harness' + +import { builtModule, useBuiltPackage } from './built-package' + +useBuiltPackage() +useBrowser() + +test('built UI inherits German through formatting-only locales and defined components, preserving real edits', async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'en-GB' }) + await v.page.waitForFunction(() => !!(window as any).__builtRuntime) + await v.page.evaluate(async ({ pkg, german }) => { + const { React: R, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + if ('de' in api || 'LOCALES' in api) throw new Error('optional German leaked into root exports') + const de = (await import(/* @vite-ignore */ german)).de + function Button(p: any) { + return R.createElement('button', { 'data-built-host': '', 'aria-label': p.title, 'data-active': p.active ? '' : undefined, disabled: p.disabled, onMouseDown: p.onMouseDown, onClick: p.onClick }, p.icon, p.label, p.children) + } + const root = createRoot(document.getElementById('built')!) + let current: any = { src: '/samples/sample.docx', editable: true, locale: 'en-GB' } + const onLoad = (c: any) => window.__events.push({ type: 'load', kind: c.kind }) + const onError = (e: Error) => window.__events.push({ type: 'error', message: e.message }) + function render() { + root.render(R.createElement(api.OfficeUIProvider, { strings: de, components: { Button } }, + R.createElement(api.OfficeUIProvider, { locale: 'fr-FR', components: { Button: undefined } }, + R.createElement(api.DocViewer, { ...current, strings: { file: { menu: 'Ablage' } }, + onLoad, onError, + onSave: async (f: File) => { const bytes = new Uint8Array(await f.arrayBuffer()); let raw = ''; for (const b of bytes) raw += String.fromCharCode(b); window.__events.push({ type: 'save', b64: btoa(raw) }) }, + })))) + } + ;(window as any).__builtUpdate = (p: any) => { current = { ...current, ...p }; render() } + render() + }, { pkg: builtModule('index.js'), german: builtModule('locales/de.js') }) + await v.ready('docx') + expect(await v.page.locator('.de-file').innerText()).toBe('Ablage') + await v.selectText('document') + await v.page.locator('button[data-built-host][aria-label^="Fett"]').click() + await v.page.locator('button[data-built-host][aria-label^="Fett"][data-active]').waitFor() + await v.page.evaluate(() => (window as any).__builtUpdate({ locale: 'vi-VN' })) + expect(await v.page.locator('.de-file').innerText()).toBe('Ablage') + await v.page.locator('.de-bar button.de-mode', { hasText: 'Speichern' }).click() + const saved = await v.waitEvent('save') + const p = (await docxParas(Buffer.from(saved.b64 as string, 'base64'))).find((x) => paraText(x).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text.includes('document'))!.s.b).toBe(true) + expect(await v.events('load')).toHaveLength(1) + expect(v.errors).toEqual([]) +}) diff --git a/e2e/ui-layout.spec.ts b/e2e/ui-layout.spec.ts new file mode 100644 index 0000000..97c5047 --- /dev/null +++ b/e2e/ui-layout.spec.ts @@ -0,0 +1,110 @@ +import { expect, test } from 'bun:test' +import { useBrowser, viewer } from './harness' + +useBrowser() + +test('More keeps its natural width in a 600px row and replacement host components are remeasured', async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const more = v.page.locator('.de-ebar').first().locator('.de-ebar-morewrap button') + await more.waitFor() + const bounds = () => v.page.locator('.de-ebar').first().evaluate((row) => { + const wrapper = row.querySelector('.de-ebar-morewrap')! + const clone = wrapper.cloneNode(true) as HTMLElement + clone.style.cssText = 'position:absolute;width:max-content;visibility:hidden' + row.append(clone) + const natural = clone.getBoundingClientRect().width + clone.remove() + return { + natural, width: wrapper.getBoundingClientRect().width, + right: wrapper.getBoundingClientRect().right, edge: row.getBoundingClientRect().right - 8, + cut: row.querySelectorAll(':scope > [data-i]').length, + } + }) + const before = await bounds() + console.info('initial More bounds', JSON.stringify(before)) + await v.page.getByText('Replace components', { exact: true }).click() + const after = await bounds() + console.info('replacement More bounds', JSON.stringify(after)) + expect(before.width).toBeCloseTo(before.natural, 1) + expect(before.right).toBeLessThanOrEqual(before.edge + 1) + expect(after.cut).toBeLessThan(before.cut) + expect(after.width).toBeCloseTo(after.natural, 1) + expect(after.right).toBeLessThanOrEqual(after.edge + 1) + // Unrelated host rerenders must not read toolbar item geometry again. + await v.page.evaluate(() => { + const original = Element.prototype.getBoundingClientRect + Element.prototype.getBoundingClientRect = function () { + if (this.matches('.de-ebar > [data-i], .de-ebar-morewrap')) window.__events.push({ type: 'measure' }) + return original.call(this) + } + }) + await v.page.getByText('Rerender 0', { exact: true }).click() + console.info('geometry reads on unrelated rerender', (await v.events('measure')).length) + expect(await v.events('measure')).toHaveLength(0) + await more.click() + expect(await v.page.locator('.de-ebar-more button').count()).toBeGreaterThan(0) + expect(v.errors).toEqual([]) +}) + +test('a delayed host dialog focuses and selects the prompt input', async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const input = v.page.getByRole('dialog').locator('input') + await input.waitFor() + const focus = await input.evaluate((el: HTMLInputElement) => ({ focused: document.activeElement === el, start: el.selectionStart, end: el.selectionEnd })) + console.info('delayed prompt focus/selection', JSON.stringify(focus)) + expect(focus).toEqual({ focused: true, start: 0, end: 6 }) + expect(v.errors).toEqual([]) +}) + +test('a prompt host footer outside the form and Enter each submit once', async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const input = v.page.getByRole('dialog').locator('input') + await input.waitFor() + expect(await v.page.getByRole('button', { name: 'OK', exact: true }).evaluate((el) => !!el.closest('form'))).toBe(false) + await input.fill('From footer') + await v.page.getByRole('button', { name: 'OK', exact: true }).click() + console.info('external footer submit events', JSON.stringify(await v.events('submit'))) + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'From footer' }]) + expect(await v.events('close')).toHaveLength(1) + await input.fill('From form') + await input.press('Enter') + console.info('footer then Enter submit events', JSON.stringify(await v.events('submit'))) + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'From footer' }, { type: 'submit', value: 'From form' }]) + expect(await v.events('close')).toHaveLength(2) + expect(v.errors).toEqual([]) +}) + +test('the built-in prompt submits once per primary click or Enter', async () => { + const v = await viewer({ defaultDialog: true }, { page: 'ui.html', wait: false }) + const input = v.page.getByRole('dialog').locator('input') + await input.fill('Click') + await v.page.getByRole('button', { name: 'OK', exact: true }).click() + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'Click' }]) + await input.fill('Enter') + await input.press('Enter') + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'Click' }, { type: 'submit', value: 'Enter' }]) + expect(await v.events('close')).toHaveLength(2) + expect(v.errors).toEqual([]) +}) + +for (const placement of ['overflow', 'popover'] as const) { + test(`a React-portaled host Select in ${placement} survives mousedown and delivers onChange`, async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const title = placement === 'overflow' ? 'Overflow picker' : 'Popover picker' + const parent = placement === 'overflow' ? v.page.locator('[data-portal-overflow] .de-ebar-more') : v.page.locator('.de-tb-pop').last() + if (placement === 'overflow') await v.page.locator('[data-portal-overflow] .de-ebar-morewrap > button').click() + else await v.page.getByRole('button', { name: 'Open popover', exact: true }).click() + await v.page.getByRole('button', { name: title, exact: true }).click() + const option = v.page.getByRole('option', { name: 'Choose option' }) + await option.waitFor() + expect(await option.evaluate((el) => !!el.closest('.de-ebar-more, .de-tb-pop'))).toBe(false) + await option.click() + console.info(`${placement} portal after option click`, JSON.stringify({ parentVisible: await parent.isVisible(), events: await v.events('pick') })) + expect(await v.events('pick')).toEqual([{ type: 'pick', value: 'chosen', title }]) + expect(await parent.isVisible()).toBe(true) + await v.page.getByText('Outside with stopped propagation', { exact: true }).click() + await parent.waitFor({ state: 'detached', timeout: 5000 }) + expect(await parent.count()).toBe(0) + expect(v.errors).toEqual([]) + }) +} diff --git a/package.json b/package.json index bd00820..b0092fc 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,10 @@ "types": "./dist/types/embed.d.ts", "import": "./dist/embed.js" }, + "./locales/de": { + "types": "./dist/types/locales/de.d.ts", + "import": "./dist/locales/de.js" + }, "./worker": "./dist/office-engine.worker.js", "./embed.js": "./dist/office-engine.embed.js", "./collab": { diff --git a/src/collab/react.tsx b/src/collab/react.tsx index ffc37b7..bc869f5 100644 --- a/src/collab/react.tsx +++ b/src/collab/react.tsx @@ -6,6 +6,7 @@ import type { DocumentClient } from '../core/worker/client' import { getPeers, subscribePeers, type PeerView } from './hosts' import { startCollab, type Collab, type CollabOptions } from './index' import type { CollabStatus } from './session' +import { useStrings } from '../react/strings' const transportIds = new WeakMap() let nextTransportId = 0 @@ -66,16 +67,10 @@ const initials = (name: string) => .map((w) => w[0]!.toUpperCase()) .join('') || '?' -const LABEL: Record = { - connecting: 'Connecting…', - syncing: 'Syncing…', - live: 'Live', - offline: 'Offline · changes will sync', - error: 'Not synced', -} - /** status chip + collaborators' avatars (top bar) */ export function CollabBar({ client, state }: { client: DocumentClient; state: CollabState }) { + const t = useStrings() + const LABEL: Record = t.collab const peers = useSyncExternalStore( (fn) => subscribePeers(client, fn), () => getPeers(client), @@ -88,12 +83,12 @@ export function CollabBar({ client, state }: { client: DocumentClient; state: Co return () => clearInterval(t) }, [state.collab]) if (!state.status) return null - const title = state.status === 'error' ? state.error ?? 'Collaboration stopped' : state.status === 'live' && pending ? `Saving ${pending} change${pending > 1 ? 's' : ''}…` : LABEL[state.status] + const title = state.status === 'error' ? state.error ?? t.collab.stopped : state.status === 'live' && pending ? t.collab.saving(pending) : LABEL[state.status] return ( - {state.status === 'live' ? (peers.length ? `${peers.length + 1} editing` : 'Live') : LABEL[state.status]} + {state.status === 'live' ? (peers.length ? t.collab.editing(peers.length + 1) : LABEL.live) : LABEL[state.status]} {peers.length > 0 && ( diff --git a/src/embed.ts b/src/embed.ts index 925e128..73101f8 100644 --- a/src/embed.ts +++ b/src/embed.ts @@ -3,6 +3,7 @@ import { createRoot, type Root } from 'react-dom/client' import './core/default-worker' import { DocViewer, type DocViewerProps } from './react/DocViewer' import type { Icons } from './react/edit/Toolbar' +import type { StringsOverride } from './react/strings' export type MountOptions = Omit @@ -36,15 +37,17 @@ export function mount(el: HTMLElement, options: MountOptions): MountedViewer { * `` * Rendered inside a shadow root so host page CSS cannot leak in. * Attributes: src, name, editable, toolbar / thumbnails / save / download / file-menu / open / capture-select-all ("false" to turn off), - * theme ("light" | "dark" | "auto"); + * theme ("light" | "dark" | "auto"), locale (BCP 47 number/date formatting tag); other languages are supplied through `.strings`. * real-time collaboration: collab (hub WebSocket URL), room, user (display name), base (snapshot seq `src` was opened at). - * Properties: `file` (File/Blob/ArrayBuffer) for local data; `icons` (map or resolver, as DocViewer's `icons`). + * Properties: `file` (File/Blob/ArrayBuffer) for local data; `icons` (map or resolver, as DocViewer's `icons`); + * `strings` (texts replacing English or the enclosing provider's). */ export class OfficeViewerElement extends HTMLElement { - static observedAttributes = ['src', 'name', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments'] + static observedAttributes = ['src', 'name', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments', 'locale'] private viewer?: MountedViewer private _file?: Blob | ArrayBuffer private _icons?: Icons + private _strings?: StringsOverride // one function each for the element's life: a new one with every update would run the viewer's load effect again (a `load` event per update) private readonly onLoad: NonNullable = (client) => this.dispatchEvent(new CustomEvent('load', { detail: { kind: client.kind, name: client.name } })) private readonly onError: NonNullable = (error) => this.dispatchEvent(new CustomEvent('error', { detail: error })) @@ -65,6 +68,13 @@ export class OfficeViewerElement extends HTMLElement { this._icons = v this.sync() } + get strings() { + return this._strings + } + set strings(v: StringsOverride | undefined) { + this._strings = v + this.sync() + } connectedCallback() { if (this.viewer) return @@ -100,6 +110,8 @@ export class OfficeViewerElement extends HTMLElement { captureSelectAll: this.getAttribute('capture-select-all') !== 'false', theme: THEMES.find((t) => t === this.getAttribute('theme')), icons: this._icons, + locale: this.getAttribute('locale') ?? undefined, + strings: this._strings, collab: this.getAttribute('collab') && this.getAttribute('room') ? { diff --git a/src/index.ts b/src/index.ts index ec48d5b..84bc54b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,9 @@ export { useDocument, type DocumentState } from './react/useDocument' export { injectStyles, stylesText } from './react/injectStyles' export type { Zoom } from './react/common/ZoomControl' export { THEME_TOKENS, createTheme, themeStyle, useThemeRoot, type Theme, type ThemeMode, type ThemeOptions, type ThemeToken, type ThemeTokens } from './react/theme' -export { IconsProvider, ICON_NAMES, type IconName, type Icons } from './react/edit/Toolbar' +export { Icon, IconsProvider, ICON_NAMES, type DropOption, type IconName, type Icons } from './react/edit/Toolbar' +export { OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogAction, type DialogProps, type SelectProps, type ToastProps, type UIComponents } from './react/ui' +export { StringsProvider, useStrings, resolveStrings, en, type Strings, type StringsOverride, type Locale } from './react/strings' export { DocumentClient, setDefaultWorker, type OpenOptions } from './core/worker/client' export type { DocSource } from './core/source' diff --git a/src/locales/de.ts b/src/locales/de.ts new file mode 100644 index 0000000..97d0fa3 --- /dev/null +++ b/src/locales/de.ts @@ -0,0 +1,2 @@ +/** Optional German (Germany) UI texts. Import and pass as `strings` to opt in. */ +export { de } from '../react/strings/de' diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx index 59ca633..9982aec 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -7,13 +7,13 @@ import { ViewerContext, type FileOps, type ViewerApi } from './common/Slots' import { StatusContext } from './common/Status' import { ConfirmDialog, PromptDialog, Toast } from './common/Dialog' import { download, Icon, IconsProvider, type Icons } from './edit/Toolbar' +import { UIComponentsProvider, type UIComponents } from './ui' import { DetailsDialog } from './file/DetailsDialog' -import { FileMenu, KIND_LABEL, useFileActions, type FileMenuItem } from './file/FileMenu' +import { FileMenu, useFileActions, type FileMenuItem } from './file/FileMenu' import { importFile, type Imported } from './file/importFile' import { blankPptx, parasToDocx, rowsToXlsx } from '../core/convert' import type { DocKind } from '../core/opc' import { extOf, HAS_SOURCE, PLAIN_EXT, PLAIN_FILE, unpackedName, type PlainFormat } from '../core/plain' -import type { LegacyFormat } from '../core/legacy' import { injectStyles } from './injectStyles' import { isTextEntry, useSize } from './common/hooks' import { useThemeRoot, type Theme } from './theme' @@ -26,6 +26,7 @@ import type { CollabOptions } from '../collab' import { CollabBar, PeerOverlay, useCollab } from '../collab/react' import { CommentsContext, CommentsCtl, useCommentsState, type CommentOptions } from './comments/Comments' import { COMMENT_KEYS, CommentsPanel } from './comments/CommentsPanel' +import { formatBytes, StringsProvider, useStrings, type Locale, type StringsOverride } from './strings' export interface DocViewerProps { /** @@ -112,39 +113,21 @@ export interface DocViewerProps { * Each is rendered in `span.de-icon`, sized by font-size (1em). */ icons?: Icons + /** + * The host's own UI components (`Button`, `Select`, `Separator`, `Dialog`, `Toast`), rendered in the toolbars and + * dialogs instead of the built-in ones; each one left out keeps the built-in one. See docs/theming.md. + */ + components?: Partial + /** BCP 47 number/date formatting tag; defaults to the enclosing table or browser. Does not select UI texts. */ + locale?: Locale + /** Texts replacing the enclosing provider's or English texts, key by key (see `Strings`): a group may be given in part, e.g. `{ file: { menu: 'Datei' } }`. */ + strings?: StringsOverride } const EXT: Record = { docx: '.docx', xlsx: '.xlsx', pptx: '.pptx' } -const FROM_LABEL: Record<'pages' | 'keynote' | 'numbers' | 'visio', string> = { - pages: 'Apple Pages document', - keynote: 'Apple Keynote presentation', - numbers: 'Apple Numbers spreadsheet', - visio: 'Microsoft Visio drawing', -} -const CONVERTED_LABEL: Record = { - doc: 'Word 97-2003 document', - xls: 'Excel 97-2003 workbook', - ppt: 'PowerPoint 97-2003 presentation', - rtf: 'Rich Text Format document', - odt: 'OpenDocument text', - ods: 'OpenDocument spreadsheet', - odp: 'OpenDocument presentation', -} const IMPORTED_BADGE: Record = { csv: 'csv', tsv: 'tsv', text: 'txt', markdown: 'md', html: 'html', svg: 'svg', mermaid: 'mmd', plantuml: 'puml', graphviz: 'dot' } -const IMPORTED_LABEL: Record = { - csv: 'CSV file', - tsv: 'Tab-separated values', - text: 'Plain text', - markdown: 'Markdown', - html: 'HTML page', - svg: 'SVG picture', - mermaid: 'Mermaid diagram', - plantuml: 'PlantUML diagram', - graphviz: 'Graphviz diagram', -} /** plain formats saved back as themselves: Markdown and HTML built again from the document when it was edited, SVG from its text */ const SAVES_SOURCE = new Set(['markdown', 'html', 'svg']) -const UNTITLED: Record = { docx: 'Untitled document', xlsx: 'Untitled spreadsheet', pptx: 'Untitled presentation' } /** a key per opened client: a view is built again for each (the edited source's previews have one name) */ const clientIds = new WeakMap() @@ -155,13 +138,17 @@ const clientKey = (c: object) => { return id } -function fmtBytes(n: number) { - if (n < 1024) return `${n} B` - if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB` - return `${(n / 1024 / 1024).toFixed(1)} MB` +export function DocViewer(props: DocViewerProps) { + return ( + + + + ) } -export function DocViewer(props: DocViewerProps) { +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 root = useThemeRoot(theme, style) const { allowEdit = true, allowSave = true, allowDownload = true, fileMenu = true, allowOpen = true, captureSelectAll = true, onSave, onDirtyChange } = props @@ -290,6 +277,7 @@ export function DocViewer(props: DocViewerProps) { const cmOpts = props.comments || {} if (cmCtl) { cmCtl.opts = cmOpts + cmCtl.t = t cmCtl.me = cmOpts.user ?? props.collab?.user ?? { name: 'Me' } cmCtl.canComment = !readOnly && (cmOpts.canComment ?? (editing && canEdit)) } @@ -507,19 +495,19 @@ export function DocViewer(props: DocViewerProps) { canDownload: fileMenu && allowDownload && !!client, ops: fileOps, create: (kind: DocKind) => - replace(`A new ${UNTITLED[kind].split(' ')[1]} replaces the current document. Your changes are not saved.`, () => { + replace(t.bar.replaceNew(t.newWhat[kind]), () => { const blank = kind === 'docx' ? parasToDocx([]) : kind === 'xlsx' ? rowsToXlsx([], 'Sheet1') : blankPptx() - blank.then((src) => show({ src, name: UNTITLED[kind] + EXT[kind], converted: false }, allowEdit), (e: Error) => setToast(e.message)) + blank.then((src) => show({ src, name: t.untitled[kind] + EXT[kind], converted: false }, allowEdit), (e: Error) => setToast(e.message)) }), open: (file) => - replace(`Opening “${file.name}” replaces the current document. Your changes are not saved.`, () => { - importFile(file).then(show, (e: Error) => setToast(e.message)) + replace(t.bar.replaceOpen(file.name), () => { + importFile(file, t.file.unsupported).then(show, (e: Error) => setToast(e.message)) }), save, downloadOriginal: () => saveFile(true), picture: isPicture ? { - label: 'SVG picture', + label: t.file.picture, ext: '.svg', download: async () => download(new Blob([await sourceText()], { type: 'image/svg+xml' }), saveName), } @@ -564,7 +552,7 @@ export function DocViewer(props: DocViewerProps) { body = (
- Cannot open document. + {t.bar.cannotOpen}
{error.message}
@@ -573,10 +561,10 @@ export function DocViewer(props: DocViewerProps) { body = src || opened ? (
-
{progress?.phase === 'download' && progress.total ? `Downloading… ${fmtBytes(progress.loaded)} / ${fmtBytes(progress.total)}` : 'Opening…'}
+
{progress?.phase === 'download' && progress.total ? t.bar.downloading(fmtBytes(progress.loaded), fmtBytes(progress.total)) : t.bar.opening}
) : ( -
No document
+
{t.bar.noDocument}
) } else if (isPicture) body = else if (client.kind === 'docx') body = @@ -585,6 +573,7 @@ export function DocViewer(props: DocViewerProps) { return ( +
{toolbar && (
@@ -603,11 +592,11 @@ export function DocViewer(props: DocViewerProps) { className={'de-mode' + (codeShown ? ' de-mode-on' : '')} onClick={() => setCodeOpen((v) => !v)} aria-pressed={codeShown} - title={codeShown ? 'Hide the source' : 'Edit the source side by side with the document'} + title={codeShown ? t.bar.codeHide : t.bar.codeShow} data-testid="de-code-toggle" > - Code + {t.bar.code} )} {cmCtl && ( @@ -615,25 +604,25 @@ export function DocViewer(props: DocViewerProps) { type="button" className={'de-mode de-cm-toggle' + (cmState.open ? ' de-mode-on' : '')} onClick={() => cmCtl.toggle()} - title={cmCtl.canComment ? `Comments (${COMMENT_KEYS} to comment on the selection)` : 'Comments'} + title={cmCtl.canComment ? t.bar.commentsTitle(COMMENT_KEYS) : t.bar.comments} aria-pressed={cmState.open} data-testid="de-comments-toggle" > - Comments + {t.bar.comments} {cmCount > 0 && {cmCount}} )} {client && allowEdit && !readOnly && !codeShown && ( - )} {client && canSave && ((editing && !readOnly) || dirty) && ( - )}
@@ -655,13 +644,13 @@ export function DocViewer(props: DocViewerProps) { readOnly={!allowEdit || !!props.collab} notice={ dirty && !sourceEdited.current && !rebuilds - ? 'Changes made in the document are not in this source: editing it builds the document again from the source.' + ? t.bar.sourceStale : undefined } onCopy={() => navigator.clipboard?.writeText(code).then( - () => setToast('Source copied'), - () => setToast('Cannot copy here'), + () => setToast(t.bar.sourceCopied), + () => setToast(t.bar.cannotCopy), ) } onDownload={allowDownload ? () => download(new Blob([code], { type: PLAIN_FILE[srcFormat!].mime }), sourceName()) : undefined} @@ -674,7 +663,7 @@ export function DocViewer(props: DocViewerProps) { className="de-split-handle" role="separator" aria-orientation={stacked ? 'horizontal' : 'vertical'} - aria-label="Resize the source" + aria-label={t.bar.resizeSource} aria-valuenow={Math.round(split * 100)} aria-valuemin={15} aria-valuemax={85} @@ -699,14 +688,14 @@ export function DocViewer(props: DocViewerProps) { {cmCtl && cmState.open && }
{toast && } - {confirm && setConfirm(null)} />} + {confirm && setConfirm(null)} />} {renaming && client && ( { const next = v.trim().replace(/[\\/:*?"<>|]+/g, ' ').replace(new RegExp(`(\\${officeExt}|\\${saveExt})$`, 'i'), '') if (!next) return @@ -721,25 +710,26 @@ export function DocViewer(props: DocViewerProps) { 0 ? [['File size', fmtBytes(client.size)] as [string, string]] : []), - ...(dirty ? [['Status', 'Unsaved changes'] as [string, string]] : []), + ...(client.size > 0 ? [[t.details.fileSize, fmtBytes(client.size)] as [string, string]] : []), + ...(dirty ? [[t.details.status, t.details.unsaved] as [string, string]] : []), ]} stats={fileOps.current?.stats() ?? []} onClose={() => setDetails(false)} /> )}
+ ) } diff --git a/src/react/comments/Comments.ts b/src/react/comments/Comments.ts index 060c64c..e76f696 100644 --- a/src/react/comments/Comments.ts +++ b/src/react/comments/Comments.ts @@ -7,6 +7,7 @@ import { createContext, useContext, useSyncExternalStore } from 'react' import { initialsOf, nowIso, newCommentId, threadsOf, type CommentAnchor, type CommentThread, type CommentUser, type DocComment } from '../../core/comments' import type { DocKind } from '../../core/opc' import type { DocumentClient } from '../../core/worker/client' +import { en, type Strings } from '../strings/en' export interface CommentOptions { /** who writes the comments made here (default: the collaboration user, else "Me") */ @@ -66,7 +67,7 @@ export interface CommentHost { /** shows thread `id`'s place */ reveal(id: string): void /** what to do to comment, when `pending()` finds nothing */ - hint: string + hint: () => string } export interface CommentsState { @@ -87,6 +88,15 @@ export class CommentsCtl { host: CommentHost | null = null opts: CommentOptions = {} me: CommentUser = { name: 'Me' } + /** texts of the notices */ + private texts: Strings = en + get t(): Strings { return this.texts } + set t(value: Strings) { + if (value === this.texts) return + this.texts = value + // Quotes may contain translated locations; keep the host (and its navigation sequence) intact. + this.placedCache = null + } canComment = false loaded = false private subs = new Set<() => void>() @@ -187,7 +197,7 @@ export class CommentsCtl { if (!this.canComment || !this.host) return false const draft = at ?? this.host.pending() if (!draft) { - this.set({ open: true, draft: null, notice: this.host.hint }) + this.set({ open: true, draft: null, notice: this.host.hint() }) return false } if (draft.existing) { @@ -222,7 +232,7 @@ export class CommentsCtl { await this.client.call('comments.set', id, c) return true } catch (e) { - this.set({ notice: `Couldn't save the comment: ${(e as Error).message}` }) + this.set({ notice: this.t.comments.saveFailed((e as Error).message) }) return false } } @@ -263,7 +273,7 @@ export class CommentsCtl { const mine = () => (this.state.draft === draft ? { draft: null } : {}) if (host.attach && !(await host.attach(id, draft))) { await this.write(id, null) - this.set({ ...mine(), notice: 'The commented text is no longer there' }) + this.set({ ...mine(), notice: this.t.comments.textGone }) return false } this.set(this.state.draft === draft ? { draft: null, active: id } : {}) diff --git a/src/react/comments/CommentsPanel.tsx b/src/react/comments/CommentsPanel.tsx index 28f4238..a0fc37c 100644 --- a/src/react/comments/CommentsPanel.tsx +++ b/src/react/comments/CommentsPanel.tsx @@ -5,6 +5,7 @@ import { ContextMenu, MOD, type MenuItem } from '../common/ContextMenu' import { ConfirmDialog } from '../common/Dialog' import { Icon } from '../edit/Toolbar' import { useCommentsState, type CommentsCtl, type PlacedThread } from './Comments' +import { useStrings, type Strings } from '../strings' const ALT = MOD === '⌘' ? '⌥' : 'Alt+' /** shortcut that starts a comment on the selection */ @@ -17,16 +18,16 @@ function colorOf(u: CommentUser): string { return PEER_COLORS[h % PEER_COLORS.length] } -function ago(iso: string, now: number): string { +function ago(iso: string, now: number, str: Strings): string { const t = Date.parse(iso) if (!Number.isFinite(t)) return '' const s = Math.max(0, (now - t) / 1000) - if (s < 45) return 'just now' - if (s < 3600) return `${Math.round(s / 60)} min ago` - if (s < 86400) return `${Math.round(s / 3600)} h ago` - if (s < 7 * 86400) return `${Math.round(s / 86400)} d ago` + if (s < 45) return str.comments.justNow + if (s < 3600) return str.comments.minutesAgo(Math.round(s / 60)) + if (s < 86400) return str.comments.hoursAgo(Math.round(s / 3600)) + if (s < 7 * 86400) return str.comments.daysAgo(Math.round(s / 86400)) const d = new Date(t) - return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', ...(d.getFullYear() !== new Date(now).getFullYear() ? { year: 'numeric' } : {}) }) + return d.toLocaleDateString(str.locale, { month: 'short', day: 'numeric', ...(d.getFullYear() !== new Date(now).getFullYear() ? { year: 'numeric' } : {}) }) } /** comment text with its mentions set apart */ @@ -80,6 +81,7 @@ export function Composer(props: { onCancel?: () => void }) { const { ctl } = props + const str = useStrings() const [text, setText] = useState(props.initial ?? '') const [mentions, setMentions] = useState(props.mentions ?? []) const [pop, setPop] = useState<{ at: number; end: number; list: CommentUser[]; hi: number } | null>(null) @@ -204,10 +206,10 @@ export function Composer(props: {
)}
- {canMention && @ to mention} + {canMention && {str.comments.mentionTip}} {props.onCancel && ( )} )} -
{ctl.canComment && !st.draft && ( - )} {st.notice && (
{st.notice} -
@@ -395,7 +401,7 @@ export function CommentsPanel({ ctl }: { ctl: CommentsCtl }) { {ctl.me.name}
- ctl.post(t, m)} onCancel={() => ctl.cancelDraft()} /> + ctl.post(t, m)} onCancel={() => ctl.cancelDraft()} /> )} {shown.map((t) => ( @@ -403,16 +409,16 @@ export function CommentsPanel({ ctl }: { ctl: CommentsCtl }) { ))} {!shown.length && !st.draft && (
- {all.length ? 'Every comment is resolved.' : ctl.canComment ? `No comments yet. ${ctl.host?.hint ?? ''}` : 'No comments.'} + {all.length ? str.comments.allResolved : ctl.canComment ? str.comments.noneYet(ctl.host?.hint() ?? '') : str.comments.none}
)} {menu && setMenu(null)} />} {confirm && ( void ctl.remove(confirm.id)} onClose={() => setConfirm(null)} /> diff --git a/src/react/common/Dialog.tsx b/src/react/common/Dialog.tsx index 74678b7..0ca8de9 100644 --- a/src/react/common/Dialog.tsx +++ b/src/react/common/Dialog.tsx @@ -1,4 +1,6 @@ -import { useEffect, useRef, useState, type ReactNode } from 'react' +import { useCallback, useEffect, useState, type ReactNode } from 'react' +import { useStrings } from '../strings' +import { DefaultDialog, DefaultToast, useHostUI, type DialogAction } from '../ui' export interface PromptSpec { title: string @@ -16,10 +18,10 @@ export interface PromptSpec { /** Small modal prompt (no window.prompt: works in sandboxed / embedded pages). */ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () => void }) { + const t = useStrings() + const Dialog = useHostUI().Dialog ?? DefaultDialog const [v, setV] = useState(spec.initial ?? '') - const ref = useRef(null) - useEffect(() => { - const el = ref.current + const ref = useCallback((el: HTMLInputElement | HTMLTextAreaElement | null) => { el?.focus() el?.select() }, []) @@ -27,107 +29,64 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () onClose() spec.onOk(v) } + const actions: DialogAction[] = [ + ...(spec.extra + ? [ + { + label: spec.extra.label, + extra: true, + onClick: () => { + onClose() + spec.extra!.run() + }, + }, + ] + : []), + { label: t.common.cancel, onClick: onClose }, + { label: spec.ok ?? t.common.ok, primary: true, submit: true, onClick: done }, + ] return ( -
e.target === e.currentTarget && onClose()} - onKeyDown={(e) => { - if (e.key === 'Escape') { - e.stopPropagation() - onClose() - } - }} - > -
{ - e.preventDefault() - done() - }} - > -
{spec.title}
- {spec.label && } - {spec.area ? ( -