From 1c0faf07f6747a41c07e2031c7d77d78acefe503 Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 14 Nov 2026 11:08:48 +0100 Subject: [PATCH 01/19] feat(viewer): translatable UI texts: strings table, locale and strings props The viewer's texts come from one typed table, `Strings` (src/react/strings/en.ts), with a complete German table next to it (de.ts, Swiss spelling, Word / Excel / PowerPoint terms). `DocViewer`, `mount()` and `` take `locale` ('en' | 'de', default 'en') and `strings`, a partial table merged over the locale key by key; `StringsProvider` / `useStrings()` give standalone views the same texts. Numbers and dates in the UI go through Intl with the table's locale; the English output is unchanged. This change converts the top bar, the details rows, the common dialogs, the zoom control, the shared toolbar controls, the source pane and the picture view. The shared groups (`edit`, `find`, `table`, `format`) are in the table already, so the document, sheet and slide views can be converted in separate changes. A unit test checks that every locale has all keys of `en`, no empty text and no sharp s in German. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + docs/api.md | 45 ++++- e2e/app/main.tsx | 3 + src/embed.ts | 19 ++- src/index.ts | 1 + src/react/DocViewer.tsx | 106 +++++------- src/react/common/Dialog.tsx | 9 +- src/react/common/ZoomControl.tsx | 12 +- src/react/edit/Toolbar.tsx | 21 ++- src/react/picture/PictureView.tsx | 8 +- src/react/source/SourceEditor.tsx | 12 +- src/react/strings/de.ts | 256 ++++++++++++++++++++++++++++ src/react/strings/en.ts | 267 ++++++++++++++++++++++++++++++ src/react/strings/index.tsx | 66 ++++++++ test/strings.test.ts | 63 +++++++ 15 files changed, 801 insertions(+), 88 deletions(-) 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.test.ts diff --git a/README.md b/README.md index 45ca7a7..c11adba 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,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; English by default, German shipped (`locale="de"`), any text replaceable through `strings` - **Embed anywhere**: React component, hook, vanilla `mount()`, `` web component, single ` ``` -``: 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="de"`, `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/main.tsx b/e2e/app/main.tsx index be08f97..e1b6a41 100644 --- a/e2e/app/main.tsx +++ b/e2e/app/main.tsx @@ -3,6 +3,7 @@ * ?src=samples/sample.docx&editable=1&allowSave=0&onSave=1&items=1&close=1&collab=ws://…&room=r * comments: &me=Ann&meId=u1 (author), &people=1 (mentions: Ann, Bob Stone, Cid), &comments=0 (hidden), &cmOpen=1 * &icons=1: every icon from a host resolver, as `` + * texts: &locale=de, &fileLabel=… (a partial `strings` override of the File menu's label) */ import { useState } from 'react' import { createRoot } from 'react-dom/client' @@ -48,6 +49,8 @@ const initial: DocViewerProps = { captureSelectAll: flag('captureSelectAll'), theme: (q.get('theme') as DocViewerProps['theme']) ?? undefined, injectStyles: flag('injectStyles'), + locale: (q.get('locale') as DocViewerProps['locale']) ?? undefined, + strings: q.has('fileLabel') ? { file: { menu: q.get('fileLabel')! } } : undefined, onSave: q.has('onSave') ? async (blob, name) => void log({ type: 'save', name, b64: await b64(blob) }) : undefined, onDirtyChange: (dirty) => log({ type: 'dirty', dirty }), onRename: (name) => log({ type: 'rename', name }), diff --git a/src/embed.ts b/src/embed.ts index 81318e0..afab05b 100644 --- a/src/embed.ts +++ b/src/embed.ts @@ -3,10 +3,12 @@ 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 const THEMES = ['light', 'dark', 'auto'] as const +const LOCALE_NAMES = ['en', 'de'] as const export interface MountedViewer { update(next: Partial): void @@ -36,15 +38,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 ("en" | "de"); * 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 the locale'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 get file() { return this._file @@ -61,6 +65,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 @@ -96,6 +107,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: LOCALE_NAMES.find((l) => l === this.getAttribute('locale')), + strings: this._strings, collab: this.getAttribute('collab') && this.getAttribute('room') ? { diff --git a/src/index.ts b/src/index.ts index 9d018d0..e90e0e8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ 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 { StringsProvider, useStrings, resolveStrings, LOCALES, en, de, 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/react/DocViewer.tsx b/src/react/DocViewer.tsx index 8d1f37c..3ec9030 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -8,12 +8,11 @@ import { StatusContext } from './common/Status' import { ConfirmDialog, PromptDialog, Toast } from './common/Dialog' import { download, Icon, IconsProvider, type Icons } from './edit/Toolbar' 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 +25,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 { /** @@ -111,38 +111,20 @@ export interface DocViewerProps { * Each is rendered in `span.de-icon`, sized by font-size (1em). */ icons?: Icons + /** Language of the viewer's texts (bars, menus, dialogs, messages): 'en' or 'de'. Default 'en'. */ + locale?: Locale + /** Texts replacing the locale's, 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', string> = { pages: 'Apple Pages document', keynote: 'Apple Keynote presentation', numbers: 'Apple Numbers spreadsheet' } -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 savesSource = (name: string) => { const f = PLAIN_EXT[extOf(unpackedName(name) ?? name)] return !!f && SAVES_SOURCE.has(f) } -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() @@ -153,13 +135,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 @@ -465,12 +451,12 @@ 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.`, () => { + replace(t.bar.replaceOpen(file.name), () => { importFile(file).then(show, (e: Error) => setToast(e.message)) }), save, @@ -482,7 +468,7 @@ export function DocViewer(props: DocViewerProps) { }, picture: isPicture ? { - label: 'SVG picture', + label: t.file.picture, ext: '.svg', download: async () => download(new Blob([await sourceText()], { type: 'image/svg+xml' }), saveName), } @@ -527,7 +513,7 @@ export function DocViewer(props: DocViewerProps) { body = (
- Cannot open document. + {t.bar.cannotOpen}
{error.message}
@@ -536,10 +522,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 = @@ -566,11 +552,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 && ( @@ -578,25 +564,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) && ( - )}
@@ -618,13 +604,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} @@ -637,7 +623,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} @@ -662,14 +648,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(`(\\${EXT[client.kind]}|\\${saveExt})$`, 'i'), '') if (!next) return @@ -684,19 +670,19 @@ 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/common/Dialog.tsx b/src/react/common/Dialog.tsx index 74678b7..6489f77 100644 --- a/src/react/common/Dialog.tsx +++ b/src/react/common/Dialog.tsx @@ -1,4 +1,5 @@ import { useEffect, useRef, useState, type ReactNode } from 'react' +import { useStrings } from '../strings' export interface PromptSpec { title: string @@ -16,6 +17,7 @@ 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 [v, setV] = useState(spec.initial ?? '') const ref = useRef(null) useEffect(() => { @@ -69,10 +71,10 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () )}
@@ -82,6 +84,7 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () /** Yes / no question (no window.confirm: works in sandboxed / embedded pages). */ export function ConfirmDialog(props: { title: string; message: ReactNode; ok: string; onOk: () => void; onClose: () => void }) { + const t = useStrings() const okRef = useRef(null) useEffect(() => okRef.current?.focus(), []) return ( @@ -100,7 +103,7 @@ export function ConfirmDialog(props: { title: string; message: ReactNode; ok: st
{props.message}
- onChange(zoom === 'fit' ? 1 : 'fit')}> - {zoom === 'fit' ? 'Fit' : `${Math.round(effective * 100)}%`} + onChange(zoom === 'fit' ? 1 : 'fit')}> + {zoom === 'fit' ? t.zoom.fit : formatNumber(t, effective, { style: 'percent' })} -
diff --git a/src/react/edit/Toolbar.tsx b/src/react/edit/Toolbar.tsx index 55240ec..bd17e3e 100644 --- a/src/react/edit/Toolbar.tsx +++ b/src/react/edit/Toolbar.tsx @@ -16,6 +16,7 @@ import { type RefObject, } from 'react' import { cssColor } from '../../core/color' +import { useStrings } from '../strings' const BORDER_GRID = @@ -471,10 +472,11 @@ export function SizeBox(props: { value?: number; placeholder?: number; sizes?: n if (text !== null) set(parseFloat(text)) inputRef.current?.blur() } - const title = props.title ?? 'Font size' + const t = useStrings() + const title = props.title ?? t.toolbar.fontSize return ( - - {open && ( @@ -551,6 +553,7 @@ const signature = (el: ReactElement) => { * Item widths are measured once per set of items and cached for resizes. */ export function ToolbarRow({ children }: { children: ReactNode }) { + const t = useStrings() const items = flatten(children) const sig = items.map(signature).join('|') const rowRef = useRef(null) @@ -614,7 +617,7 @@ export function ToolbarRow({ children }: { children: ReactNode }) { ))} {rest.length > 0 && ( - {more && ( @@ -685,6 +688,7 @@ export function ColorBtn(props: { icon: IconName; title: string; value?: string; const onPick = useRef(props.onPick) onPick.current = props.onPick const cur = props.value?.toLowerCase() + const t = useStrings() // native 'change' fires once the OS picker is confirmed (React's onChange would fire while dragging) useEffect(() => { @@ -725,13 +729,13 @@ export function ColorBtn(props: { icon: IconName; title: string; value?: string; {open && (
{(props.palette ?? PALETTE).map(swatch)}
-
Custom
+
{t.toolbar.custom}
{custom.map(swatch)} -
@@ -805,6 +809,7 @@ export function Pop(props: { icon: IconName; title: string; children: (close: () /** rows × cols picker for new tables */ export function GridPicker({ onPick }: { onPick: (r: number, c: number) => void }) { const [hover, setHover] = useState<[number, number]>([0, 0]) + const t = useStrings() return (
setHover([0, 0])}> @@ -814,7 +819,7 @@ export function GridPicker({ onPick }: { onPick: (r: number, c: number) => void return
-
{hover[0] ? `${hover[0]} × ${hover[1]}` : 'Table size'}
+
{hover[0] ? `${hover[0]} × ${hover[1]}` : t.toolbar.tableSize}
) } diff --git a/src/react/picture/PictureView.tsx b/src/react/picture/PictureView.tsx index e963819..4b05eb0 100644 --- a/src/react/picture/PictureView.tsx +++ b/src/react/picture/PictureView.tsx @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react' import { svgImage } from '../../core/svgfile' import type { DocumentClient } from '../../core/worker/client' import { useFileOps } from '../common/Slots' +import { formatNumber, useStrings } from '../strings' type Pic = { url: string; w: number; h: number; alt: string } | { error: string } @@ -10,6 +11,7 @@ type Pic = { url: string; w: number; h: number; alt: string } | { error: string * Drawn from the file's text (the Code pane edits it); the document built from it is what Download as Word gives. */ export function PictureView({ client }: { client: DocumentClient }) { + const t = useStrings() const [pic, setPic] = useState(null) useEffect(() => { let live = true @@ -37,11 +39,11 @@ export function PictureView({ client }: { client: DocumentClient }) { const shown = pic && 'url' in pic ? pic : null useFileOps({ printable: async () => { - if (!shown) throw new Error('The picture is not shown') + if (!shown) throw new Error(t.picture.notShown) return { size: 'auto', margin: '1cm', node: {shown.alt} } }, text: async () => ((await client.call('plain.source')) as string | null) ?? '', - stats: () => (shown ? [['Picture size', `${Math.round(shown.w)} × ${Math.round(shown.h)} px`]] : []), + stats: () => (shown ? [[t.picture.size, `${formatNumber(t, Math.round(shown.w))} × ${formatNumber(t, Math.round(shown.h))} px`]] : []), }) if (!pic) return ( @@ -53,7 +55,7 @@ export function PictureView({ client }: { client: DocumentClient }) { return (
- SVG picture not drawn. + {t.picture.notDrawn}
{pic.error}
diff --git a/src/react/source/SourceEditor.tsx b/src/react/source/SourceEditor.tsx index c28d72c..a58f492 100644 --- a/src/react/source/SourceEditor.tsx +++ b/src/react/source/SourceEditor.tsx @@ -2,6 +2,7 @@ import { useMemo, useRef, type KeyboardEvent } from 'react' import type { PlainFormat } from '../../core/plain' import { Icon } from '../edit/Toolbar' import { highlight } from './highlight' +import { useStrings } from '../strings' const LABEL: Partial> = { markdown: 'Markdown', html: 'HTML', svg: 'SVG', mermaid: 'Mermaid', plantuml: 'PlantUML', graphviz: 'Graphviz' } @@ -21,6 +22,7 @@ export interface SourceEditorProps { * textarea over the colored text, both sized by their content in one grid cell (they scroll together). */ export function SourceEditor({ text, format, onChange, readOnly, notice, onCopy, onDownload }: SourceEditorProps) { + const t = useStrings() const tokens = useMemo(() => highlight(format, text), [format, text]) const lines = useMemo(() => { let n = 1 @@ -63,19 +65,19 @@ export function SourceEditor({ text, format, onChange, readOnly, notice, onCopy,
- {LABEL[format] ?? 'Source'} + {LABEL[format] ?? t.source.source} - {lines} {lines === 1 ? 'line' : 'lines'} + {lines} {t.source.lines(lines)} {onCopy && ( - )} {onDownload && ( - )} @@ -103,7 +105,7 @@ export function SourceEditor({ text, format, onChange, readOnly, notice, onCopy, wrap="off" rows={1} cols={1} - aria-label={`${LABEL[format] ?? 'Source'} source`} + aria-label={t.source.input(LABEL[format] ?? t.source.source)} data-testid="de-source-input" />
diff --git a/src/react/strings/de.ts b/src/react/strings/de.ts new file mode 100644 index 0000000..ac7232e --- /dev/null +++ b/src/react/strings/de.ts @@ -0,0 +1,256 @@ +import type { Strings } from './en' + +/** German UI texts (Swiss spelling: ss, never the sharp s; terms as in the German Word / Excel / PowerPoint). */ +export const de: Strings = { + locale: 'de-CH', + + common: { + ok: 'OK', + cancel: 'Abbrechen', + close: 'Schliessen', + save: 'Speichern', + delete: 'Löschen', + edit: 'Bearbeiten', + none: 'Keine', + apply: 'Übernehmen', + remove: 'Entfernen', + error: (message: string) => `Fehler: ${message}`, + stillLoading: 'Das Dokument wird noch geladen. Bitte gleich nochmals versuchen.', + }, + + bar: { + cannotOpen: 'Das Dokument kann nicht geöffnet werden.', + downloading: (loaded: string, total: string) => `Herunterladen… ${loaded} / ${total}`, + opening: 'Öffnen…', + noDocument: 'Kein Dokument', + code: 'Code', + codeHide: 'Quelltext ausblenden', + codeShow: 'Quelltext neben dem Dokument bearbeiten', + comments: 'Kommentare', + commentsTitle: (keys: string) => `Kommentare (${keys} kommentiert die Auswahl)`, + view: 'Ansicht', + edit: 'Bearbeiten', + toView: 'Zur Ansicht wechseln', + toEdit: 'Dokument bearbeiten', + saveTitle: 'Kopie speichern (Ctrl+S)', + saving: 'Speichern…', + save: 'Speichern', + download: 'Herunterladen', + sourceStale: 'Änderungen im Dokument sind nicht in diesem Quelltext: Wird er bearbeitet, entsteht das Dokument neu aus dem Quelltext.', + sourceCopied: 'Quelltext kopiert', + cannotCopy: 'Kopieren ist hier nicht möglich', + resizeSource: 'Grösse des Quelltexts ändern', + discardTitle: 'Nicht gespeicherte Änderungen verwerfen?', + discardOk: 'Weiter', + replaceNew: (what: string) => `${what} ersetzt das aktuelle Dokument. Die Änderungen sind nicht gespeichert.`, + replaceOpen: (name: string) => `„${name}“ ersetzt das aktuelle Dokument. Die Änderungen sind nicht gespeichert.`, + renameTitle: 'Umbenennen', + renameLabel: 'Dateiname', + renameOk: 'Umbenennen', + }, + + untitled: { docx: 'Unbenanntes Dokument', xlsx: 'Unbenannte Tabelle', pptx: 'Unbenannte Präsentation' }, + newWhat: { docx: 'Ein neues Dokument', xlsx: 'Eine neue Tabelle', pptx: 'Eine neue Präsentation' }, + + kind: { docx: 'Word-Dokument', xlsx: 'Excel-Arbeitsmappe', pptx: 'PowerPoint-Präsentation' }, + from: { pages: 'Apple-Pages-Dokument', keynote: 'Apple-Keynote-Präsentation', numbers: 'Apple-Numbers-Tabelle' }, + converted: { + doc: 'Word-97-2003-Dokument', + xls: 'Excel-97-2003-Arbeitsmappe', + ppt: 'PowerPoint-97-2003-Präsentation', + rtf: 'Rich-Text-Format-Dokument', + odt: 'OpenDocument-Text', + ods: 'OpenDocument-Tabelle', + odp: 'OpenDocument-Präsentation', + }, + imported: { + csv: 'CSV-Datei', + tsv: 'Tabulatorgetrennte Werte', + text: 'Nur-Text', + markdown: 'Markdown', + html: 'HTML-Seite', + svg: 'SVG-Bild', + mermaid: 'Mermaid-Diagramm', + plantuml: 'PlantUML-Diagramm', + graphviz: 'Graphviz-Diagramm', + }, + + details: { + title: 'Dokumenteigenschaften', + name: 'Name', + type: 'Typ', + viewOnly: (what: string) => `${what} (nur Ansicht)`, + openedAs: (what: string, kind: string) => `${what}, geöffnet als ${kind}`, + fileSize: 'Dateigrösse', + status: 'Status', + unsaved: 'Nicht gespeicherte Änderungen', + core: { + title: 'Titel', + subject: 'Thema', + creator: 'Autor', + keywords: 'Stichwörter', + description: 'Kommentare', + lastModifiedBy: 'Zuletzt geändert von', + created: 'Erstellt', + modified: 'Geändert', + }, + }, + + file: { + menu: 'Datei', + new: 'Neu', + newDocx: 'Dokument', + newXlsx: 'Tabelle', + newPptx: 'Präsentation', + open: 'Öffnen…', + importCsv: 'CSV in neues Blatt importieren…', + save: 'Speichern', + rename: 'Umbenennen…', + downloadAs: 'Herunterladen als', + pdf: 'PDF-Dokument', + html: 'Webseite', + txt: 'Nur-Text', + md: 'Markdown', + csv: 'CSV (aktuelles Blatt)', + tsv: 'TSV (aktuelles Blatt)', + picture: 'SVG-Bild', + details: 'Dokumenteigenschaften', + print: 'Drucken', + close: 'Schliessen', + preparingPdf: 'PDF wird vorbereitet… im Druckdialog „Als PDF speichern“ wählen', + preparing: 'Wird vorbereitet…', + unsupported: (name: string) => + `„${name}“ kann nicht geöffnet werden: unterstützt werden Word, Excel, PowerPoint (auch 97-2003), OpenDocument, RTF, Pages, Keynote, Numbers, CSV, Text, Markdown, HTML, SVG, Mermaid, PlantUML und Graphviz (auch gzip-komprimiert: .svgz, .csv.gz)`, + }, + + zoom: { + group: 'Zoom', + out: 'Verkleinern', + in: 'Vergrössern', + fit: 'Breite', + fitTitle: 'An Breite angepasst (Klick für 100%)', + toFit: 'Klicken, um an die Breite anzupassen', + }, + + toolbar: { + fontSize: 'Schriftgrad', + fontSizeDown: 'Schriftgrad verkleinern', + fontSizeUp: 'Schriftgrad vergrössern', + more: 'Mehr', + moreTools: 'Weitere Werkzeuge', + custom: 'Benutzerdefiniert', + customColor: 'Benutzerdefinierte Farbe', + customColorTitle: 'Benutzerdefinierte Farbe…', + tableSize: 'Tabellengrösse', + }, + + edit: { + undo: 'Rückgängig', + redo: 'Wiederholen', + bold: 'Fett', + italic: 'Kursiv', + underline: 'Unterstrichen', + strike: 'Durchgestrichen', + textColor: 'Schriftfarbe', + highlight: 'Texthervorhebungsfarbe', + automatic: 'Automatisch', + font: 'Schriftart', + alignLeft: 'Linksbündig', + center: 'Zentriert', + alignRight: 'Rechtsbündig', + justify: 'Blocksatz', + bullets: 'Aufzählungszeichen', + numbers: 'Nummerierung', + indentLess: 'Einzug verkleinern', + indentMore: 'Einzug vergrössern', + sup: 'Hochgestellt', + sub: 'Tiefgestellt', + clearFormat: 'Formatierung löschen', + link: 'Link einfügen', + editLink: 'Link bearbeiten', + linkPlaceholder: 'https://…', + openLink: 'Link öffnen', + editLinkMenu: 'Link bearbeiten…', + insertLinkMenu: 'Link einfügen…', + removeLink: 'Link entfernen', + image: 'Bild einfügen', + imageMenu: 'Bild einfügen…', + altText: 'Alternativtext', + altTextMenu: 'Alternativtext…', + altLabel: 'Bild für Bildschirmleseprogramme beschreiben', + cut: 'Ausschneiden', + copy: 'Kopieren', + paste: 'Einfügen', + pastePlain: 'Ohne Formatierung einfügen', + selectAll: 'Alles auswählen', + clipboardBlocked: (keys: string) => `Der Browser hat den Zugriff auf die Zwischenablage blockiert. Zum Einfügen ${keys} verwenden.`, + useKeys: (keys: string) => `${keys} verwenden`, + comment: 'Kommentar', + showComment: 'Kommentar anzeigen', + delKey: 'Entf', + findReplace: 'Suchen und Ersetzen', + keyed: (label: string, keys: string) => `${label} (${keys})`, + }, + + find: { + placeholder: 'Im Dokument suchen', + label: 'Suchen', + prev: 'Vorheriges (Umschalt+Eingabe)', + next: 'Nächstes (Eingabe)', + replace: 'Ersetzen', + replaceWith: 'Ersetzen durch', + replaceAll: 'Alle', + close: 'Schliessen (Esc)', + }, + + table: { + menu: 'Tabelle', + rowAbove: 'Zeile oberhalb einfügen', + rowBelow: 'Zeile unterhalb einfügen', + colLeft: 'Spalte links einfügen', + colRight: 'Spalte rechts einfügen', + delRow: 'Zeile löschen', + delCol: 'Spalte löschen', + delTable: 'Tabelle löschen', + distribute: 'Spalten gleichmässig verteilen', + merge: 'Zellen verbinden', + unmerge: 'Zellen teilen', + insert: 'Tabelle einfügen', + }, + + format: { + noFill: 'Keine Füllung', + borderColor: 'Rahmenfarbe', + black: 'Schwarz', + borderStyle: 'Linienart', + borders: { + all: 'Alle Rahmenlinien', + inner: 'Rahmenlinien innen', + outer: 'Rahmenlinien aussen', + none: 'Kein Rahmen', + top: 'Rahmenlinie oben', + bottom: 'Rahmenlinie unten', + left: 'Rahmenlinie links', + right: 'Rahmenlinie rechts', + }, + lines: { thin: 'Dünn', medium: 'Mittel', thick: 'Dick', dashed: 'Gestrichelt', dotted: 'Gepunktet', double: 'Doppelt' }, + vAlign: 'Vertikale Ausrichtung', + vAligns: { top: 'Oben', middle: 'Mitte', bottom: 'Unten' }, + spacings: { single: 'Einfach', double: 'Doppelt', triple: 'Dreifach' }, + inches: (w: string, h: string) => `${w} × ${h} Zoll`, + }, + + source: { + source: 'Quelltext', + lines: (n: number) => (n === 1 ? 'Zeile' : 'Zeilen'), + copy: 'Quelltext kopieren', + download: 'Quelltext herunterladen', + input: (format: string) => `${format}-Quelltext`, + }, + + picture: { + notShown: 'Das Bild wird nicht angezeigt', + size: 'Bildgrösse', + notDrawn: 'Das SVG-Bild konnte nicht dargestellt werden.', + }, +} diff --git a/src/react/strings/en.ts b/src/react/strings/en.ts new file mode 100644 index 0000000..7bbc6f5 --- /dev/null +++ b/src/react/strings/en.ts @@ -0,0 +1,267 @@ +/** + * The viewer's UI texts in English (the default locale). Every other locale has the same keys (`Strings`); + * values are plain strings, or functions where a text takes numbers or names. + */ +export const en = { + /** BCP 47 tag used for numbers and dates (Intl) */ + locale: 'en-US', + + common: { + ok: 'OK', + cancel: 'Cancel', + close: 'Close', + save: 'Save', + delete: 'Delete', + edit: 'Edit', + none: 'None', + apply: 'Apply', + remove: 'Remove', + error: (message: string) => `Error: ${message}`, + stillLoading: 'The document is still loading — try again in a moment', + }, + + bar: { + cannotOpen: 'Cannot open document.', + downloading: (loaded: string, total: string) => `Downloading… ${loaded} / ${total}`, + opening: 'Opening…', + noDocument: 'No document', + code: 'Code', + codeHide: 'Hide the source', + codeShow: 'Edit the source side by side with the document', + comments: 'Comments', + commentsTitle: (keys: string) => `Comments (${keys} to comment on the selection)`, + view: 'View', + edit: 'Edit', + toView: 'Switch to viewing', + toEdit: 'Edit document', + saveTitle: 'Save a copy (Ctrl+S)', + saving: 'Saving…', + save: 'Save', + download: 'Download', + sourceStale: 'Changes made in the document are not in this source: editing it builds the document again from the source.', + sourceCopied: 'Source copied', + cannotCopy: 'Cannot copy here', + resizeSource: 'Resize the source', + discardTitle: 'Discard unsaved changes?', + discardOk: 'Continue', + replaceNew: (what: string) => `A new ${what} replaces the current document. Your changes are not saved.`, + replaceOpen: (name: string) => `Opening “${name}” replaces the current document. Your changes are not saved.`, + renameTitle: 'Rename', + renameLabel: 'File name', + renameOk: 'Rename', + }, + + /** file names of new documents (the extension is added) */ + untitled: { docx: 'Untitled document', xlsx: 'Untitled spreadsheet', pptx: 'Untitled presentation' }, + /** what File → New makes: the subject of `bar.replaceNew` */ + newWhat: { docx: 'document', xlsx: 'spreadsheet', pptx: 'presentation' }, + + kind: { docx: 'Word document', xlsx: 'Excel workbook', pptx: 'PowerPoint presentation' }, + from: { pages: 'Apple Pages document', keynote: 'Apple Keynote presentation', numbers: 'Apple Numbers spreadsheet' }, + converted: { + 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', + }, + imported: { + 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', + }, + + details: { + title: 'Document details', + name: 'Name', + type: 'Type', + viewOnly: (what: string) => `${what} (view only)`, + openedAs: (what: string, kind: string) => `${what}, opened as ${kind}`, + fileSize: 'File size', + status: 'Status', + unsaved: 'Unsaved changes', + core: { + title: 'Title', + subject: 'Subject', + creator: 'Author', + keywords: 'Keywords', + description: 'Comments', + lastModifiedBy: 'Last modified by', + created: 'Created', + modified: 'Modified', + }, + }, + + file: { + menu: 'File', + new: 'New', + newDocx: 'Document', + newXlsx: 'Spreadsheet', + newPptx: 'Presentation', + open: 'Open…', + importCsv: 'Import CSV into new sheet…', + save: 'Save', + rename: 'Rename…', + downloadAs: 'Download as', + pdf: 'PDF document', + html: 'Web page', + txt: 'Plain text', + md: 'Markdown', + csv: 'CSV (current sheet)', + tsv: 'TSV (current sheet)', + picture: 'SVG picture', + details: 'Document details', + print: 'Print', + close: 'Close', + preparingPdf: 'Preparing PDF… choose “Save as PDF” in the print dialog', + preparing: 'Preparing…', + unsupported: (name: string) => + `Cannot open “${name}”: supported files are Word, Excel, PowerPoint (also 97-2003), OpenDocument, RTF, Pages, Keynote, Numbers, CSV, text, Markdown, HTML, SVG, Mermaid, PlantUML and Graphviz (also gzip-compressed: .svgz, .csv.gz)`, + }, + + zoom: { + group: 'Zoom', + out: 'Zoom out', + in: 'Zoom in', + fit: 'Fit', + fitTitle: 'Fit width (click for 100%)', + toFit: 'Click to fit width', + }, + + toolbar: { + fontSize: 'Font size', + fontSizeDown: 'Decrease font size', + fontSizeUp: 'Increase font size', + more: 'More', + moreTools: 'More tools', + custom: 'Custom', + customColor: 'Custom color', + customColorTitle: 'Custom color…', + tableSize: 'Table size', + }, + + /** text editing shared by the document, cell and slide editors */ + edit: { + undo: 'Undo', + redo: 'Redo', + bold: 'Bold', + italic: 'Italic', + underline: 'Underline', + strike: 'Strikethrough', + textColor: 'Text color', + highlight: 'Highlight color', + automatic: 'Automatic', + font: 'Font', + alignLeft: 'Align left', + center: 'Center', + alignRight: 'Align right', + justify: 'Justify', + bullets: 'Bulleted list', + numbers: 'Numbered list', + indentLess: 'Decrease indent', + indentMore: 'Increase indent', + sup: 'Superscript', + sub: 'Subscript', + clearFormat: 'Clear formatting', + link: 'Insert link', + editLink: 'Edit link', + linkPlaceholder: 'https://…', + openLink: 'Open link', + editLinkMenu: 'Edit link…', + insertLinkMenu: 'Insert link…', + removeLink: 'Remove link', + image: 'Insert image', + imageMenu: 'Insert image…', + altText: 'Alt text', + altTextMenu: 'Alt text…', + altLabel: 'Describe the picture for screen readers', + cut: 'Cut', + copy: 'Copy', + paste: 'Paste', + pastePlain: 'Paste without formatting', + selectAll: 'Select all', + clipboardBlocked: (keys: string) => `The browser blocked clipboard access — use ${keys} to paste`, + useKeys: (keys: string) => `Use ${keys}`, + /** context menu entry that starts a comment */ + comment: 'Comment', + showComment: 'Show comment', + /** the Delete key, as a menu hint */ + delKey: 'Del', + findReplace: 'Find & replace', + /** a menu entry or button with its shortcut */ + keyed: (label: string, keys: string) => `${label} (${keys})`, + }, + + find: { + placeholder: 'Find in document', + label: 'Find', + prev: 'Previous (Shift+Enter)', + next: 'Next (Enter)', + replace: 'Replace', + replaceWith: 'Replace with', + replaceAll: 'All', + close: 'Close (Esc)', + }, + + table: { + menu: 'Table', + rowAbove: 'Insert row above', + rowBelow: 'Insert row below', + colLeft: 'Insert column left', + colRight: 'Insert column right', + delRow: 'Delete row', + delCol: 'Delete column', + delTable: 'Delete table', + distribute: 'Distribute columns evenly', + merge: 'Merge cells', + unmerge: 'Unmerge cells', + insert: 'Insert table', + }, + + /** cell and shape formatting shared by the document, sheet and slide toolbars */ + format: { + noFill: 'No fill', + borderColor: 'Border color', + black: 'Black', + borderStyle: 'Border style', + borders: { + all: 'All borders', + inner: 'Inner borders', + outer: 'Outer borders', + none: 'No borders', + top: 'Top border', + bottom: 'Bottom border', + left: 'Left border', + right: 'Right border', + }, + lines: { thin: 'Thin', medium: 'Medium', thick: 'Thick', dashed: 'Dashed', dotted: 'Dotted', double: 'Double' }, + vAlign: 'Vertical align', + vAligns: { top: 'Top', middle: 'Middle', bottom: 'Bottom' }, + spacings: { single: 'Single', double: 'Double', triple: 'Triple' }, + inches: (w: string, h: string) => `${w} × ${h} in`, + }, + + source: { + source: 'Source', + lines: (n: number): string => (n === 1 ? 'line' : 'lines'), + copy: 'Copy the source', + download: 'Download the source', + input: (format: string) => `${format} source`, + }, + + picture: { + notShown: 'The picture is not shown', + size: 'Picture size', + notDrawn: 'SVG picture not drawn.', + }, +} + +export type Strings = typeof en diff --git a/src/react/strings/index.tsx b/src/react/strings/index.tsx new file mode 100644 index 0000000..3396dd6 --- /dev/null +++ b/src/react/strings/index.tsx @@ -0,0 +1,66 @@ +import { createContext, useContext, useMemo, type ReactNode } from 'react' +import { en, type Strings } from './en' +import { de } from './de' + +export type { Strings } from './en' +export { en } from './en' +export { de } from './de' + +/** Locales shipped with the engine. */ +export type Locale = 'en' | 'de' + +export const LOCALES: Record = { en, de } + +type DeepPartial = { [K in keyof T]?: T[K] extends string | ((...args: never[]) => unknown) ? T[K] : DeepPartial } + +/** A partial table: groups merge key by key over the locale's texts. */ +export type StringsOverride = DeepPartial + +const isGroup = (v: unknown): v is Record => !!v && typeof v === 'object' + +function merge(base: Record, over: Record): Record { + const out = { ...base } + for (const [k, v] of Object.entries(over)) { + if (v === undefined) continue + const cur = out[k] + out[k] = isGroup(cur) && isGroup(v) ? merge(cur, v) : v + } + return out +} + +/** The texts for `locale` with `override` merged over them (unknown locales fall back to English). */ +export function resolveStrings(locale: Locale | string = 'en', override?: StringsOverride): Strings { + const base = LOCALES[locale as Locale] ?? en + return override ? (merge(base, override as Record) as Strings) : base +} + +const formats = new Map() + +/** A number in the texts' locale, without digit grouping unless `opts` asks for it. */ +export function formatNumber(s: Strings, n: number, opts?: Intl.NumberFormatOptions): string { + const key = s.locale + JSON.stringify(opts ?? {}) + let f = formats.get(key) + if (!f) formats.set(key, (f = new Intl.NumberFormat(s.locale, { useGrouping: false, ...opts }))) + return f.format(n) +} + +/** A count (pages, words, rows) with digit grouping. */ +export const formatCount = (s: Strings, n: number) => formatNumber(s, n, { useGrouping: true }) + +/** A byte count as B / KB / MB. */ +export function formatBytes(s: Strings, n: number): string { + if (n < 1024) return `${formatNumber(s, n)} B` + if (n < 1024 * 1024) return `${formatNumber(s, n / 1024, { maximumFractionDigits: 0 })} KB` + return `${formatNumber(s, n / 1024 / 1024, { minimumFractionDigits: 1, maximumFractionDigits: 1 })} MB` +} + +const StringsContext = createContext(en) + +/** Provides the UI texts to the views below it (`DocViewer` provides its own from `locale` / `strings`). */ +export function StringsProvider({ locale, strings, children }: { locale?: Locale | string; strings?: StringsOverride; children?: ReactNode }) { + const value = useMemo(() => resolveStrings(locale, strings), [locale, strings]) + return {children} +} + +/** The UI texts of the nearest `StringsProvider` (English without one). */ +export const useStrings = () => useContext(StringsContext) diff --git a/test/strings.test.ts b/test/strings.test.ts new file mode 100644 index 0000000..64df67d --- /dev/null +++ b/test/strings.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, test } from 'bun:test' +import { de, en, formatBytes, formatCount, LOCALES, resolveStrings, type Strings } from '../src/react/strings' + +type Entry = [path: string, value: unknown] + +/** every leaf of a table, with its dotted key */ +function leaves(table: object, prefix = ''): Entry[] { + return Object.entries(table).flatMap(([k, v]): Entry[] => (v && typeof v === 'object' ? leaves(v, `${prefix}${k}.`) : [[prefix + k, v]])) +} + +/** a sample call of a text function: numbers for counts, names otherwise */ +const sample = (fn: (...args: never[]) => unknown, n: number) => (fn as (...a: unknown[]) => unknown)(...Array.from({ length: fn.length }, () => n), 'x') + +describe('UI strings', () => { + const enLeaves = leaves(en) + + test('every locale has exactly the keys of en, with the same kind of value', () => { + for (const [name, table] of Object.entries(LOCALES)) { + const got = new Map(leaves(table)) + expect([...got.keys()].sort(), name).toEqual(enLeaves.map(([k]) => k).sort()) + for (const [k, v] of enLeaves) expect(typeof got.get(k), `${name}.${k}`).toBe(typeof v) + } + }) + + test('no text is empty, also for 1 and for many', () => { + for (const [name, table] of Object.entries(LOCALES)) { + for (const [k, v] of leaves(table)) { + const texts = typeof v === 'function' ? [sample(v as never, 1), sample(v as never, 3)] : [v] + for (const t of texts) { + expect(typeof t, `${name}.${k}`).toBe('string') + expect((t as string).trim().length, `${name}.${k}`).toBeGreaterThan(0) + } + } + } + }) + + test('German is Swiss: no sharp s', () => { + for (const [k, v] of leaves(de)) { + const texts = typeof v === 'function' ? [sample(v as never, 1), sample(v as never, 3)] : [v] + for (const t of texts) expect(String(t).includes('ß'), `de.${k}`).toBe(false) + } + }) + + test('an override merges key by key over the locale', () => { + const s = resolveStrings('de', { file: { menu: 'Ablage' }, zoom: { in: 'Grösser' } }) + expect(s.file.menu).toBe('Ablage') + expect(s.file.print).toBe(de.file.print) + expect(s.zoom.in).toBe('Grösser') + expect(s.zoom.out).toBe(de.zoom.out) + expect(s.details.core.title).toBe(de.details.core.title) + // the shipped tables are left alone + expect(de.file.menu).toBe('Datei') + expect(resolveStrings('fr' as never)).toBe(en as Strings) + }) + + test('numbers keep the English output and follow the locale', () => { + expect(formatBytes(en, 512)).toBe('512 B') + expect(formatBytes(en, 2048)).toBe('2 KB') + expect(formatBytes(en, 1536 * 1024 * 1024)).toBe('1536.0 MB') + expect(formatCount(en, 1234567)).toBe('1,234,567') + expect(formatCount(de, 1234567)).not.toBe('1,234,567') + }) +}) From 5d98742a6865398a41aca7d5a2e17b4ae13725b6 Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 14 Nov 2026 11:30:19 +0100 Subject: [PATCH 02/19] feat(viewer): replaceable UI components for toolbars and dialogs A host can render its own Button, Select, Separator, Dialog and Toast in the engine's toolbars and dialogs (`components` prop, UIComponentsProvider), for a design system's controls where design tokens are not enough. Each one left out keeps the built-in one, whose markup is unchanged. - every toolbar button goes through Button: Btn, the color, picker and overflow toggles, the font size steps; Dropdown/Select through Select - PromptDialog and ConfirmDialog build their actions and body and render them through Dialog; Toast keeps its timer and renders through Toast - OfficeUIProvider carries icons, components, locale and strings to views mounted without DocViewer - the overflow button's title is its accessible name ("More tools"), so the unused "More" text goes - docs/theming.md "Your own components"; unit tests for each component and nested providers; e2e with host components: toolbar, formatting keeps the selection, overflow at a narrow width, the link prompt Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 1 + docs/theming.md | 46 +++++++++- e2e/app/main.tsx | 47 +++++++++- e2e/components.spec.ts | 60 +++++++++++++ src/index.ts | 3 +- src/react/DocViewer.tsx | 8 ++ src/react/common/Dialog.tsx | 131 ++++++++++------------------ src/react/edit/Toolbar.tsx | 101 +++++++++++----------- src/react/strings/de.ts | 1 - src/react/strings/en.ts | 1 - src/react/ui.tsx | 168 ++++++++++++++++++++++++++++++++++++ test/ui.test.tsx | 108 +++++++++++++++++++++++ 12 files changed, 534 insertions(+), 141 deletions(-) create mode 100644 e2e/components.spec.ts create mode 100644 src/react/ui.tsx create mode 100644 test/ui.test.tsx diff --git a/docs/api.md b/docs/api.md index 6e5cd39..9f509fc 100644 --- a/docs/api.md +++ b/docs/api.md @@ -74,6 +74,7 @@ CSS is auto-injected, no import needed (or import `@p10node/office-engine/styles | `captureSelectAll` | `boolean` | `true` | Ctrl/⌘+A from anywhere on the page selects the document; `false`: from the viewer only | | `fileMenuItems` | `FileMenuItem[]` | – | Extra File menu entries (`label`, `onClick`, `icon`, `hint`) | | `icons` | `Icons` | built-in | Your own icons: a map by `IconName` or a resolver `(name, { size }) => node`; see [Icons](#icons) | +| `components` | `Partial` | built-in | Your own `Button`, `Select`, `Separator`, `Dialog`, `Toast` in the toolbars and dialogs; see [Theming](theming.md#your-own-components) | | `onRename` | `(name) => void` | – | File → Rename result (extension included) | | `onClose` | `() => void` | – | Adds File → Close | | `onSave` | `(blob, name) => void` | download | Receives saved file (downloads by default): the Office file, or a Markdown / HTML / SVG file as itself | diff --git a/docs/theming.md b/docs/theming.md index 648b0ed..0ff91a9 100644 --- a/docs/theming.md +++ b/docs/theming.md @@ -66,9 +66,53 @@ 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. + +## 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 + ( + + {icon}{label}{children} + + ), + Separator: () => , + }} +/> +``` + +| 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, size list, 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`, `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`, `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 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. + ## Tokens | Group | Tokens | diff --git a/e2e/app/main.tsx b/e2e/app/main.tsx index e1b6a41..f9eebb0 100644 --- a/e2e/app/main.tsx +++ b/e2e/app/main.tsx @@ -4,10 +4,11 @@ * comments: &me=Ann&meId=u1 (author), &people=1 (mentions: Ann, Bob Stone, Cid), &comments=0 (hidden), &cmOpen=1 * &icons=1: every icon from a host resolver, as `` * texts: &locale=de, &fileLabel=… (a partial `strings` override of the File menu's label) + * &components=1: the host's own Button, Separator, Dialog and Toast (`data-host-*` markers) */ import { useState } from 'react' import { createRoot } from 'react-dom/client' -import { DocViewer, type DocViewerProps, type FileMenuItem } from '../../src' +import { DocViewer, type DocViewerProps, type FileMenuItem, type UIComponents } from '../../src' type Ev = { type: string; [k: string]: unknown } declare global { @@ -34,6 +35,49 @@ const items: FileMenuItem[] = [ { label: 'Version history', hint: 'beta', onClick: () => log({ type: 'item', label: 'Version history' }) }, ] +// plain host components: no engine classes, so nothing of the engine's CSS styles them +const components: Partial = { + Button: (p) => ( + + ), + Separator: () => , + Dialog: (p) => { + const actions = p.actions.map((a, i) => ( + + )) + const body = ( + <> +

{p.title}

+ {p.children} + {actions} + + ) + return ( +
e.key === 'Escape' && p.onClose()}> + {p.onSubmit ? ( +
{ + e.preventDefault() + p.onSubmit!() + }} + > + {body} +
+ ) : ( + body + )} +
+ ) + }, + Toast: ({ text }) => {text}, +} + const initial: DocViewerProps = { src: q.get('src'), name: q.get('name') ?? undefined, @@ -67,6 +111,7 @@ const initial: DocViewerProps = { open: flag('cmOpen'), onEvent: (e) => log({ type: 'comment', action: e.type, id: e.comment.id, text: e.comment.text, thread: e.thread.id, quote: e.quote, mentioned: e.mentioned.map((m) => m.id ?? m.name), participants: e.participants.map((m) => m.id ?? m.name) }), }, + components: q.has('components') ? components : undefined, icons: q.has('icons') ? (name) => ( diff --git a/e2e/components.spec.ts b/e2e/components.spec.ts new file mode 100644 index 0000000..e194eaf --- /dev/null +++ b/e2e/components.spec.ts @@ -0,0 +1,60 @@ +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() + 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([]) + }) +}) diff --git a/src/index.ts b/src/index.ts index e90e0e8..7b7435d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,8 @@ 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 { 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, LOCALES, en, de, type Strings, type StringsOverride, type Locale } from './react/strings' export { DocumentClient, setDefaultWorker, type OpenOptions } from './core/worker/client' diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx index 3ec9030..2e8f0bf 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -7,6 +7,7 @@ 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, useFileActions, type FileMenuItem } from './file/FileMenu' import { importFile, type Imported } from './file/importFile' @@ -111,6 +112,11 @@ 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 /** Language of the viewer's texts (bars, menus, dialogs, messages): 'en' or 'de'. Default 'en'. */ locale?: Locale /** Texts replacing the locale's, key by key (see `Strings`): a group may be given in part, e.g. `{ file: { menu: 'Datei' } }`. */ @@ -534,6 +540,7 @@ function Viewer(props: DocViewerProps) { return ( +
{toolbar && (
@@ -689,6 +696,7 @@ function Viewer(props: DocViewerProps) { /> )}
+ ) } diff --git a/src/react/common/Dialog.tsx b/src/react/common/Dialog.tsx index 6489f77..c2b8785 100644 --- a/src/react/common/Dialog.tsx +++ b/src/react/common/Dialog.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState, type ReactNode } from 'react' import { useStrings } from '../strings' +import { DefaultDialog, DefaultToast, useHostUI, type DialogAction } from '../ui' export interface PromptSpec { title: string @@ -18,6 +19,7 @@ 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(() => { @@ -29,108 +31,63 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () onClose() spec.onOk(v) } + const actions: DialogAction[] = [ + ...(spec.extra + ? [ + { + label: spec.extra.label, + onClick: () => { + onClose() + spec.extra!.run() + }, + }, + ] + : []), + { label: t.common.cancel, onClick: onClose }, + { label: spec.ok ?? t.common.ok, primary: true, submit: true }, + ] return ( -
e.target === e.currentTarget && onClose()} - onKeyDown={(e) => { - if (e.key === 'Escape') { - e.stopPropagation() - onClose() - } - }} - > -
{ - e.preventDefault() - done() - }} - > -
{spec.title}
- {spec.label && } - {spec.area ? ( -
', + ) + expect(html(, null)).toBe( + '
Delete?
Gone for good
', + ) }) test('Button gets title, resolved icon, state, the engine classes and the focus-keeping mouse down', () => { @@ -84,12 +94,26 @@ describe('UI components', () => { html() const [prompt, confirm] = seen.dialog expect(prompt.onSubmit).toBeFunction() + expect(prompt.actions[0]).toMatchObject({ label: 'Remove link', extra: true }) expect(prompt.actions.at(-1)).toMatchObject({ primary: true, submit: true }) expect(confirm.kind).toBe('alert') expect(confirm.onSubmit).toBeUndefined() expect(confirm.actions.at(-1)).toMatchObject({ label: 'Delete', primary: true, autoFocus: true }) }) + 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 + const Select = (p: SelectProps) => <>{p.options.map((o) => o.icon && )} + const out = renderToStaticMarkup( + host bold }}> + + , + ) + expect(out).toContain('') + expect(out).toContain(' { expect(html()).toBe('Saved') }) From 3d8d0afa2cdde61d6bb828a891765c5fb40e79d3 Mon Sep 17 00:00:00 2001 From: Markus Date: Tue, 17 Nov 2026 20:39:02 +0100 Subject: [PATCH 13/19] fix(viewer): complete localization behavior and regression coverage --- README.md | 2 +- docs/api.md | 12 ++++++---- e2e/embed.spec.ts | 30 +++++++++++++++++++++++ e2e/locale.spec.ts | 36 ++++++++++++++++++++++++++++ src/embed.ts | 7 ++++-- src/react/comments/CommentsPanel.tsx | 2 +- src/react/docx/DocxView.tsx | 2 +- src/react/pptx/PptxView.tsx | 6 ++--- src/react/strings/de.ts | 1 + src/react/strings/en.ts | 1 + src/react/strings/index.tsx | 2 +- src/react/xlsx/XlsxView.tsx | 2 +- test/strings-render.test.tsx | 35 +++++++++++++++++++++++++++ test/strings.test.ts | 9 +++++-- 14 files changed, 130 insertions(+), 17 deletions(-) create mode 100644 test/strings-render.test.tsx diff --git a/README.md b/README.md index c11adba..c7c8054 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,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; English by default, German shipped (`locale="de"`), any text replaceable through `strings` +- **Translatable UI**: every text of the bars, menus and dialogs from one typed table; English by default, German shipped with Swiss spelling and `de-CH` number/date formatting (`locale="de"`; see [UI texts](docs/api.md#ui-texts)), any text replaceable through `strings` - **Embed anywhere**: React component, hook, vanilla `mount()`, `` web component, single `.ts` with a `Strings` table, list it in `LOCALES` and the `Locale` type (`src/react/strings/index.tsx`) and in `LOCALE_NAMES` (`src/embed.ts`); `test/strings.test.ts` checks that it has every key and no empty text. -Not translated: texts that end up in the saved document (a new sheet's name, the author "Me", the text of a new text box), font names, number format previews, and messages from the parsing worker that the UI shows as they are. +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 parsing-worker messages are not translated by the table. ## Without a React build diff --git a/e2e/embed.spec.ts b/e2e/embed.spec.ts index 6ad47e2..41f7f85 100644 --- a/e2e/embed.spec.ts +++ b/e2e/embed.spec.ts @@ -45,4 +45,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') + el.setAttribute('locale', 'de') + el.strings = { file: { menu: 'Ablage' } } + ;(window as any).__mounted.update({ toolbar: true, locale: 'de', strings: { 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', 'de-DE') + ;(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/locale.spec.ts b/e2e/locale.spec.ts index ca9ae71..a00719a 100644 --- a/e2e/locale.spec.ts +++ b/e2e/locale.spec.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from 'bun:test' +import { de, en } from '../src/react/strings' import { useBrowser, viewer } from './harness' useBrowser() @@ -45,4 +46,39 @@ describe('locale', () => { 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.__setProps({ locale: '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', 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.__setProps({ locale: '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/src/embed.ts b/src/embed.ts index afab05b..4fa61c3 100644 --- a/src/embed.ts +++ b/src/embed.ts @@ -49,6 +49,9 @@ export class OfficeViewerElement extends HTMLElement { private _file?: Blob | ArrayBuffer private _icons?: Icons private _strings?: StringsOverride + // Keep event callbacks stable across attribute/property updates: changing UI texts must not replay load/error events. + private onLoad: NonNullable = (client) => this.dispatchEvent(new CustomEvent('load', { detail: { kind: client.kind, name: client.name } })) + private onError: NonNullable = (error) => this.dispatchEvent(new CustomEvent('error', { detail: error })) get file() { return this._file @@ -125,8 +128,8 @@ export class OfficeViewerElement extends HTMLElement { user: this.getAttribute('user') ? { name: this.getAttribute('user')! } : undefined, onEvent: (e) => this.dispatchEvent(new CustomEvent('comment', { detail: e })), }, - onLoad: (client) => this.dispatchEvent(new CustomEvent('load', { detail: { kind: client.kind, name: client.name } })), - onError: (error) => this.dispatchEvent(new CustomEvent('error', { detail: error })), + onLoad: this.onLoad, + onError: this.onError, } } diff --git a/src/react/comments/CommentsPanel.tsx b/src/react/comments/CommentsPanel.tsx index 7672471..ea539c3 100644 --- a/src/react/comments/CommentsPanel.tsx +++ b/src/react/comments/CommentsPanel.tsx @@ -401,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) => ( diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index 8389281..0286730 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -720,7 +720,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp } cm.setHost(host) return () => cm.setHost(null) - }, [cm, editor]) + }, [cm, editor, str]) useEffect(() => cm?.touch(), [cm, version]) const cmMarks = cm ? cm.threads().filter((t) => !t.root.done || t.root.id === cmState.active).map((t) => t.root.id) : [] // the text a thread being written covers stays highlighted while the box has the focus diff --git a/src/react/pptx/PptxView.tsx b/src/react/pptx/PptxView.tsx index de396c9..895c1da 100644 --- a/src/react/pptx/PptxView.tsx +++ b/src/react/pptx/PptxView.tsx @@ -598,7 +598,7 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t const commentAt = (i: number, x: number, y: number): PendingComment | null => { const s = meta.slides[i] if (!s) return null - return { quote: `Slide ${i + 1}`, at: { slide: s.path, x: Math.max(0, Math.min(meta.w - 1, x)), y: Math.max(0, Math.min(meta.h - 1, y)) } } + return { quote: str.pptx.slideNumber(formatCount(str, i + 1)), at: { slide: s.path, x: Math.max(0, Math.min(meta.w - 1, x)), y: Math.max(0, Math.min(meta.h - 1, y)) } } } const cmLive = useRef({ selected, current, go }) cmLive.current = { selected, current, go } @@ -622,7 +622,7 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t const out: (PlacedThread & { k: number[] })[] = [] for (const t of threads) { const x = slideOf(t) - if (x) out.push({ ...t, quote: `Slide ${x.i + 1}`, k: [x.i, x.a.y, x.a.x] }) + if (x) out.push({ ...t, quote: str.pptx.slideNumber(formatCount(str, x.i + 1)), k: [x.i, x.a.y, x.a.x] }) } return out.sort((a, b) => a.k[0] - b.k[0] || a.k[1] - b.k[1] || a.k[2] - b.k[2]) }, @@ -633,7 +633,7 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t }, }) return () => cm.setHost(null) - }, [cm, meta, slidesVer]) // eslint-disable-line react-hooks/exhaustive-deps + }, [cm, meta, slidesVer, str]) // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => cm?.touch(), [cm, slidesVer, meta.count]) const pins = useMemo(() => { const out = new Map() diff --git a/src/react/strings/de.ts b/src/react/strings/de.ts index cfe5a0e..4e9d22e 100644 --- a/src/react/strings/de.ts +++ b/src/react/strings/de.ts @@ -526,6 +526,7 @@ export const de: Strings = { wedgeRoundRectCallout: 'Abgerundete Legende', }, slide: 'Folie', + slideNumber: (n: string) => `Folie ${n}`, newSlide: 'Neue Folie', duplicateSlide: 'Folie duplizieren', deleteSlide: 'Folie löschen', diff --git a/src/react/strings/en.ts b/src/react/strings/en.ts index 5937ffe..52d0d23 100644 --- a/src/react/strings/en.ts +++ b/src/react/strings/en.ts @@ -538,6 +538,7 @@ export const en = { wedgeRoundRectCallout: 'Rounded callout', }, slide: 'Slide', + slideNumber: (n: string) => `Slide ${n}`, newSlide: 'New slide', duplicateSlide: 'Duplicate slide', deleteSlide: 'Delete slide', diff --git a/src/react/strings/index.tsx b/src/react/strings/index.tsx index 3396dd6..987cbfc 100644 --- a/src/react/strings/index.tsx +++ b/src/react/strings/index.tsx @@ -30,7 +30,7 @@ function merge(base: Record, over: Record): Re /** The texts for `locale` with `override` merged over them (unknown locales fall back to English). */ export function resolveStrings(locale: Locale | string = 'en', override?: StringsOverride): Strings { - const base = LOCALES[locale as Locale] ?? en + const base = Object.hasOwn(LOCALES, locale) ? LOCALES[locale as Locale] : en return override ? (merge(base, override as Record) as Strings) : base } diff --git a/src/react/xlsx/XlsxView.tsx b/src/react/xlsx/XlsxView.tsx index 5297219..6b6c75e 100644 --- a/src/react/xlsx/XlsxView.tsx +++ b/src/react/xlsx/XlsxView.tsx @@ -355,7 +355,7 @@ export function XlsxView({ client, onStatus, initialSheet }: XlsxViewProps) { off() cm.setHost(null) } - }, [cm, store, meta]) + }, [cm, store, meta, str]) const [edit, setEdit] = useState(null) /** set while switching sheets during a formula edit: blur must not commit */ diff --git a/test/strings-render.test.tsx b/test/strings-render.test.tsx new file mode 100644 index 0000000..3e38c3a --- /dev/null +++ b/test/strings-render.test.tsx @@ -0,0 +1,35 @@ +import { describe, expect, test } from 'bun:test' +import { renderToStaticMarkup } from 'react-dom/server' +import { PromptDialog } from '../src/react/common/Dialog' +import { FindBar } from '../src/react/docx/FindBar' +import { StringsProvider } from '../src/react/strings' + +const noop = () => {} +const find = + +describe('rendered UI strings', () => { + test('German find/replace labels and a partial override reach the rendered controls', () => { + const html = renderToStaticMarkup( + + {find} + + , + ) + expect(html).toContain('placeholder="Im Dokument suchen"') + expect(html).toContain('aria-label="Suchen"') + expect(html).toContain('aria-label="Vorheriges (Umschalt+Eingabe)"') + expect(html).toContain('aria-label="Ersetzen durch"') + expect(html).toContain('>Ersetzen') + expect(html).toContain('>Alle Treffer ersetzen') + expect(html).toContain('>Abbrechen') + expect(html).not.toContain('Find in document') + expect(html).not.toContain('>Cancel') + }) + + test('standalone controls default to English and the German render leaves that default intact', () => { + const html = renderToStaticMarkup(find) + expect(html).toContain('placeholder="Find in document"') + expect(html).toContain('aria-label="Replace with"') + expect(html).toContain('>All') + }) +}) diff --git a/test/strings.test.ts b/test/strings.test.ts index 64df67d..2edfb48 100644 --- a/test/strings.test.ts +++ b/test/strings.test.ts @@ -50,7 +50,10 @@ describe('UI strings', () => { expect(s.details.core.title).toBe(de.details.core.title) // the shipped tables are left alone expect(de.file.menu).toBe('Datei') - expect(resolveStrings('fr' as never)).toBe(en as Strings) + for (const locale of ['fr', 'de-DE', 'de-CH', 'constructor', 'toString', '__proto__']) { + expect(resolveStrings(locale), locale).toBe(en as Strings) + expect(resolveStrings(locale, { file: { menu: 'Custom' } }).common.cancel, locale).toBe('Cancel') + } }) test('numbers keep the English output and follow the locale', () => { @@ -58,6 +61,8 @@ describe('UI strings', () => { expect(formatBytes(en, 2048)).toBe('2 KB') expect(formatBytes(en, 1536 * 1024 * 1024)).toBe('1536.0 MB') expect(formatCount(en, 1234567)).toBe('1,234,567') - expect(formatCount(de, 1234567)).not.toBe('1,234,567') + expect(de.locale).toBe('de-CH') + // ICU versions use either a straight or a typographic apostrophe. + expect(formatCount(de, 1234567)).toMatch(/^1['’]234['’]567$/) }) }) From 781c23933a9ea1477111b50cebdb9d761cafeddd Mon Sep 17 00:00:00 2001 From: Markus Date: Tue, 17 Nov 2026 20:39:15 +0100 Subject: [PATCH 14/19] fix(viewer): preserve controller ownership and enforce action permissions --- docs/api.md | 6 ++++ e2e/app/main.tsx | 10 ++++-- e2e/controller.spec.ts | 61 +++++++++++++++++++++++++++++++++---- src/embed.ts | 10 +++--- src/index.ts | 2 +- src/react/DocViewer.tsx | 21 ++++++------- src/react/common/Slots.tsx | 4 +-- src/react/controller.ts | 52 ++++++++++++++++++++++--------- src/react/file/FileMenu.tsx | 20 +++++++++--- src/react/pptx/PptxView.tsx | 9 ++---- src/react/xlsx/XlsxView.tsx | 6 ++-- test/controller.test.ts | 53 +++++++++++++++++++++++++------- 12 files changed, 189 insertions(+), 65 deletions(-) diff --git a/docs/api.md b/docs/api.md index 99dbef7..3c584bb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -138,6 +138,12 @@ action: `pdf`, `html`, `text:md`, `details`, `rename`…), `toggleComments(open? for does nothing. `subscribe(fn)` returns its unsubscribe; `snapshot()` the current state. Without `react`, `mount()` returns the controller (`mounted.controller`), and `` has it as `element.controller`. +Controller actions obey `allowEdit`, `allowSave`, `allowDownload` and `allowOpen` even when the File menu is hidden. +`fileMenu={false}` hides that menu and its keyboard shortcuts; it does not disable a host's controller controls. +New/Open replace the document and remain available for a read-only file when `allowOpen` permits them. +Import changes a workbook and additionally requires editing permission. Controllers are created with +`createViewerController()`; publishing and attachment methods are internal to the engine. + ### Comments ```tsx diff --git a/e2e/app/main.tsx b/e2e/app/main.tsx index 6625797..09c7953 100644 --- a/e2e/app/main.tsx +++ b/e2e/app/main.tsx @@ -17,6 +17,7 @@ declare global { __events: Ev[] __setProps: (p: Partial) => void __ctl: ViewerController + __overlap: (phase: number) => void } } window.__events = [] @@ -101,7 +102,7 @@ const initial: DocViewerProps = { locale: (q.get('locale') as DocViewerProps['locale']) ?? undefined, strings: q.has('fileLabel') ? { file: { menu: q.get('fileLabel')! } } : undefined, headless: flag('headless'), - controller: window.__ctl, + controller: flag('controller') ? window.__ctl : undefined, onSave: q.has('onSave') ? async (blob, name) => void log({ type: 'save', name, b64: await b64(blob) }) : undefined, onDirtyChange: (dirty) => log({ type: 'dirty', dirty }), onRename: (name) => log({ type: 'rename', name }), @@ -131,8 +132,13 @@ const initial: DocViewerProps = { function App() { const [props, setProps] = useState(initial) + const [phase, setPhase] = useState(0) + window.__overlap = setPhase window.__setProps = (p) => setProps((cur) => ({ ...cur, ...p })) - return + return <> + {phase < 2 && } + {phase > 0 && } + } createRoot(document.getElementById('root')!).render() diff --git a/e2e/controller.spec.ts b/e2e/controller.spec.ts index ea4d760..a1d6612 100644 --- a/e2e/controller.spec.ts +++ b/e2e/controller.spec.ts @@ -10,7 +10,7 @@ const until = (v: Viewer, check: string) => v.page.waitForFunction(`(() => { con describe('controller and headless mode', () => { test('docx: zoom, pages and headings through the controller; no chrome of its own', async () => { - const v = await viewer({ src: 'samples/sample.docx', headless: true }) + const v = await viewer({ controller: true, src: 'samples/sample.docx', headless: true }) const { page } = v expect(await page.locator('.de-bar').count()).toBe(0) expect(await page.locator('.de-zoom').count()).toBe(0) @@ -37,8 +37,21 @@ describe('controller and headless mode', () => { expect(v.errors).toEqual([]) }) + test('an overlapping viewer survives the old viewer unmounting', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', headless: true }) + await v.page.evaluate(() => window.__overlap(1)) + await v.waitEvent('load', 2) + await until(v, "s.kind === 'docx' && s.zoom && s.page && s.page.count > 0") + await v.page.evaluate(() => window.__overlap(2)) + await v.page.evaluate(() => window.__ctl.setZoom(1.25)) + await until(v, 's.kind === "docx" && s.zoom.value === 1.25') + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.editing') + expect(v.errors).toEqual([]) + }) + test('docx: editing and saving through the controller', async () => { - const v = await viewer({ src: 'samples/sample.docx', headless: true, onSave: true }) + const v = await viewer({ controller: true, src: 'samples/sample.docx', headless: true, onSave: true }) const { page } = v await until(v, 's.canEdit') await page.evaluate(() => window.__ctl.setEditing(true)) @@ -55,7 +68,7 @@ describe('controller and headless mode', () => { }) test('docx: undo is offered only while editing', async () => { - const v = await viewer({ src: 'samples/sample.docx', headless: true }) + const v = await viewer({ controller: true, src: 'samples/sample.docx', headless: true }) await until(v, 's.canEdit') await v.page.evaluate(() => window.__ctl.setEditing(true)) await until(v, 's.editing') @@ -70,7 +83,7 @@ describe('controller and headless mode', () => { }) test('xlsx: the sheets as the outline, no tabs of its own', async () => { - const v = await viewer({ src: 'samples/sample.xlsx', headless: true }) + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', headless: true }) const { page } = v expect(await page.locator('.de-tabs').isVisible()).toBe(false) await until(v, "s.kind === 'xlsx' && s.outline && s.outline.kind === 'sheets'") @@ -83,8 +96,44 @@ describe('controller and headless mode', () => { expect(v.errors).toEqual([]) }) + test('xlsx: history cannot mutate a workbook outside editing', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', editable: true, headless: true }) + await v.typeCell('J12', 'history') + await until(v, 's.canUndo') + await v.page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && !s.canUndo && !s.canRedo') + await v.page.evaluate(() => { window.__ctl.undo(); window.__ctl.redo() }) + expect(await v.shown('J12')).toBe('history') + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.canUndo') + await v.page.evaluate(() => window.__ctl.undo()) + await until(v, 's.canRedo') + expect(await v.shown('J12')).toBe('') + }) + + test('controller file actions enforce permissions even with the menu hidden', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', fileMenu: false, allowOpen: false, allowEdit: false, editable: true, allowSave: false, allowDownload: false, onSave: true }) + const pickers: string[] = [], downloads: string[] = [] + v.page.on('filechooser', () => pickers.push('picker')) + v.page.on('download', () => downloads.push('download')) + await v.page.evaluate(() => { + for (const id of ['new:docx', 'new:invalid', 'open', 'import', 'save', 'original', 'pdf', 'print']) window.__ctl.fileAction(id) + window.__ctl.setEditing(true) + }) + await v.page.waitForTimeout(300) + expect(pickers).toEqual([]) + expect(downloads).toEqual([]) + expect(await v.events('save')).toEqual([]) + expect((await state(v)).editing).toBe(false) + expect((await state(v)).kind).toBe('xlsx') + await v.page.evaluate(() => window.__setProps({ allowDownload: true })) + const dl = await v.download(() => v.page.evaluate(() => window.__ctl.fileAction('text:csv'))) + expect(dl.name).toBe('sample.csv') + expect(v.errors).toEqual([]) + }) + test('pptx: slides, zoom and the slide in view; no thumbnails, zoom or Present button', async () => { - const v = await viewer({ src: 'samples/sample.pptx', headless: true }) + const v = await viewer({ controller: true, src: 'samples/sample.pptx', headless: true }) const { page } = v expect(await page.locator('.de-thumbs').count()).toBe(0) expect(await page.locator('.de-zoom').count()).toBe(0) @@ -101,7 +150,7 @@ describe('controller and headless mode', () => { }) test('with chrome: the controller still follows the view', async () => { - const v = await viewer({ src: 'samples/sample.docx' }) + const v = await viewer({ controller: true, src: 'samples/sample.docx' }) const { page } = v expect(await page.locator('.de-bar').count()).toBe(1) await until(v, "s.kind === 'docx' && s.zoom") diff --git a/src/embed.ts b/src/embed.ts index 5053a85..d83c0cc 100644 --- a/src/embed.ts +++ b/src/embed.ts @@ -4,7 +4,7 @@ import './core/default-worker' import { DocViewer, type DocViewerProps } from './react/DocViewer' import type { Icons } from './react/edit/Toolbar' import type { StringsOverride } from './react/strings' -import { ViewerController } from './react/controller' +import { createViewerController, type ViewerController } from './react/controller' export type MountOptions = Omit @@ -22,14 +22,16 @@ export interface MountedViewer { export function mount(el: HTMLElement, options: MountOptions): MountedViewer { let root: Root | null = createRoot(el) let props = options - const controller = options.controller ?? new ViewerController() + const ownController = createViewerController() + let controller = options.controller ?? ownController const shadow = el.getRootNode() instanceof ShadowRoot ? (el.getRootNode() as ShadowRoot) : undefined const render = () => root?.render(createElement(DocViewer, { ...props, controller, styleTarget: shadow })) render() return { - controller, + get controller() { return controller }, update(next) { props = { ...props, ...next } + controller = props.controller ?? ownController render() }, destroy() { @@ -56,7 +58,7 @@ export class OfficeViewerElement extends HTMLElement { private _icons?: Icons private _strings?: StringsOverride /** the viewer's state and commands, the same object for the element's whole life */ - readonly controller = new ViewerController() + readonly controller = createViewerController() get file() { return this._file diff --git a/src/index.ts b/src/index.ts index 901fb38..a979ad8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,7 +13,7 @@ export { THEME_TOKENS, createTheme, themeStyle, useThemeRoot, type Theme, type T export { 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, LOCALES, en, de, type Strings, type StringsOverride, type Locale } from './react/strings' -export { ViewerController, createViewerController, useViewerState, type ViewerState, type ViewerOutline, type OutlineItem } from './react/controller' +export { type ViewerController, createViewerController, useViewerState, type ViewerState, type ViewerOutline, type OutlineItem } from './react/controller' export { DocumentClient, setDefaultWorker, type OpenOptions } from './core/worker/client' export type { DocSource } from './core/source' diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx index 3ee34ea..1e197cb 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -8,7 +8,7 @@ import { StatusContext } from './common/Status' import { ConfirmDialog, PromptDialog, Toast } from './common/Dialog' import { download, Icon, IconsProvider, type Icons } from './edit/Toolbar' import { UIComponentsProvider, type UIComponents } from './ui' -import { ViewerController } from './controller' +import { createViewerController, internalController, type ViewerController } from './controller' import { DetailsDialog } from './file/DetailsDialog' import { FileMenu, useFileActions, type FileMenuItem } from './file/FileMenu' import { importFile, type Imported } from './file/importFile' @@ -168,8 +168,8 @@ function Viewer(props: DocViewerProps) { const headless = !!props.headless const toolbar = props.toolbar ?? !headless // without a controller from the host the viewer keeps its own: the view publishes to one either way - const ownCtl = useMemo(() => new ViewerController(), []) - const ctl = props.controller ?? ownCtl + const ownCtl = useMemo(() => createViewerController(), []) + const ctl = internalController(props.controller ?? ownCtl) const root = useThemeRoot(theme, style) const { allowEdit = true, allowSave = true, allowDownload = true, fileMenu = true, allowOpen = true, captureSelectAll = true, onSave, onDirtyChange } = props const [editing, setEditing] = useState(!!props.editable) @@ -373,7 +373,7 @@ function Viewer(props: DocViewerProps) { ) const selectAll = useRef<(() => void) | null>(null) // next to its source, the document is a preview: it is edited through the source - const docEditable = editing && canEdit && !codeShown + const docEditable = editing && allowEdit && canEdit && !codeShown const api = useMemo( () => ({ bar: barEl, editable: docEditable, setDirty: setDocDirty, save, canDownload: allowDownload, client, fileOps, selectAll, ctl, headless }), [barEl, docEditable, setDocDirty, save, allowDownload, client, ctl, headless], @@ -468,14 +468,14 @@ function Viewer(props: DocViewerProps) { setOpened(doc) if (edit) setEditing(true) }, []) - const canOpen = fileMenu && allowOpen && !props.collab + const canOpen = allowOpen && !props.collab const fileActions = useFileActions({ kind: client?.kind, base: baseName, canOpen, - canImport: fileMenu && allowEdit && canEdit, - canSave: fileMenu && canSave, - canDownload: fileMenu && allowDownload && !!client, + canImport: allowOpen && allowEdit && canEdit, + canSave, + canDownload: allowDownload && !!client, ops: fileOps, create: (kind: DocKind) => replace(t.bar.replaceNew(t.newWhat[kind]), () => { @@ -538,12 +538,12 @@ function Viewer(props: DocViewerProps) { // ---- controller: the viewer's part of the state, and its commands ---- const editAllowed = allowEdit && !readOnly && !codeShown useEffect(() => { - ctl.update({ kind: client?.kind ?? null, loading: busy, editing: docEditable, canEdit: editAllowed && canEdit, dirty, saving }) + ctl.update({ kind: client?.kind ?? null, loading: busy, editing: docEditable, canEdit: !!client && editAllowed && canEdit, dirty, saving }) }, [ctl, client, busy, docEditable, editAllowed, canEdit, dirty, saving]) const commands = useRef({ editAllowed, save, fileActions, cmCtl }) commands.current = { editAllowed, save, fileActions, cmCtl } useEffect(() => { - ctl.attachViewer({ + return ctl.attachViewer({ setEditing: (on) => { if (!on || commands.current.editAllowed) setEditing(on) }, @@ -551,7 +551,6 @@ function Viewer(props: DocViewerProps) { fileAction: (id) => commands.current.fileActions.run(id), toggleComments: (open) => commands.current.cmCtl?.toggle(open), }) - return () => ctl.attachViewer(null) }, [ctl]) let body: ReactNode diff --git a/src/react/common/Slots.tsx b/src/react/common/Slots.tsx index b44d09c..bfcc2cc 100644 --- a/src/react/common/Slots.tsx +++ b/src/react/common/Slots.tsx @@ -3,7 +3,7 @@ import { createPortal } from 'react-dom' import { ToolbarRow } from '../edit/Toolbar' import type { DocumentClient } from '../../core/worker/client' import type { Printable } from '../file/print' -import type { ViewerController } from '../controller' +import type { InternalViewerController } from '../controller' /** What the active view offers to the File menu. */ export interface FileOps { @@ -33,7 +33,7 @@ export interface ViewerApi { /** set by the mounted view (see useSelectAll): Ctrl/⌘+A */ selectAll: { current: (() => void) | null } /** the viewer's controller: the view publishes its state and registers its commands there */ - ctl: ViewerController | null + ctl: InternalViewerController | null /** the host draws the controls: the view shows no zoom, outline, sheet tabs or slide list of its own */ headless: boolean } diff --git a/src/react/controller.ts b/src/react/controller.ts index e7af907..f876d8f 100644 --- a/src/react/controller.ts +++ b/src/react/controller.ts @@ -82,7 +82,7 @@ function same(a: unknown, b: unknown): boolean { return JSON.stringify(a) === JSON.stringify(b) } -export class ViewerController { +export class InternalViewerController { private state: ViewerState = EMPTY private subs = new Set<() => void>() private watchers = new Set<() => void>() @@ -91,10 +91,11 @@ export class ViewerController { subscribe = (fn: () => void) => { const first = this.subs.size === 0 - this.subs.add(fn) + const listener = () => fn() + this.subs.add(listener) if (first) for (const w of this.watchers) w() return () => { - this.subs.delete(fn) + if (this.subs.delete(listener) && this.subs.size === 0) for (const w of this.watchers) w() } } @@ -103,7 +104,7 @@ export class ViewerController { return this.subs.size > 0 } - /** calls `fn` when the first subscriber arrives */ + /** calls `fn` when observation starts or stops */ watchObserved(fn: () => void): () => void { this.watchers.add(fn) return () => { @@ -195,20 +196,44 @@ export class ViewerController { for (const fn of this.subs) fn() } - /** @internal the mounted view's commands; null when it goes (its state is cleared) */ - attachView(c: ViewCommands | null) { + /** @internal releases only this registration, so an exiting viewer cannot detach its successor. */ + attachView(c: ViewCommands): () => void { this.view = c - if (!c) this.update(VIEW_STATE) + return () => { + if (this.view !== c) return + this.view = null + this.update(VIEW_STATE) + } } - /** @internal the viewer's commands; null when it goes (its state is cleared) */ - attachViewer(c: ViewerCommands | null) { + /** @internal releases only this registration. */ + attachViewer(c: ViewerCommands): () => void { this.viewer = c - if (!c) this.update(VIEWER_STATE) + return () => { + if (this.viewer !== c) return + this.viewer = null + this.update(VIEWER_STATE) + } } } -export const createViewerController = () => new ViewerController() +/** Host API; publishing and lifecycle methods belong to the engine. */ +export type ViewerController = Pick + +export const createViewerController = (): ViewerController => new InternalViewerController() +/** @internal controllers supplied to viewers originate from createViewerController(). */ +export const internalController = (ctl: ViewerController): InternalViewerController => ctl as InternalViewerController + +/** @internal follows both subscription transitions, including a replacement controller. */ +export function useControllerObserved(ctl: InternalViewerController | null): boolean { + return useSyncExternalStore( + (fn) => ctl?.watchObserved(fn) ?? (() => {}), + () => !!ctl?.observed, + () => false, + ) +} /** The controller's state, rendering again whenever it changes: for a host's own controls in React. */ export function useViewerState(ctl: ViewerController): ViewerState { @@ -216,12 +241,11 @@ export function useViewerState(ctl: ViewerController): ViewerState { } /** Registers a view's commands (the latest closures each render) while it is mounted. */ -export function useViewCommands(ctl: ViewerController | null, commands: ViewCommands) { +export function useViewCommands(ctl: InternalViewerController | null, commands: ViewCommands) { const latest = useLatest(commands) useEffect(() => { if (!ctl) return const call = (k: K) => ((...a: unknown[]) => (latest.current[k] as ((...x: unknown[]) => void) | undefined)?.(...a)) as ViewCommands[K] - ctl.attachView({ setZoom: call('setZoom'), goto: call('goto'), gotoPage: call('gotoPage'), undo: call('undo'), redo: call('redo'), present: call('present') }) - return () => ctl.attachView(null) + return ctl.attachView({ setZoom: call('setZoom'), goto: call('goto'), gotoPage: call('gotoPage'), undo: call('undo'), redo: call('redo'), present: call('present') }) }, [ctl, latest]) } diff --git a/src/react/file/FileMenu.tsx b/src/react/file/FileMenu.tsx index 4ffc405..426dc99 100644 --- a/src/react/file/FileMenu.tsx +++ b/src/react/file/FileMenu.tsx @@ -114,12 +114,21 @@ export function useFileActions(o: FileActionsOptions): FileActions { const exec = async (action: string) => { const c = opts.current - if (action.startsWith('new:')) return c.create(action.slice(4) as DocKind) - if (action.startsWith('extra:')) return c.extra[Number(action.slice(6))]?.onClick() + if (action.startsWith('new:')) { + const kind = action.slice(4) + if (c.canOpen && (kind === 'docx' || kind === 'xlsx' || kind === 'pptx')) c.create(kind) + return + } + if (action.startsWith('extra:')) { + const item = c.extra[Number(action.slice(6))] + if (item && !item.disabled) item.onClick() + return + } switch (action) { case 'open': { + if (!c.canOpen) return const [file] = await pickFiles(OPEN_ACCEPT, false) - if (file) c.open(file) + if (file && opts.current.canOpen) opts.current.open(file) return } case 'rename': @@ -129,12 +138,13 @@ export function useFileActions(o: FileActionsOptions): FileActions { case 'close': return c.close?.() case 'save': - return c.save() + return c.kind && c.canSave ? c.save() : undefined } const ops = c.ops.current if (action === 'import') { + if (!c.canImport || c.kind !== 'xlsx') return const [file] = await pickFiles('.csv,.tsv,.tab,.txt', false) - if (!file) return + if (!file || !opts.current.canImport) return if (!ops?.importText) throw new Error(t.common.stillLoading) await ops.importText(file, file.name.replace(/\.[^.]+$/, '').slice(0, 31) || 'Imported') return diff --git a/src/react/pptx/PptxView.tsx b/src/react/pptx/PptxView.tsx index 29012cd..ace0a5f 100644 --- a/src/react/pptx/PptxView.tsx +++ b/src/react/pptx/PptxView.tsx @@ -6,7 +6,7 @@ import { useFileOps, useViewer, useSelectAll } from '../common/Slots' import { slidesToText } from '../file/text' import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' -import { useViewCommands } from '../controller' +import { useViewCommands, useControllerObserved } from '../controller' import { getSel } from '../edit/input' import { PptxEditor } from './PptxEditor' import { PptxToolbar, type AlignTo, type Arrange, type Rotate, type SlideCmd } from './PptxToolbar' @@ -600,12 +600,7 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t const { ctl, headless } = viewer // slide titles for the outline, read only while a host reads the controller: from the slides' XML in one call // once the first slides are shown, then from each slide model an edit puts in the cache - const [observed, setObserved] = useState(() => !!ctl?.observed) - useEffect(() => { - if (!ctl) return - if (ctl.observed) setObserved(true) - return ctl.watchObserved(() => setObserved(true)) - }, [ctl]) + const observed = useControllerObserved(ctl) const [titles, setTitles] = useState([]) useEffect(() => { if (!observed) return diff --git a/src/react/xlsx/XlsxView.tsx b/src/react/xlsx/XlsxView.tsx index 2d07d0b..7fb4f94 100644 --- a/src/react/xlsx/XlsxView.tsx +++ b/src/react/xlsx/XlsxView.tsx @@ -977,7 +977,7 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g // nothing to undo or redo: the worker's history is shorter than counted (it keeps the last 200 edits) else if (kind === 'undo') store.history = { ...h, undo: 0 } else if (kind === 'redo') store.history = { ...h, redo: 0 } - viewer.ctl?.update({ canUndo: store.history.undo > 0, canRedo: store.history.redo > 0 }) + viewer.ctl?.update({ canUndo: viewer.editable && store.history.undo > 0, canRedo: viewer.editable && store.history.redo > 0 }) setDetailTick((t) => t + 1) } catch (e) { console.error('[office-engine]', e) @@ -1187,7 +1187,9 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g const redo = () => void run(client.call('xlsx.redo'), 'redo') // the controller's undo / redo: this sheet's grid runs them while it is shown useEffect(() => { - gridCommands.current = { undo, redo } + gridCommands.current = { undo: () => editable && undo(), redo: () => editable && redo() } + const h = store.history + viewer.ctl?.update({ canUndo: editable && h.undo > 0, canRedo: editable && h.redo > 0 }) }) const tsv = () => { diff --git a/test/controller.test.ts b/test/controller.test.ts index 248cf3f..eca6406 100644 --- a/test/controller.test.ts +++ b/test/controller.test.ts @@ -1,9 +1,9 @@ import { describe, expect, test } from 'bun:test' -import { createViewerController } from '../src/react/controller' +import { InternalViewerController } from '../src/react/controller' describe('viewer controller', () => { test('observed once a host subscribes; watchers hear the first subscriber only', () => { - const ctl = createViewerController() + const ctl = new InternalViewerController() let heard = 0 const stop = ctl.watchObserved(() => heard++) expect(ctl.observed).toBe(false) @@ -16,7 +16,7 @@ describe('viewer controller', () => { }) test('state changes count once each; an equal update is no change', () => { - const ctl = createViewerController() + const ctl = new InternalViewerController() let calls = 0 ctl.subscribe(() => calls++) ctl.update({ kind: 'docx', zoom: { value: 'fit', effective: 0.8 } }) @@ -29,7 +29,7 @@ describe('viewer controller', () => { }) test('commands go to the view and the viewer that registered them; without them they do nothing', async () => { - const ctl = createViewerController() + const ctl = new InternalViewerController() ctl.goto('1') ctl.setEditing(true) await ctl.save() @@ -47,7 +47,7 @@ describe('viewer controller', () => { }) test('zoom steps from the effective zoom: in from a fitted 0.8 is 0.9, out from 0.25 is nothing', () => { - const ctl = createViewerController() + const ctl = new InternalViewerController() const set: unknown[] = [] ctl.attachView({ setZoom: (z) => set.push(z) }) ctl.update({ zoom: { value: 'fit', effective: 0.8 } }) @@ -62,18 +62,49 @@ describe('viewer controller', () => { }) test('the view going clears its part of the state', () => { - const ctl = createViewerController() - ctl.attachView({}) + const ctl = new InternalViewerController() + const detach = ctl.attachView({}) ctl.update({ kind: 'pptx', page: { current: 2, count: 9 }, canUndo: true, status: 'Slide 2 of 9' }) - ctl.attachView(null) + detach() expect(ctl.snapshot()).toMatchObject({ kind: 'pptx', page: null, canUndo: false, status: '', outline: null, zoom: null }) }) test('the viewer going clears its part of the state', () => { - const ctl = createViewerController() - ctl.attachViewer({ setEditing: () => {}, save: async () => {}, fileAction: () => {}, toggleComments: () => {} }) + const ctl = new InternalViewerController() + const detach = ctl.attachViewer({ setEditing: () => {}, save: async () => {}, fileAction: () => {}, toggleComments: () => {} }) ctl.update({ kind: 'docx', loading: true, editing: true, canEdit: true, dirty: true, saving: true }) - ctl.attachViewer(null) + detach() expect(ctl.snapshot()).toMatchObject({ kind: null, loading: false, editing: false, canEdit: false, dirty: false, saving: false }) }) + test('an exiting viewer cannot detach the newer viewer or view', () => { + const ctl = new InternalViewerController() + const log: string[] = [] + const commands = (id: string) => ({ setEditing: () => log.push(id), save: async () => {}, fileAction: () => {}, toggleComments: () => {} }) + const oldViewer = ctl.attachViewer(commands('old')) + const oldView = ctl.attachView({ undo: () => log.push('old undo') }) + const newViewer = ctl.attachViewer(commands('new')) + const newView = ctl.attachView({ undo: () => log.push('new undo') }) + ctl.update({ kind: 'xlsx', canUndo: true, status: 'new' }) + oldView(); oldViewer() + ctl.setEditing(true); ctl.undo() + expect(log).toEqual(['new', 'new undo']) + expect(ctl.snapshot()).toMatchObject({ kind: 'xlsx', canUndo: true, status: 'new' }) + newView(); newViewer() + expect(ctl.snapshot()).toMatchObject({ kind: null, canUndo: false, status: '' }) + }) + + test('observation follows the last unsubscribe, resubscribe and duplicate callbacks', () => { + const ctl = new InternalViewerController() + const observed: boolean[] = [] + const stop = ctl.watchObserved(() => observed.push(ctl.observed)) + const fn = () => {} + const a = ctl.subscribe(fn), b = ctl.subscribe(fn) + a(); a() + expect(ctl.observed).toBe(true) + b() + const c = ctl.subscribe(fn) + c(); stop() + expect(observed).toEqual([true, false, true, false]) + }) + }) From acd8b168bfcf1491946aebba5c39e5e30923ab7f Mon Sep 17 00:00:00 2001 From: Markus Date: Tue, 17 Nov 2026 21:27:05 +0100 Subject: [PATCH 15/19] feat(i18n): make German opt-in and localize drawing placeholders --- README.md | 2 +- docs/api.md | 64 +++++++++++++++++++++------ e2e/app/embed.html | 2 + e2e/app/main.tsx | 11 +++-- e2e/embed.spec.ts | 8 ++-- e2e/locale-docx.spec.ts | 4 +- e2e/locale-xlsx.spec.ts | 2 +- e2e/locale.spec.ts | 21 ++++----- package.json | 4 ++ src/embed.ts | 4 +- src/index.ts | 2 +- src/locales/de.ts | 2 + src/react/DocViewer.tsx | 2 +- src/react/strings/de.ts | 83 ++++++++++++++++++++++-------------- src/react/strings/en.ts | 17 ++++++++ src/react/strings/index.tsx | 8 ++-- src/react/xlsx/XlsxView.tsx | 2 +- src/react/xlsx/drawings.tsx | 12 +++--- test/strings-render.test.tsx | 29 ++++++++++++- test/strings.test.ts | 39 +++++++++++------ vite.config.ts | 2 +- 21 files changed, 219 insertions(+), 101 deletions(-) create mode 100644 src/locales/de.ts diff --git a/README.md b/README.md index c7c8054..df11a06 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,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; English by default, German shipped with Swiss spelling and `de-CH` number/date formatting (`locale="de"`; see [UI texts](docs/api.md#ui-texts)), any text replaceable through `strings` +- **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 parsing-worker messages are not translated by the table. @@ -244,7 +282,7 @@ Document content stays in its original language. Default new sheet names, the au ``` -``: attributes `src`, `name`, `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `locale="de"`, `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`; properties `.file = File`, `.icons` (map or resolver, as `icons` above) and `.strings = { … }` (see [UI texts](#ui-texts)); events `load`, `error`, `comment` (`detail`: a `CommentEvent`). +``: attributes `src`, `name`, `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `locale="en"`, `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/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 @@