From 1c0faf07f6747a41c07e2031c7d77d78acefe503 Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 14 Nov 2026 11:08:48 +0100 Subject: [PATCH 01/41] 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/41] 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 8409cf9726c7b5ea6252d9bf9f7b3428ec659f4b Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:03:10 +0100 Subject: [PATCH 15/41] fix(ui): measure host controls and preserve prompt and portal actions --- docs/theming.md | 27 ++++++--- e2e/app/main.tsx | 2 +- e2e/app/ui.html | 5 ++ e2e/app/ui.tsx | 53 +++++++++++++++++ e2e/ui-layout.spec.ts | 110 ++++++++++++++++++++++++++++++++++++ src/react/common/Dialog.tsx | 8 +-- src/react/edit/Toolbar.tsx | 71 +++++++++++++---------- src/react/styles.css | 2 +- src/react/ui.tsx | 5 +- test/ui.test.tsx | 51 +++++++++++++---- 10 files changed, 277 insertions(+), 57 deletions(-) create mode 100644 e2e/app/ui.html create mode 100644 e2e/app/ui.tsx create mode 100644 e2e/ui-layout.spec.ts diff --git a/docs/theming.md b/docs/theming.md index 28be5f6..7a70f2f 100644 --- a/docs/theming.md +++ b/docs/theming.md @@ -110,13 +110,20 @@ const components: Partial = { Button: ViewerButton, Separator: Vie /> ``` -| 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`, `extra` for an auxiliary action such as Remove link, `primary`, `submit`, `autoFocus`), `onSubmit` (the body is a form), `onClose` (Escape, backdrop) | -| `Toast` | short messages at the bottom | `text` (the viewer removes it after a few seconds) | +| Component | Used for | Props | +| ----------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Button` | every toolbar button, the toggles that open color, table and border pickers, the overflow button | `ButtonProps`: `title`, `icon` (resolved through `icons`), `iconName`, `label`, `children`, `active`, `expanded`, `disabled`, `wide`, `onClick`, `onMouseDown`, `className` (the built-in classes) | +| `Select` | font, style, format and menu dropdowns | `SelectProps`: `title`, `options` (`DropOption`: `value`, `label`, `hint`, `icon`, `disabled`, `sep`, `head`, `style`), `value` (undefined for a command menu), `onChange`, `label` (`null` hides the label for an icon-only trigger), `icon` (an `IconName`, not a resolved node), `className` (extra trigger class), `placeholder`, `width`, `menuWidth`, `disabled`, `alignRight` | +| `Separator` | between toolbar groups | none | +| `Dialog` | prompts (link, rename, …) and confirmations | `DialogProps`: `title`, `kind` (`'alert'` for a question), `children` (the body), `actions` (`label`, `onClick`, `extra` for an auxiliary action such as Remove link, `primary`, `submit`, `autoFocus`), `onSubmit` (the body is a form), `onClose` (Escape, backdrop) | +| `Toast` | short messages at the bottom | `text` (the viewer removes it after a few seconds) | + +The font-size input and its list (`SizeBox`), Page setup, Header / footer and Details dialogs, and the buttons +inside border pickers retain the built-in markup. `components` replaces the controls listed above. + +A host Dialog can put its footer outside the form: call the action's `onClick` from a regular button. Inside +a form, render `submit` actions as submit buttons and let `onSubmit` run them; do not also call their `onClick`, +which would submit twice. Keep `onClick` for the other actions. The document must keep the focus while a toolbar control is used, or the command loses its selection: @@ -125,6 +132,12 @@ The document must keep the focus while a toolbar control is used, or the command The built-in one captures the keys at the window while open. The overflow menu measures each toolbar item from a wrapper of its own, so a host component needs no ref. +It measures the More button in the same pass and remeasures when Button, Select or Separator is replaced. + +Host Select lists rendered with React's `createPortal` remain inside their surrounding overflow menu or popover +for outside-click handling. The portal must belong to the same React tree as the Select. An independently +mounted React root or a non-React overlay has no such ownership path; render that list inside the Select's DOM +subtree instead. A host `Select` can render its trigger and option icons with the exported `Icon`: `` (when `option.icon` is set). It uses the viewer's `icons` overrides and falls back to the built-in SVGs. diff --git a/e2e/app/main.tsx b/e2e/app/main.tsx index 50e41cc..f3ffbb2 100644 --- a/e2e/app/main.tsx +++ b/e2e/app/main.tsx @@ -51,7 +51,7 @@ const components: Partial = { Separator: () => , Dialog: (p) => { const actions = p.actions.map((a, i) => ( - )) diff --git a/e2e/app/ui.html b/e2e/app/ui.html new file mode 100644 index 0000000..46c8778 --- /dev/null +++ b/e2e/app/ui.html @@ -0,0 +1,5 @@ + + + UI regression fixture +
+ diff --git a/e2e/app/ui.tsx b/e2e/app/ui.tsx new file mode 100644 index 0000000..178a872 --- /dev/null +++ b/e2e/app/ui.tsx @@ -0,0 +1,53 @@ +import { useEffect, useState } from 'react' +import { createRoot } from 'react-dom/client' +import { createPortal } from 'react-dom' +import { PromptDialog } from '../../src/react/common/Dialog' +import { Btn, Dropdown, Pop, ToolbarRow } from '../../src/react/edit/Toolbar' +import { OfficeUIProvider, type ButtonProps, type DialogProps, type SelectProps } from '../../src/react/ui' +import '../../src/react/styles.css' + +window.__events = [] +const noop = () => {} +function Button(p: ButtonProps) { + return +} +function WideButton(p: ButtonProps) { + return )} + +} +function PortalSelect(p: SelectProps) { + const [open, setOpen] = useState(false) + return <> + + {open && createPortal(
+ {p.options.map((o) => )} +
, document.body)} + +} +const picker = (title: string) => window.__events.push({ type: 'pick', value, title })} /> +function App() { + const [wide, setWide] = useState(false) + const [tick, setTick] = useState(0) + return +
+ + + + {Array.from({ length: 17 }, (_, i) => )} +
+ {Array.from({ length: 8 }, (_, i) => )} + {picker('Overflow picker')} +
+ {() => picker('Popover picker')} + window.__events.push({ type: 'submit', value }) }} onClose={() => window.__events.push({ type: 'close' })} /> +
+
+} +createRoot(document.getElementById('root')!).render() diff --git a/e2e/ui-layout.spec.ts b/e2e/ui-layout.spec.ts new file mode 100644 index 0000000..97c5047 --- /dev/null +++ b/e2e/ui-layout.spec.ts @@ -0,0 +1,110 @@ +import { expect, test } from 'bun:test' +import { useBrowser, viewer } from './harness' + +useBrowser() + +test('More keeps its natural width in a 600px row and replacement host components are remeasured', async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const more = v.page.locator('.de-ebar').first().locator('.de-ebar-morewrap button') + await more.waitFor() + const bounds = () => v.page.locator('.de-ebar').first().evaluate((row) => { + const wrapper = row.querySelector('.de-ebar-morewrap')! + const clone = wrapper.cloneNode(true) as HTMLElement + clone.style.cssText = 'position:absolute;width:max-content;visibility:hidden' + row.append(clone) + const natural = clone.getBoundingClientRect().width + clone.remove() + return { + natural, width: wrapper.getBoundingClientRect().width, + right: wrapper.getBoundingClientRect().right, edge: row.getBoundingClientRect().right - 8, + cut: row.querySelectorAll(':scope > [data-i]').length, + } + }) + const before = await bounds() + console.info('initial More bounds', JSON.stringify(before)) + await v.page.getByText('Replace components', { exact: true }).click() + const after = await bounds() + console.info('replacement More bounds', JSON.stringify(after)) + expect(before.width).toBeCloseTo(before.natural, 1) + expect(before.right).toBeLessThanOrEqual(before.edge + 1) + expect(after.cut).toBeLessThan(before.cut) + expect(after.width).toBeCloseTo(after.natural, 1) + expect(after.right).toBeLessThanOrEqual(after.edge + 1) + // Unrelated host rerenders must not read toolbar item geometry again. + await v.page.evaluate(() => { + const original = Element.prototype.getBoundingClientRect + Element.prototype.getBoundingClientRect = function () { + if (this.matches('.de-ebar > [data-i], .de-ebar-morewrap')) window.__events.push({ type: 'measure' }) + return original.call(this) + } + }) + await v.page.getByText('Rerender 0', { exact: true }).click() + console.info('geometry reads on unrelated rerender', (await v.events('measure')).length) + expect(await v.events('measure')).toHaveLength(0) + await more.click() + expect(await v.page.locator('.de-ebar-more button').count()).toBeGreaterThan(0) + expect(v.errors).toEqual([]) +}) + +test('a delayed host dialog focuses and selects the prompt input', async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const input = v.page.getByRole('dialog').locator('input') + await input.waitFor() + const focus = await input.evaluate((el: HTMLInputElement) => ({ focused: document.activeElement === el, start: el.selectionStart, end: el.selectionEnd })) + console.info('delayed prompt focus/selection', JSON.stringify(focus)) + expect(focus).toEqual({ focused: true, start: 0, end: 6 }) + expect(v.errors).toEqual([]) +}) + +test('a prompt host footer outside the form and Enter each submit once', async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const input = v.page.getByRole('dialog').locator('input') + await input.waitFor() + expect(await v.page.getByRole('button', { name: 'OK', exact: true }).evaluate((el) => !!el.closest('form'))).toBe(false) + await input.fill('From footer') + await v.page.getByRole('button', { name: 'OK', exact: true }).click() + console.info('external footer submit events', JSON.stringify(await v.events('submit'))) + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'From footer' }]) + expect(await v.events('close')).toHaveLength(1) + await input.fill('From form') + await input.press('Enter') + console.info('footer then Enter submit events', JSON.stringify(await v.events('submit'))) + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'From footer' }, { type: 'submit', value: 'From form' }]) + expect(await v.events('close')).toHaveLength(2) + expect(v.errors).toEqual([]) +}) + +test('the built-in prompt submits once per primary click or Enter', async () => { + const v = await viewer({ defaultDialog: true }, { page: 'ui.html', wait: false }) + const input = v.page.getByRole('dialog').locator('input') + await input.fill('Click') + await v.page.getByRole('button', { name: 'OK', exact: true }).click() + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'Click' }]) + await input.fill('Enter') + await input.press('Enter') + expect(await v.events('submit')).toEqual([{ type: 'submit', value: 'Click' }, { type: 'submit', value: 'Enter' }]) + expect(await v.events('close')).toHaveLength(2) + expect(v.errors).toEqual([]) +}) + +for (const placement of ['overflow', 'popover'] as const) { + test(`a React-portaled host Select in ${placement} survives mousedown and delivers onChange`, async () => { + const v = await viewer({}, { page: 'ui.html', wait: false }) + const title = placement === 'overflow' ? 'Overflow picker' : 'Popover picker' + const parent = placement === 'overflow' ? v.page.locator('[data-portal-overflow] .de-ebar-more') : v.page.locator('.de-tb-pop').last() + if (placement === 'overflow') await v.page.locator('[data-portal-overflow] .de-ebar-morewrap > button').click() + else await v.page.getByRole('button', { name: 'Open popover', exact: true }).click() + await v.page.getByRole('button', { name: title, exact: true }).click() + const option = v.page.getByRole('option', { name: 'Choose option' }) + await option.waitFor() + expect(await option.evaluate((el) => !!el.closest('.de-ebar-more, .de-tb-pop'))).toBe(false) + await option.click() + console.info(`${placement} portal after option click`, JSON.stringify({ parentVisible: await parent.isVisible(), events: await v.events('pick') })) + expect(await v.events('pick')).toEqual([{ type: 'pick', value: 'chosen', title }]) + expect(await parent.isVisible()).toBe(true) + await v.page.getByText('Outside with stopped propagation', { exact: true }).click() + await parent.waitFor({ state: 'detached', timeout: 5000 }) + expect(await parent.count()).toBe(0) + expect(v.errors).toEqual([]) + }) +} diff --git a/src/react/common/Dialog.tsx b/src/react/common/Dialog.tsx index d9a8ad8..0ca8de9 100644 --- a/src/react/common/Dialog.tsx +++ b/src/react/common/Dialog.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState, type ReactNode } from 'react' +import { useCallback, useEffect, useState, type ReactNode } from 'react' import { useStrings } from '../strings' import { DefaultDialog, DefaultToast, useHostUI, type DialogAction } from '../ui' @@ -21,9 +21,7 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () const t = useStrings() const Dialog = useHostUI().Dialog ?? DefaultDialog const [v, setV] = useState(spec.initial ?? '') - const ref = useRef(null) - useEffect(() => { - const el = ref.current + const ref = useCallback((el: HTMLInputElement | HTMLTextAreaElement | null) => { el?.focus() el?.select() }, []) @@ -45,7 +43,7 @@ export function PromptDialog({ spec, onClose }: { spec: PromptSpec; onClose: () ] : []), { label: t.common.cancel, onClick: onClose }, - { label: spec.ok ?? t.common.ok, primary: true, submit: true }, + { label: spec.ok ?? t.common.ok, primary: true, submit: true, onClick: done }, ] return ( diff --git a/src/react/edit/Toolbar.tsx b/src/react/edit/Toolbar.tsx index 88189ea..fbafebe 100644 --- a/src/react/edit/Toolbar.tsx +++ b/src/react/edit/Toolbar.tsx @@ -3,6 +3,7 @@ import { createContext, Fragment, isValidElement, + useCallback, useContext, useEffect, useLayoutEffect, @@ -228,19 +229,33 @@ function PopBox(props: { className?: string; children: ReactNode; onMouseDown?: ) } -/** closes a popup on outside mousedown (shadow-DOM safe: uses the composed path) */ +/** Closes on outside mousedown; attach the returned capture handler to the popup's wrapper for React portals. */ export function useDismiss(ref: RefObject, open: boolean, close: () => void) { const cb = useRef(close) + const insideEvents = useRef(new WeakSet()) cb.current = close + const onMouseDownCapture = useCallback((e: React.MouseEvent) => { + insideEvents.current.add(e.nativeEvent) + }, []) useEffect(() => { if (!open) return + let active = true const on = (e: MouseEvent) => { const el = ref.current - if (el && !e.composedPath().includes(el)) cb.current() + if (!el || e.composedPath().includes(el)) return + // React capture follows the logical tree through portals. Wait for it even if bubbling is stopped. + setTimeout(() => { + if (active && !insideEvents.current.has(e)) cb.current() + insideEvents.current.delete(e) + }, 0) } window.addEventListener('mousedown', on, true) - return () => window.removeEventListener('mousedown', on, true) + return () => { + active = false + window.removeEventListener('mousedown', on, true) + } }, [open, ref]) + return onMouseDownCapture } function DefaultButton(props: ButtonProps) { @@ -328,7 +343,7 @@ function DefaultSelect(props: SelectProps) { const check = props.value !== undefined const sel = check ? options.findIndex((o) => o.value === props.value) : -1 const current = sel >= 0 ? options[sel] : undefined - useDismiss(ref, open, () => setOpen(false)) + const onMouseDownCapture = useDismiss(ref, open, () => setOpen(false)) const pick = (o: DropOption | undefined) => { if (!o || o.disabled) return @@ -397,7 +412,7 @@ function DefaultSelect(props: SelectProps) { const label = props.label !== undefined ? props.label : (current?.label ?? props.placeholder ?? '') return ( - + diff --git a/test/ui.test.tsx b/test/ui.test.tsx index 61e41ce..aa38434 100644 --- a/test/ui.test.tsx +++ b/test/ui.test.tsx @@ -1,10 +1,10 @@ import { describe, expect, test } from 'bun:test' -import type { ReactNode } from 'react' +import type { ReactElement, ReactNode } from 'react' import { renderToStaticMarkup } from 'react-dom/server' import type { Icon as PublicIcon } from '../src' import { ConfirmDialog, PromptDialog, Toast } from '../src/react/common/Dialog' import { Btn, ColorBtn, Dropdown, Icon, Pop, Sep } from '../src/react/edit/Toolbar' -import { OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogProps, type SelectProps, type UIComponents } from '../src/react/ui' +import { DefaultDialog, OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogProps, type SelectProps, type UIComponents } from '../src/react/ui' const seen: { button: ButtonProps[]; select: SelectProps[]; dialog: DialogProps[] } = { button: [], select: [], dialog: [] } const host: Partial = { @@ -44,15 +44,16 @@ describe('UI components', () => { expect(html(, null)).toBe('') expect(html(, null)).toContain('class="de-dd"') expect(html(, null)).toBe('
Saved
') - expect(html(, null)).toBe( - '
', - ) - expect(html(, null)).toBe( - '
', - ) - expect(html(, null)).toBe( - '
Delete?
Gone for good
', - ) + const prompt = html(, null) + expect(prompt).toContain('role="dialog" aria-label="Link"') + expect(prompt).toContain('') + expect([...prompt.matchAll(/]*>([^<]*)<\/button>/g)].map((m) => m[1])).toEqual(['Remove link', 'Cancel', 'OK']) + expect(prompt).toContain('') + const notes = html(, null) + expect(notes).toContain('') + const confirm = html(, null) + expect(confirm).toContain('role="alertdialog" aria-label="Delete?"') + expect(confirm).toContain('') }) test('Button gets title, resolved icon, state, the engine classes and the focus-keeping mouse down', () => { @@ -83,6 +84,8 @@ describe('UI components', () => { expect(html()).toBe('
') expect(html()).toBe('2') expect(seen.select[0]).toMatchObject({ title: 'Style', value: 'b' }) + html() + expect(seen.select[1]).toMatchObject({ label: null, icon: 'bold', className: 'host-trigger' }) }) test('dialogs: prompt submits through its primary action, confirm is an alert', () => { @@ -101,6 +104,31 @@ describe('UI components', () => { expect(confirm.actions.at(-1)).toMatchObject({ label: 'Delete', primary: true, autoFocus: true }) }) + + test('a host footer outside the form can invoke the prompt primary action', () => { + const values: string[] = [] + let closes = 0 + seen.dialog.length = 0 + html( values.push(v) }} onClose={() => closes++} />) + seen.dialog[0].actions.find((a) => a.primary)!.onClick!() + expect(values).toEqual(['Report']) + expect(closes).toBe(1) + }) + + test('the default form submits once without also invoking the submit action callback', () => { + let submissions = 0 + let clicks = 0 + const tree = DefaultDialog({ title: 'Rename', children: null, onClose: noop, onSubmit: () => submissions++, actions: [{ label: 'OK', submit: true, onClick: () => clicks++ }] }) + const form = tree.props.children as ReactElement<{ onSubmit: (e: { preventDefault: () => void }) => void; children: ReactElement<{ children: ReactElement[] }> }> + const actions = form.props.children.props.children[2] as ReactElement<{ children: ReactElement<{ onClick?: () => void; type: string }>[] }> + const button = actions.props.children[0] + expect(button.props.type).toBe('submit') + button.props.onClick?.() + form.props.onSubmit({ preventDefault: noop }) + expect(submissions).toBe(1) + expect(clicks).toBe(0) + }) + test('host Select can render option icons through the public Icon export and host icon provider', () => { // The root entry includes Vite worker imports; check its public type without loading it in Bun. const OptionIcon: typeof PublicIcon = Icon @@ -129,4 +157,5 @@ describe('UI components', () => { ) expect(out).toBe('innert') }) + }) From 695d0cea614574c2e03ee80946b1323eb4f6004d Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:03:10 +0100 Subject: [PATCH 16/41] fix(ui): inherit nested provider strings and defined components --- docs/theming.md | 6 ++++-- src/react/ui.tsx | 6 +++++- test/ui.test.tsx | 31 ++++++++++++++++++++++++++++++- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/docs/theming.md b/docs/theming.md index 7a70f2f..688df4e 100644 --- a/docs/theming.md +++ b/docs/theming.md @@ -70,14 +70,16 @@ gives the class name and style their root needs: ```tsx const root = useThemeRoot(theme) return ( - +
) ``` `OfficeUIProvider` carries what `DocViewer` takes as `icons`, `components`, `locale` and `strings` to views mounted on -their own. +their own. Nested providers inherit the outer texts, icons and components. Local `strings` merge key by key; +an explicit `locale` changes number/date formatting while preserving the inherited texts. Omitted or `undefined` +components and string entries preserve the outer values. ## Your own components diff --git a/src/react/ui.tsx b/src/react/ui.tsx index d9e8200..76c7b38 100644 --- a/src/react/ui.tsx +++ b/src/react/ui.tsx @@ -94,7 +94,11 @@ const UIContext = createContext>({}) /** Replaces UI components for everything below it; an outer provider's components stay for those left out. */ export function UIComponentsProvider({ components, children }: { components?: Partial; children?: ReactNode }) { const outer = useContext(UIContext) - const value = useMemo(() => (components ? { ...outer, ...components } : outer), [outer, components]) + const value = useMemo(() => { + if (!components) return outer + const defined = Object.fromEntries(Object.entries(components).filter(([, component]) => component !== undefined)) + return { ...outer, ...defined } + }, [outer, components]) return {children} } diff --git a/test/ui.test.tsx b/test/ui.test.tsx index aa38434..e1e4f1c 100644 --- a/test/ui.test.tsx +++ b/test/ui.test.tsx @@ -4,6 +4,8 @@ import { renderToStaticMarkup } from 'react-dom/server' import type { Icon as PublicIcon } from '../src' import { ConfirmDialog, PromptDialog, Toast } from '../src/react/common/Dialog' import { Btn, ColorBtn, Dropdown, Icon, Pop, Sep } from '../src/react/edit/Toolbar' +import { useStrings, type Strings } from '../src/react/strings' +import { de } from '../src/locales/de' import { DefaultDialog, OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogProps, type SelectProps, type UIComponents } from '../src/react/ui' const seen: { button: ButtonProps[]; select: SelectProps[]; dialog: DialogProps[] } = { button: [], select: [], dialog: [] } @@ -37,6 +39,11 @@ const host: Partial = { /** renders with the host components, or with `null` with the built-in ones */ const html = (node: ReactNode, components: Partial | null = host) => renderToStaticMarkup({node}) const noop = () => {} +const texts: Strings[] = [] +function TextProbe() { + texts.push(useStrings()) + return null +} describe('UI components', () => { test('without host components the built-in markup is unchanged', () => { @@ -149,7 +156,7 @@ describe('UI components', () => { test('nested providers: inner components win, the outer ones stay for the rest', () => { const out = renderToStaticMarkup( - inner }}> + inner, Toast: undefined }}> @@ -158,4 +165,26 @@ describe('UI components', () => { expect(out).toBe('innert') }) + test('nested OfficeUIProvider inherits texts and merges only defined string overrides', () => { + texts.length = 0 + renderToStaticMarkup( + + + + + + , + ) + expect(texts[1]).toBe(texts[0]) + expect(texts[2].locale).toBe('de-CH') + expect(texts[2].common.ok).toBe('Outer OK') + expect(texts[2].common.cancel).toBe('Inner cancel') + expect(texts[2].file.menu).toBe('Ablage') + expect(texts[2].file.print).toBe(de.file.print) + expect(texts[3].locale).toBe('en-GB') + expect(texts[3].common.ok).toBe('Inner OK') + expect(texts[3].file.menu).toBe('Ablage') + expect(texts[3].file.print).toBe(de.file.print) + expect(de.common.ok).toBe('OK') + }) }) From aedfd2bce15959725d394bc72a0492fbfa518c8f Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:10:07 +0100 Subject: [PATCH 17/41] test(ui): verify rebuilt provider semantics against production ESM --- e2e/ui-built.spec.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++ test/ui.test.tsx | 2 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 e2e/ui-built.spec.ts diff --git a/e2e/ui-built.spec.ts b/e2e/ui-built.spec.ts new file mode 100644 index 0000000..256879a --- /dev/null +++ b/e2e/ui-built.spec.ts @@ -0,0 +1,46 @@ +/** Exercise host UI/provider composition against emitted ESM, after `bun run build`. */ +import { expect, test } from 'bun:test' +import { docxParas, paraText, runsOf, useBrowser, viewer } from './harness' + +useBrowser() + +test('built UI inherits German through formatting-only locales and defined components, preserving real edits', async () => { + const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'en-GB' }) + await v.page.waitForFunction(() => !!(window as any).__builtRuntime) + await v.page.evaluate(async ({ pkg, german }) => { + const { React: R, createRoot } = (window as any).__builtRuntime + const api = await import(/* @vite-ignore */ pkg) + if ('de' in api || 'LOCALES' in api) throw new Error('optional German leaked into root exports') + const de = (await import(/* @vite-ignore */ german)).de + function Button(p: any) { + return R.createElement('button', { 'data-built-host': '', 'aria-label': p.title, 'data-active': p.active ? '' : undefined, disabled: p.disabled, onMouseDown: p.onMouseDown, onClick: p.onClick }, p.icon, p.label, p.children) + } + const root = createRoot(document.getElementById('built')!) + let current: any = { src: '/samples/sample.docx', editable: true, locale: 'en-GB' } + const onLoad = (c: any) => window.__events.push({ type: 'load', kind: c.kind }) + const onError = (e: Error) => window.__events.push({ type: 'error', message: e.message }) + function render() { + root.render(R.createElement(api.OfficeUIProvider, { strings: de, components: { Button } }, + R.createElement(api.OfficeUIProvider, { locale: 'fr-FR', components: { Button: undefined } }, + R.createElement(api.DocViewer, { ...current, strings: { file: { menu: 'Ablage' } }, + onLoad, onError, + onSave: async (f: File) => { const bytes = new Uint8Array(await f.arrayBuffer()); let raw = ''; for (const b of bytes) raw += String.fromCharCode(b); window.__events.push({ type: 'save', b64: btoa(raw) }) }, + })))) + } + ;(window as any).__builtUpdate = (p: any) => { current = { ...current, ...p }; render() } + render() + }, { pkg: `/@fs${process.cwd()}/dist/index.js`, german: `/@fs${process.cwd()}/dist/locales/de.js` }) + await v.ready('docx') + expect(await v.page.locator('.de-file').innerText()).toBe('Ablage') + await v.selectText('document') + await v.page.locator('button[data-built-host][aria-label^="Fett"]').click() + await v.page.locator('button[data-built-host][aria-label^="Fett"][data-active]').waitFor() + await v.page.evaluate(() => (window as any).__builtUpdate({ locale: 'vi-VN' })) + expect(await v.page.locator('.de-file').innerText()).toBe('Ablage') + await v.page.locator('.de-bar button.de-mode', { hasText: 'Speichern' }).click() + const saved = await v.waitEvent('save') + const p = (await docxParas(Buffer.from(saved.b64 as string, 'base64'))).find((x) => paraText(x).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text.includes('document'))!.s.b).toBe(true) + expect(await v.events('load')).toHaveLength(1) + expect(v.errors).toEqual([]) +}) diff --git a/test/ui.test.tsx b/test/ui.test.tsx index e1e4f1c..36c9ae0 100644 --- a/test/ui.test.tsx +++ b/test/ui.test.tsx @@ -168,7 +168,7 @@ describe('UI components', () => { test('nested OfficeUIProvider inherits texts and merges only defined string overrides', () => { texts.length = 0 renderToStaticMarkup( - + From b24e0a47b16b15b6a99af046a29dd69dcba22697 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:14:03 +0100 Subject: [PATCH 18/41] fix(ui): retain PR6 string table keys for host compatibility --- src/react/strings/de.ts | 1 + src/react/strings/en.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/react/strings/de.ts b/src/react/strings/de.ts index 8f12b99..68369cd 100644 --- a/src/react/strings/de.ts +++ b/src/react/strings/de.ts @@ -136,6 +136,7 @@ export const de: Strings = { fontSize: 'Schriftgrad', fontSizeDown: 'Schriftgrad verkleinern', fontSizeUp: 'Schriftgrad vergrößern', + more: 'Mehr', moreTools: 'Weitere Werkzeuge', custom: 'Benutzerdefiniert', customColor: 'Benutzerdefinierte Farbe', diff --git a/src/react/strings/en.ts b/src/react/strings/en.ts index 87158f0..b282f41 100644 --- a/src/react/strings/en.ts +++ b/src/react/strings/en.ts @@ -140,6 +140,7 @@ export const en = { fontSize: 'Font size', fontSizeDown: 'Decrease font size', fontSizeUp: 'Increase font size', + more: 'More', moreTools: 'More tools', custom: 'Custom', customColor: 'Custom color', From 9f71702de0f43474b23011719963d86397982ada Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:44:24 +0100 Subject: [PATCH 19/41] test(ui): require fresh emitted packages for browser coverage --- e2e/built-package.ts | 32 ++++++++++++++++++++++++++++++++ e2e/locale-built.spec.ts | 28 ++++++++-------------------- e2e/ui-built.spec.ts | 5 ++++- 3 files changed, 44 insertions(+), 21 deletions(-) create mode 100644 e2e/built-package.ts diff --git a/e2e/built-package.ts b/e2e/built-package.ts new file mode 100644 index 0000000..346bce8 --- /dev/null +++ b/e2e/built-package.ts @@ -0,0 +1,32 @@ +/** Emitted-package suites require a complete, fresh production build. */ +import { beforeAll } from 'bun:test' +import { existsSync, readdirSync, statSync } from 'node:fs' +import { resolve } from 'node:path' + +export const packageRoot = resolve(process.env.BUILT_PACKAGE_ROOT ?? process.cwd()) +export const builtModule = (file: string) => `/@fs${packageRoot}/dist/${file}` + +function newestSource(path: string): number { + if (!existsSync(path)) return 0 + if (!statSync(path).isDirectory()) return statSync(path).mtimeMs + return Math.max(0, ...readdirSync(path).map((name) => newestSource(`${path}/${name}`))) +} + +/** An external package without sources is checked for completeness only. */ +export function useBuiltPackage() { + beforeAll(() => { + const outputs = ['index.js', 'locales/de.js', 'office-engine.worker.js', 'office-engine.embed.js', 'styles.css'] + for (const file of outputs) { + if (!existsSync(`${packageRoot}/dist/${file}`)) throw new Error(`Missing dist/${file} in ${packageRoot}; run bun run build before browser tests`) + } + const inputs = ['src', 'package.json', 'bun.lock', 'vite.config.ts', 'vite.embed.config.ts', 'vite.worker.config.ts', 'tsconfig.build.json'] + // Published packages do not include source/build inputs; a checkout must always be fresh, + // including when explicitly selected through BUILT_PACKAGE_ROOT. + if (existsSync(`${packageRoot}/src`)) { + const newest = Math.max(...inputs.map((file) => newestSource(`${packageRoot}/${file}`))) + for (const file of outputs) { + if (statSync(`${packageRoot}/dist/${file}`).mtimeMs < newest) throw new Error(`Stale dist/${file} in ${packageRoot}; run bun run build before browser tests`) + } + } + }) +} diff --git a/e2e/locale-built.spec.ts b/e2e/locale-built.spec.ts index d45e892..46905a5 100644 --- a/e2e/locale-built.spec.ts +++ b/e2e/locale-built.spec.ts @@ -1,14 +1,16 @@ /** Production-artifact checks: run `bun run build` first, as CI does before browser tests. */ -import { beforeAll, describe, expect, test } from 'bun:test' -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' import { parasToDocx, rowsToXlsx } from '../src/core/convert' import { unzipSync, zipSync, strFromU8, strToU8 } from 'fflate' import { useBrowser, viewer, type Viewer, SAMPLES } from './harness' +import { builtModule, useBuiltPackage } from './built-package' + +useBuiltPackage() useBrowser() -const packageRoot = process.env.BUILT_PACKAGE_ROOT ?? process.cwd() -const pkg = `/@fs${packageRoot}/dist/index.js` -const german = `/@fs${packageRoot}/dist/locales/de.js` +const pkg = builtModule('index.js') +const german = builtModule('locales/de.js') /** Load the emitted package in a real browser, sharing the fixture's React runtime. */ async function mount(v: Viewer, props: Record = {}, outerGerman = false) { @@ -58,20 +60,6 @@ function emfDeck() { return Buffer.from(zipSync(files)) } -// Refuse missing or stale local output rather than silently skipping or testing an old bundle. -function newestSource(path: string): number { - return Math.max(...readdirSync(path, { withFileTypes: true }).map((entry) => { - const file = `${path}/${entry.name}` - return entry.isDirectory() ? newestSource(file) : statSync(file).mtimeMs - })) -} -beforeAll(() => { - expect(existsSync(`${packageRoot}/dist/index.js`), 'Run bun run build before browser tests').toBe(true) - if (!process.env.BUILT_PACKAGE_ROOT) { - expect(statSync(`${packageRoot}/dist/index.js`).mtimeMs, 'dist is stale; run bun run build').toBeGreaterThanOrEqual(newestSource(`${packageRoot}/src`)) - } -}) - describe('built package localization', () => { for (const locale of ['en-GB', 'vi-VN', 'de-DE', 'ar-EG']) { test(`default formatting follows the ${locale} browser; invalid tags fall back`, async () => { @@ -131,7 +119,7 @@ describe('built package localization', () => { test('standalone production embed loads English and explicitly imported German', async () => { const v = await viewer({}, { page: 'built-locale.html', wait: false, locale: 'vi-VN' }) - await v.page.addScriptTag({ url: `/@fs${packageRoot}/dist/office-engine.embed.js` }) + await v.page.addScriptTag({ url: builtModule('office-engine.embed.js') }) await v.page.evaluate(() => { const el = document.createElement('office-viewer') el.setAttribute('src', '/samples/sample.docx') diff --git a/e2e/ui-built.spec.ts b/e2e/ui-built.spec.ts index 256879a..d2ad794 100644 --- a/e2e/ui-built.spec.ts +++ b/e2e/ui-built.spec.ts @@ -2,6 +2,9 @@ import { expect, test } from 'bun:test' import { docxParas, paraText, runsOf, useBrowser, viewer } from './harness' +import { builtModule, useBuiltPackage } from './built-package' + +useBuiltPackage() useBrowser() test('built UI inherits German through formatting-only locales and defined components, preserving real edits', async () => { @@ -29,7 +32,7 @@ test('built UI inherits German through formatting-only locales and defined compo } ;(window as any).__builtUpdate = (p: any) => { current = { ...current, ...p }; render() } render() - }, { pkg: `/@fs${process.cwd()}/dist/index.js`, german: `/@fs${process.cwd()}/dist/locales/de.js` }) + }, { pkg: builtModule('index.js'), german: builtModule('locales/de.js') }) await v.ready('docx') expect(await v.page.locator('.de-file').innerText()).toBe('Ablage') await v.selectText('document') From b4d8c85a8b964efbb3c7dcae6c8a9e943054fc83 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:55:52 +0100 Subject: [PATCH 20/41] test(ui): inspect parsed controls instead of serialized markup --- test/ui.test.tsx | 83 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 57 insertions(+), 26 deletions(-) diff --git a/test/ui.test.tsx b/test/ui.test.tsx index 36c9ae0..069c6e6 100644 --- a/test/ui.test.tsx +++ b/test/ui.test.tsx @@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test' import type { ReactElement, ReactNode } from 'react' import { renderToStaticMarkup } from 'react-dom/server' import type { Icon as PublicIcon } from '../src' +import { parseXml, textOf, type XEl } from '../src/core/xml' import { ConfirmDialog, PromptDialog, Toast } from '../src/react/common/Dialog' import { Btn, ColorBtn, Dropdown, Icon, Pop, Sep } from '../src/react/edit/Toolbar' import { useStrings, type Strings } from '../src/react/strings' @@ -38,6 +39,11 @@ const host: Partial = { } /** renders with the host components, or with `null` with the built-in ones */ const html = (node: ReactNode, components: Partial | null = host) => renderToStaticMarkup({node}) +/** React's static markup is XML-compatible; inspect its elements rather than its serialization. */ +const tree = (markup: string) => parseXml(`${markup}`) +const elements = (el: XEl): XEl[] => el.c.flatMap((child) => [child, ...elements(child)]) +const tagged = (el: XEl, name: string) => elements(el).filter((child) => child.n === name) +const classes = (el: XEl) => el.a.class?.split(/\s+/) ?? [] const noop = () => {} const texts: Strings[] = [] function TextProbe() { @@ -46,28 +52,41 @@ function TextProbe() { } describe('UI components', () => { - test('without host components the built-in markup is unchanged', () => { - expect(html(, null)).toStartWith('') - expect([...prompt.matchAll(/]*>([^<]*)<\/button>/g)].map((m) => m[1])).toEqual(['Remove link', 'Cancel', 'OK']) - expect(prompt).toContain('') - const notes = html(, null) - expect(notes).toContain('') - const confirm = html(, null) - expect(confirm).toContain('role="alertdialog" aria-label="Delete?"') - expect(confirm).toContain('') + test('built-in controls retain their roles, classes and action order', () => { + const button = tagged(tree(html(, null)), 'button')[0] + expect(button.a).toMatchObject({ type: 'button', title: 'Bold', 'aria-label': 'Bold', 'aria-pressed': 'true' }) + expect(classes(button)).toEqual(expect.arrayContaining(['de-tb', 'de-tb-on'])) + expect(classes(tagged(tree(html(, null)), 'span')[0])).toContain('de-tb-sep') + expect(elements(tree(html(, null))).some((el) => classes(el).includes('de-dd'))).toBe(true) + const toast = tagged(tree(html(, null)), 'div')[0] + expect(toast.a.role).toBe('status') + expect(classes(toast)).toContain('de-toast') + expect(textOf(toast)).toBe('Saved') + const prompt = tree(html(, null)) + expect(elements(prompt).find((el) => el.a.role === 'dialog')?.a['aria-label']).toBe('Link') + const actions = tagged(prompt, 'button') + expect(actions.map(textOf)).toEqual(['Remove link', 'Cancel', 'OK']) + expect(actions[0].a.type).toBe('button') + expect(classes(actions[0])).toEqual(expect.arrayContaining(['de-btn', 'de-dialog-extra'])) + expect(actions[2].a.type).toBe('submit') + expect(classes(actions[2])).toContain('de-btn-primary') + const notes = tagged(tree(html(, null)), 'textarea')[0] + expect(notes.a.rows).toBe('3') + expect(textOf(notes)).toBe('Text') + const confirm = tree(html(, null)) + expect(elements(confirm).find((el) => el.a.role === 'alertdialog')?.a['aria-label']).toBe('Delete?') + const primary = tagged(confirm, 'button').find((el) => classes(el).includes('de-btn-primary'))! + expect(primary.a.type).toBe('button') + expect(primary.a).toHaveProperty('autofocus') + expect(textOf(primary)).toBe('Delete') }) test('Button gets title, resolved icon, state, the engine classes and the focus-keeping mouse down', () => { seen.button.length = 0 const out = html() - expect(out).toContain('data-host="button"') - expect(out).toContain(' { test('Separator and Select are replaced; Select gets the options and value', () => { seen.select.length = 0 - expect(html()).toBe('
') - expect(html()).toBe('2') + expect(tagged(tree(html()), 'hr')[0].a['data-host']).toBe('sep') + const select = tagged(tree(html()), 'span')[0] + expect(select.a['data-host']).toBe('select') + expect(textOf(select)).toBe('2') expect(seen.select[0]).toMatchObject({ title: 'Style', value: 'b' }) html() expect(seen.select[1]).toMatchObject({ label: null, icon: 'bold', className: 'host-trigger' }) @@ -98,9 +119,9 @@ describe('UI components', () => { test('dialogs: prompt submits through its primary action, confirm is an alert', () => { seen.dialog.length = 0 const out = html() - expect(out).toContain('aria-label="Link"') - expect(out).toContain('value="https://x"') - expect(out).toContain('Remove link|Cancel|OK') + const rendered = tree(out) + expect(tagged(rendered, 'section')[0].a['aria-label']).toBe('Link') + expect(tagged(rendered, 'input')[0].a.value).toBe('https://x') html() const [prompt, confirm] = seen.dialog expect(prompt.onSubmit).toBeFunction() @@ -145,12 +166,18 @@ describe('UI components', () => {
, ) - expect(out).toContain('') - expect(out).toContain(' classes(el).includes('de-icon'))! + expect(custom.a['aria-hidden']).toBe('true') + expect(textOf(custom)).toBe('host bold') + expect(tagged(custom, 'b').length).toBe(1) + expect(tagged(rendered, 'svg')[0].a).toMatchObject({ width: '16', height: '16' }) }) test('Toast', () => { - expect(html()).toBe('Saved') + const toast = tagged(tree(html()), 'output')[0] + expect(toast.a['data-host']).toBe('toast') + expect(textOf(toast)).toBe('Saved') }) test('nested providers: inner components win, the outer ones stay for the rest', () => { @@ -162,7 +189,11 @@ describe('UI components', () => {
, ) - expect(out).toBe('innert') + const rendered = tree(out) + expect(textOf(tagged(rendered, 'i')[0])).toBe('inner') + const toast = tagged(rendered, 'output')[0] + expect(toast.a['data-host']).toBe('toast') + expect(textOf(toast)).toBe('t') }) test('nested OfficeUIProvider inherits texts and merges only defined string overrides', () => { From d32014672e10a00f4ba6a1dd24b45539fd5ea5ae Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 14 Nov 2026 22:36:06 +0100 Subject: [PATCH 21/41] feat(viewer): formatting state and commands through the controller One formatting API for documents, cells and slide text, so a host can draw its own formatting toolbar: `ViewerState.format` (a TextFormat: bold, italic, underline, strike, font, size, color, highlight, align, list) and `ViewerController.format(command)`. - DocxEditor and PptxEditor publish their formatting state to subscribers (`subscribeState`) beside the toolbar's `onState`; a subscriber hears the current state at once, so a controller attached while text is selected reports its format without waiting for the selection to change - src/react/edit/format.ts maps the editors' states and the active cell's CSS to TextFormat and commands to editor calls or cell format patches - the format is null while viewing, and in a presentation unless text is being edited; a command a kind has no use for does nothing - spreadsheet undo, redo and format commands through the controller run only while editing, and canUndo / canRedo follow the editing state - docs: "Formatting" under headless mode; unit tests for the mappings; e2e: bold and size through the controller in a document (saved), bold and fill on a cell, and an undo while viewing that leaves the cell as is Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 26 +++++++++++-- e2e/controller.spec.ts | 51 +++++++++++++++++++++++- src/index.ts | 2 +- src/react/controller.ts | 46 ++++++++++++++++++++-- src/react/docx/DocxEditor.ts | 10 +++++ src/react/docx/DocxView.tsx | 13 +++++++ src/react/edit/format.ts | 75 ++++++++++++++++++++++++++++++++++++ src/react/pptx/PptxEditor.ts | 23 ++++++++--- src/react/pptx/PptxView.tsx | 14 +++++++ src/react/xlsx/XlsxView.tsx | 22 ++++++++--- test/docx-edge.test.ts | 13 +++++++ test/format.test.ts | 35 +++++++++++++++++ 12 files changed, 312 insertions(+), 18 deletions(-) create mode 100644 src/react/edit/format.ts create mode 100644 test/format.test.ts diff --git a/docs/api.md b/docs/api.md index 71c2d72..59c85e1 100644 --- a/docs/api.md +++ b/docs/api.md @@ -130,12 +130,32 @@ function Viewer({ file }: { file: File }) { | `page` | `{ current, count }` from 1: the page (documents; `count` 0 while laid out) or slide in view; `null` for spreadsheets | | `outline` | `{ kind, items: [{ id, title, level, current }] }`: a document's headings, a workbook's visible sheets, a presentation's slides (titled by their title placeholder, else "Slide n") | | `status` | the status line ("Page 2 of 7 · 1,204 words", "Slide 3 of 12", "200 rows × 8 cols") | +| `format` | while editing, the formatting at the selection (`TextFormat`, below); `null` while viewing, and in a presentation unless text is being edited | Commands: `setEditing(on)`, `save()`, `undo()`, `redo()`, `zoomIn()`, `zoomOut()`, `setZoom('fit' | number)`, `goto(outlineId)`, `gotoPage(n)`, `present()` (a slideshow from the slide in view), `print()`, `fileAction(id)` (a File menu -action: `pdf`, `html`, `text:md`, `details`, `rename`…), `toggleComments(open?)`. A command the open document has no use -for does nothing. `subscribe(fn)` returns its unsubscribe; `snapshot()` the current state. Without `react`, `mount()` -returns the controller (`mounted.controller`), and `` has it as `element.controller`. +action: `pdf`, `html`, `text:md`, `details`, `rename`…), `toggleComments(open?)`, `format(command)` (below). A command the +open document has no use for does nothing. `subscribe(fn)` returns its unsubscribe; `snapshot()` the current state; +`useViewerState(ctl)` is the state in React. Without `react`, `mount()` returns the controller (`mounted.controller`), and +`` has it as `element.controller`. + +#### Formatting + +One formatting API for documents, cells and slide text, for a toolbar of your own: + +```tsx +const f = useViewerState(ctl).format + +``` + +`TextFormat`: `bold`, `italic`, `underline`, `strike`, `font`, `size` (points), `color`, `highlight` (a cell's fill in a +spreadsheet), `align` (`'left' | 'center' | 'right' | 'justify'`), `list` (`'bullet' | 'number' | null`; undefined for +cells). `FormatCommand`: `{ op: 'toggle', mark }`, `{ op: 'font', name }`, `{ op: 'size', pt }`, `{ op: 'color', color }`, +`{ op: 'highlight', color }` (`null` removes either), `{ op: 'align', align }`, `{ op: 'list', list }`, `{ op: 'clear' }`. +What a kind has no use for does nothing (lists and justified text in cells). A button must not take the focus from the +document (prevent its mouse down), or the command loses the selection. Tables, pictures, tracked changes and cell borders +stay with the built-in toolbars. Controller actions obey `allowSave`, `allowDownload` and `allowOpen` even when the File menu is hidden. `fileMenu={false}` hides that menu and its keyboard shortcuts; it does not disable a host's controller controls. diff --git a/e2e/controller.spec.ts b/e2e/controller.spec.ts index bf4073b..b53131f 100644 --- a/e2e/controller.spec.ts +++ b/e2e/controller.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test' import type { ViewerController, ViewerState } from '../src' -import { docxBlocks, fromB64, useBrowser, viewer, xlsxSheet, type Viewer } from './harness' +import { docxBlocks, docxParas, paraText, runsOf, fromB64, useBrowser, viewer, xlsxSheet, type Viewer } from './harness' useBrowser() @@ -253,6 +253,55 @@ describe('controller and headless mode', () => { expect(v.errors).toEqual([]) }) + test('docx: formatting state and commands through the controller', async () => { + const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true, headless: true }) + const { page } = v + await until(v, 's.editing') + await v.selectText('document') + await until(v, 's.format && !s.format.bold') + await page.evaluate(() => window.__ctl.format({ op: 'toggle', mark: 'bold' })) + await until(v, 's.format.bold') + await page.evaluate(() => window.__ctl.format({ op: 'size', pt: 20 })) + await until(v, 's.format.size === 20') + // headless: no Save button, the host saves through the controller + await page.evaluate(() => window.__ctl.save()) + const saved = await v.waitEvent('save') + const p = (await docxParas(fromB64(saved.b64 as string))).find((x) => paraText(x).startsWith('This document'))! + const run = runsOf(p).find((r) => r.text.includes('document'))! + expect(run.s.b).toBe(true) + expect(run.s.sz).toBe(20) + // viewing: no formatting state, and commands do nothing + await page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && s.format === null') + expect(v.errors).toEqual([]) + }) + + test("xlsx: the active cell's format through the controller", async () => { + const v = await viewer({ src: 'samples/sample.xlsx', editable: true, onSave: true, headless: true }) + const { page } = v + await page.locator('.de-grid').waitFor() + await v.typeCell('J10', '12.5') + await v.clickCell('J10') + await until(v, 's.format && !s.format.bold && s.format.list === undefined') + await page.evaluate(() => window.__ctl.format({ op: 'toggle', mark: 'bold' })) + await page.evaluate(() => window.__ctl.format({ op: 'highlight', color: '#ffff00' })) + await until(v, "s.format.bold && /255, 255, 0|ffff00/i.test(s.format.highlight ?? '')") + // lists are not a cell format: nothing happens + await page.evaluate(() => window.__ctl.format({ op: 'list', list: 'bullet' })) + + // viewing: undo is not offered and does not change the workbook + await until(v, 's.canUndo') + await page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && !s.canUndo && s.format === null') + await page.evaluate(() => window.__ctl.undo()) + await page.waitForTimeout(300) + await page.evaluate(() => window.__ctl.setEditing(true)) + await v.clickCell('J10') + // the fill was the last edit: it is still there + await until(v, "s.format && /255, 255, 0|ffff00/i.test(s.format.highlight ?? '') && s.canUndo") + expect(v.errors).toEqual([]) + }) + test('xlsx: the sheets as the outline, no tabs of its own', async () => { const v = await viewer({ controller: true, src: 'samples/sample.xlsx', headless: true }) const { page } = v diff --git a/src/index.ts b/src/index.ts index 3ca9f47..aa63a9c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,7 +13,7 @@ export { THEME_TOKENS, createTheme, themeStyle, useThemeRoot, type Theme, type T export { Icon, IconsProvider, ICON_NAMES, type DropOption, type IconName, type Icons } from './react/edit/Toolbar' export { OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogAction, type DialogProps, type SelectProps, type ToastProps, type UIComponents } from './react/ui' export { StringsProvider, useStrings, resolveStrings, en, type Strings, type StringsOverride, type Locale } from './react/strings' -export { type ViewerController, createViewerController, useViewerState, type ViewerState, type ViewerOutline, type OutlineItem } from './react/controller' +export { type ViewerController, createViewerController, useViewerState, type FormatCommand, type TextFormat, type ViewerState, type ViewerOutline, type OutlineItem } from './react/controller' export { DocumentClient, setDefaultWorker, type OpenOptions } from './core/worker/client' export type { DocSource } from './core/source' diff --git a/src/react/controller.ts b/src/react/controller.ts index 17a1167..343fcd1 100644 --- a/src/react/controller.ts +++ b/src/react/controller.ts @@ -47,8 +47,42 @@ export interface ViewerState { outline: ViewerOutline | null /** the view's status line ("Page 2 of 7 · 1,204 words") */ status: string + /** the formatting at the selection while editing (document text, the active cell, slide text being edited), else null */ + format: TextFormat | null } +/** Formatting at the selection, the same for documents, cells and slide text. */ +export interface TextFormat { + bold: boolean + italic: boolean + underline: boolean + strike: boolean + font?: string + /** points */ + size?: number + /** CSS color of the text */ + color?: string + /** text highlight; in a spreadsheet, the cell's fill */ + highlight?: string + align?: 'left' | 'center' | 'right' | 'justify' + /** the paragraph's list; undefined where there are no lists (cells) */ + list?: 'bullet' | 'number' | null +} + +/** A formatting command for the selection (`ViewerController.format`); one a view does not support does nothing. */ +export type FormatCommand = + | { op: 'toggle'; mark: 'bold' | 'italic' | 'underline' | 'strike' } + | { op: 'font'; name: string } + | { op: 'size'; pt: number } + | { op: 'color'; color: string | null } + | { op: 'highlight'; color: string | null } + | { op: 'align'; align: 'left' | 'center' | 'right' | 'justify' } + | { op: 'list'; list: 'bullet' | 'number' } + | { op: 'clear' } + +/** the editors' names for the marks */ +export const MARK_KEY = { bold: 'b', italic: 'i', underline: 'u', strike: 'strike' } as const + /** commands a mounted view runs (each optional: a spreadsheet has no zoom) */ export interface ViewCommands { setZoom?(z: Zoom): void @@ -57,6 +91,7 @@ export interface ViewCommands { undo?(): void redo?(): void present?(): void + format?(cmd: FormatCommand): void } /** commands the viewer runs */ @@ -67,7 +102,7 @@ export interface ViewerCommands { toggleComments(open?: boolean): void } -type ViewState = Pick +type ViewState = Pick type ViewerPublication = Omit /** Internal, document-scoped publication and command registration. Never part of the host API. */ @@ -80,7 +115,7 @@ export interface ViewController { } /** the view's part of the state, cleared when a view goes */ -const VIEW_STATE = { canUndo: false, canRedo: false, zoom: null, page: null, outline: null, status: '' } as const +const VIEW_STATE = { canUndo: false, canRedo: false, zoom: null, page: null, outline: null, status: '', format: null } as const /** the viewer's part of the state, cleared when the viewer goes, so a controller that outlives it shows no document */ const VIEWER_STATE = { kind: null, loading: false, editing: false, canEdit: false, dirty: false, saving: false } as const @@ -178,6 +213,11 @@ export class InternalViewerController { this.view?.present?.() } + /** formats the selection while editing: `format({ op: 'toggle', mark: 'bold' })`, `format({ op: 'size', pt: 14 })` */ + format = (cmd: FormatCommand) => { + this.view?.format?.(cmd) + } + print = () => { this.fileAction('print') } @@ -304,6 +344,6 @@ export function useViewCommands(ctl: ViewController | null, commands: ViewComman useEffect(() => { if (!ctl) return const call = (k: K) => ((...a: unknown[]) => (latest.current[k] as ((...x: unknown[]) => void) | undefined)?.(...a)) as ViewCommands[K] - return ctl.attachView({ setZoom: call('setZoom'), goto: call('goto'), gotoPage: call('gotoPage'), undo: call('undo'), redo: call('redo'), present: call('present') }) + return ctl.attachView({ setZoom: call('setZoom'), goto: call('goto'), gotoPage: call('gotoPage'), undo: call('undo'), redo: call('redo'), present: call('present'), format: call('format') }) }, [ctl, latest]) } diff --git a/src/react/docx/DocxEditor.ts b/src/react/docx/DocxEditor.ts index 7e5442e..5c4599d 100644 --- a/src/react/docx/DocxEditor.ts +++ b/src/react/docx/DocxEditor.ts @@ -204,6 +204,15 @@ export class DocxEditor implements RichHost { /** paragraphs whose look on screen may be behind their style / list: a conversion was asked, none was applied yet */ private stale = new Set() onState?: (s: FormatState | null) => void + private stateSubs = new Set<(s: FormatState | null) => void>() + /** hears the current formatting state, then every one `onState` does (the viewer's controller, beside the toolbar) */ + subscribeState(fn: (s: FormatState | null) => void): () => void { + this.stateSubs.add(fn) + fn(this.state()) + return () => { + this.stateSubs.delete(fn) + } + } /** whether undo / redo can run, after every change of the selection or the document (the viewer's controller) */ onHistory?: (canUndo: boolean, canRedo: boolean) => void /** image selection changed (overlay with resize handles) */ @@ -1894,6 +1903,7 @@ export class DocxEditor implements RichHost { private emitState(sel: Sel | null) { const st = sel ? this.state(sel) : null this.onState?.(st) + for (const fn of this.stateSubs) fn(st) this.onImage?.(st?.img ?? null) this.onHistory?.(this.canUndo, this.canRedo) } diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index d87c3d1..6b62653 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -9,6 +9,7 @@ import { useFileOps, useSelectAll, useViewer } from '../common/Slots' import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' import { useViewCommands, useControllerObserved } from '../controller' +import { applyDocx, docxFormat } from '../edit/format' import { ContextMenu, MOD, type MenuItem } from '../common/ContextMenu' import { PromptDialog, Toast, type PromptSpec } from '../common/Dialog' import { domFromPos, getSel, opInsert, posFromDom, selPoints } from '../edit/input' @@ -819,7 +820,19 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp redo: () => { if (isEditing) editor.redo() }, + format: (c) => { + if (isEditing) applyDocx(editor, c) + }, }) + useEffect(() => { + if (!ctl) return + if (!isEditing) return ctl.update({ format: null }) + const off = editor.subscribeState((s) => ctl.update({ format: s && docxFormat(s) })) + return () => { + off() + ctl.update({ format: null }) + } + }, [ctl, editor, isEditing]) return (
diff --git a/src/react/edit/format.ts b/src/react/edit/format.ts new file mode 100644 index 0000000..95bdafe --- /dev/null +++ b/src/react/edit/format.ts @@ -0,0 +1,75 @@ +import type { FmtPatch } from '../../core/xlsx/types' +import { MARK_KEY, type FormatCommand, type TextFormat } from '../controller' +import type { DocxEditor, FormatState } from '../docx/DocxEditor' +import type { PptxEditor, PptxFormat } from '../pptx/PptxEditor' +import { fontName } from './Toolbar' + +// The editors' formatting states as the controller's TextFormat, and its commands as editor calls: one formatting +// API for a host's toolbar, whichever kind of document is open. + +const ALIGNS = ['left', 'center', 'right', 'justify'] as const +const alignOf = (a: string | undefined): TextFormat['align'] => ALIGNS.find((x) => x === a) +/** sizes as the toolbars show them: to the half point */ +const half = (n: number | undefined) => (n ? Math.round(n * 2) / 2 : undefined) + +export function docxFormat(s: FormatState): TextFormat { + return { bold: s.b, italic: s.i, underline: s.u, strike: s.strike, font: fontName(s.font) || undefined, size: half(s.sz), color: s.color, highlight: s.hl, align: alignOf(s.align), list: s.lst ?? null } +} + +export function applyDocx(ed: DocxEditor, c: FormatCommand) { + if (c.op === 'toggle') ed.toggle(MARK_KEY[c.mark]) + else if (c.op === 'font') ed.setFont(c.name) + else if (c.op === 'size') ed.setSize(c.pt) + else if (c.op === 'color') ed.setColor(c.color) + else if (c.op === 'highlight') ed.setHighlight(c.color) + else if (c.op === 'align') ed.setPara({ align: c.align }, { align: c.align }) + else if (c.op === 'list') ed.toggleList(c.list) + else ed.clearFormat() +} + +export function pptxFormat(s: PptxFormat): TextFormat { + return { bold: s.b, italic: s.i, underline: s.u, strike: s.strike, font: fontName(s.font) || undefined, size: half(s.sz), color: s.color, highlight: s.hl, align: alignOf(s.algn), list: s.bullet === 'bullet' || s.bullet === 'number' ? s.bullet : null } +} + +export function applyPptx(ed: PptxEditor, c: FormatCommand) { + if (c.op === 'toggle') ed.toggle(MARK_KEY[c.mark]) + else if (c.op === 'font') ed.setFont(c.name) + else if (c.op === 'size') ed.setSize(c.pt) + else if (c.op === 'color') ed.setColor(c.color) + else if (c.op === 'highlight') ed.setHighlight(c.color) + else if (c.op === 'align') ed.setAlign(c.align) + else if (c.op === 'list') ed.toggleBullet(c.list) + else ed.clearFormat() +} + +/** a CSS font size (px number or 'pt' string) in points */ +const pt = (v: unknown) => (typeof v === 'string' && v.endsWith('pt') ? parseFloat(v) : typeof v === 'number' ? Math.round(v * 0.75 * 2) / 2 : undefined) + +/** the active cell's formatting from its CSS, the workbook's base font where the cell sets none */ +export function cellFormat(css: Record, base: { fontFamily?: string; fontSize?: string | number }): TextFormat { + const deco = String(css.textDecoration ?? '') + const fill = typeof css.background === 'string' && !css.background.includes('gradient') ? css.background : undefined + return { + bold: css.fontWeight === 700, + italic: css.fontStyle === 'italic', + underline: deco.includes('underline'), + strike: deco.includes('line-through'), + font: fontName((css.fontFamily ?? base.fontFamily) as string | undefined) || undefined, + size: pt(css.fontSize) ?? pt(base.fontSize), + color: css.color as string | undefined, + highlight: fill, + align: alignOf(css.textAlign as string | undefined), + } +} + +/** a command as a cell format patch; null for what cells do not have (lists, justified text) */ +export function cellPatch(c: FormatCommand, now: TextFormat): FmtPatch | null { + if (c.op === 'toggle') return { [MARK_KEY[c.mark]]: !now[c.mark] } + if (c.op === 'font') return { font: c.name } + if (c.op === 'size') return { sz: c.pt } + if (c.op === 'color') return { color: c.color } + if (c.op === 'highlight') return { fill: c.color } + if (c.op === 'align') return c.align === 'justify' ? null : { align: c.align } + if (c.op === 'clear') return { clear: true } + return null +} diff --git a/src/react/pptx/PptxEditor.ts b/src/react/pptx/PptxEditor.ts index 7cad0fa..9847718 100644 --- a/src/react/pptx/PptxEditor.ts +++ b/src/react/pptx/PptxEditor.ts @@ -95,6 +95,19 @@ export class PptxEditor implements RichHost { onCommitted?: (slide: number, model: SlideModel) => void onDirty?: () => void onState?: (s: PptxFormat | null) => void + private stateSubs = new Set<(s: PptxFormat | null) => void>() + /** hears the current formatting state, then every one `onState` does (the viewer's controller, beside the toolbar) */ + subscribeState(fn: (s: PptxFormat | null) => void): () => void { + this.stateSubs.add(fn) + fn(this.state()) + return () => { + this.stateSubs.delete(fn) + } + } + private emitState(s: PptxFormat | null) { + this.onState?.(s) + for (const fn of this.stateSubs) fn(s) + } constructor(private client: DocumentClient) { this.input = new RichInput(this) @@ -122,7 +135,7 @@ export class PptxEditor implements RichHost { this.sid = -1 this.slide = -1 this.body = undefined - this.onState?.(null) + this.emitState(null) } text(): TextBody | undefined { @@ -202,7 +215,7 @@ export class PptxEditor implements RichHost { clearTimeout(this.timer) this.timer = setTimeout(() => this.commitInBackground(), 400) this.onChange?.() - this.onState?.(this.state(sel)) + this.emitState(this.state(sel)) } undo() { @@ -225,7 +238,7 @@ export class PptxEditor implements RichHost { clearTimeout(this.timer) this.timer = setTimeout(() => this.commitInBackground(), 400) this.onChange?.() - this.onState?.(this.state(sel)) + this.emitState(this.state(sel)) } private commitInBackground() { @@ -287,7 +300,7 @@ export class PptxEditor implements RichHost { if (collapsed(sel)) { this.pend = { s: { ...(this.pend?.s ?? {}), ...s }, d: { ...(this.pend?.d ?? {}), ...d }, at: sel.a } this.input.restore(sel) - this.onState?.(this.state(sel)) + this.emitState(this.state(sel)) return } const [a, b] = ordered(this, sel) @@ -388,7 +401,7 @@ export class PptxEditor implements RichHost { onSelection(sel: Sel | null) { if (sel && this.pend && (sel.a.pa !== this.pend.at.pa || sel.a.o !== this.pend.at.o)) this.pend = null - this.onState?.(sel ? this.state(sel) : null) + this.emitState(sel ? this.state(sel) : null) } shortcut?: (e: KeyboardEvent) => boolean diff --git a/src/react/pptx/PptxView.tsx b/src/react/pptx/PptxView.tsx index 567043b..68c02bd 100644 --- a/src/react/pptx/PptxView.tsx +++ b/src/react/pptx/PptxView.tsx @@ -7,6 +7,7 @@ import { slidesToText } from '../file/text' import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' import { useViewCommands, useControllerObserved } from '../controller' +import { applyPptx, pptxFormat } from '../edit/format' import { getSel } from '../edit/input' import { PptxEditor } from './PptxEditor' import { PptxToolbar, type AlignTo, type Arrange, type Rotate, type SlideCmd } from './PptxToolbar' @@ -646,7 +647,20 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t undo: () => viewer.editable && (editor.active ? editor.undo() : void undoShapes(false)), redo: () => viewer.editable && (editor.active ? editor.redo() : void undoShapes(true)), present: () => setPresenting(current), + format: (c) => { + if (viewer.editable && editor.active) applyPptx(editor, c) + }, }) + // formatting reaches text being edited; a shape that is only selected has none + useEffect(() => { + if (!ctl) return + if (!viewer.editable) return ctl.update({ format: null }) + const off = editor.subscribeState((s) => ctl.update({ format: s && pptxFormat(s) })) + return () => { + off() + ctl.update({ format: null }) + } + }, [ctl, editor, viewer.editable]) // ---- comments: a thread points at a point of a slide ---- const cm = useCommentsCtl() diff --git a/src/react/xlsx/XlsxView.tsx b/src/react/xlsx/XlsxView.tsx index 3216390..8ef1f24 100644 --- a/src/react/xlsx/XlsxView.tsx +++ b/src/react/xlsx/XlsxView.tsx @@ -10,7 +10,8 @@ import type { DocumentClient } from '../../core/worker/client' import { getPeers, publishLocal, subscribePeers, getLocalHistory, subscribeLocalHistory } from '../../collab/hosts' import { claimFocus, useForceUpdate, useScroll, useSize } from '../common/hooks' import { useFileOps, useViewer, useSelectAll } from '../common/Slots' -import { useViewCommands } from '../controller' +import { useViewCommands, type FormatCommand } from '../controller' +import { cellFormat, cellPatch } from '../edit/format' import { Status } from '../common/Status' import { ContextMenu, MOD, type MenuItem } from '../common/ContextMenu' import { Toast } from '../common/Dialog' @@ -425,7 +426,7 @@ export function XlsxView({ client, onStatus, initialSheet }: XlsxViewProps) { // ---- controller: the sheets as the outline, sheet switching, undo ---- const { ctl, headless } = viewer - const gridCommands = useRef<{ undo: () => void; redo: () => void } | null>(null) + const gridCommands = useRef<{ undo: () => void; redo: () => void; format: (c: FormatCommand) => void } | null>(null) const sheetItems = meta.sheets.filter((s) => !s.hidden).map((s) => ({ id: String(s.index), title: s.name, level: 0, current: s.index === cur })) useEffect(() => { const h = store.history @@ -441,6 +442,7 @@ export function XlsxView({ client, onStatus, initialSheet }: XlsxViewProps) { }, undo: () => gridCommands.current?.undo(), redo: () => gridCommands.current?.redo(), + format: (c) => gridCommands.current?.format(c), }) return ( @@ -540,7 +542,7 @@ interface GridProps { hold: MutableRefObject onSheet: (i: number) => void /** set by the grid: its undo / redo, for the viewer's controller */ - gridCommands: MutableRefObject<{ undo: () => void; redo: () => void } | null> + gridCommands: MutableRefObject<{ undo: () => void; redo: () => void; format: (c: FormatCommand) => void } | null> } /** text rotation (OOXML degrees, + = counter-clockwise, 255 = stacked) */ @@ -1232,9 +1234,19 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g } const undo = () => void run(client.call('xlsx.undo'), 'undo') const redo = () => void run(client.call('xlsx.redo'), 'redo') - // the controller's undo / redo: this sheet's grid runs them while it is shown + // the controller's undo / redo and formatting: this sheet's grid runs them while it is shown + const cellFmt = cellFormat(activeCss, meta.baseFont as { fontFamily?: string; fontSize?: string | number }) useEffect(() => { - gridCommands.current = { undo: () => editable && undo(), redo: () => editable && redo() } + gridCommands.current = { + undo: () => editable && undo(), + redo: () => editable && redo(), + format: (c) => { + const patch = editable && cellPatch(c, cellFmt) + if (patch) fmt(patch) + }, + } + const h = store.history + viewer.ctl?.update({ format: editable ? cellFmt : null, canUndo: editable && h.undo > 0, canRedo: editable && h.redo > 0 }) }) /** the selection as clipboard text, when all its rows are at hand (else null: the worker has them) */ diff --git a/test/docx-edge.test.ts b/test/docx-edge.test.ts index abb1746..ad584ed 100644 --- a/test/docx-edge.test.ts +++ b/test/docx-edge.test.ts @@ -367,6 +367,19 @@ describe('review findings', () => { expect(seen.at(-1)).toEqual([true, false]) client.destroy() }) + + test('a state subscriber hears the current state at once, then each change, until it unsubscribes', async () => { + const { ed, client } = await editorOn(await tracked()) + const seen: unknown[] = [] + const off = ed.subscribeState((s) => seen.push(s)) + expect(seen).toEqual([ed.state()]) + ed.onSelection(null) + expect(seen.length).toBe(2) + off() + ed.onSelection(null) + expect(seen.length).toBe(2) + client.destroy() + }) }) describe('saving in between', () => { diff --git a/test/format.test.ts b/test/format.test.ts new file mode 100644 index 0000000..871c844 --- /dev/null +++ b/test/format.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from 'bun:test' +import type { FormatState } from '../src/react/docx/DocxEditor' +import { cellFormat, cellPatch, docxFormat, pptxFormat } from '../src/react/edit/format' + +describe('formatting as TextFormat', () => { + test('docx: marks, font name from the CSS stack, half points, list', () => { + const s = { b: true, i: false, u: true, strike: false, font: '"Calibri", sans-serif', sz: 11.26, color: '#ff0000', hl: 'yellow', align: 'center', lst: 'number', inTable: false, canUndo: true, canRedo: false } as FormatState + expect(docxFormat(s)).toEqual({ bold: true, italic: false, underline: true, strike: false, font: 'Calibri', size: 11.5, color: '#ff0000', highlight: 'yellow', align: 'center', list: 'number' }) + expect(docxFormat({ ...s, lst: undefined, align: 'both' }).list).toBeNull() + expect(docxFormat({ ...s, align: 'both' }).align).toBeUndefined() + }) + + test('pptx: bullets other than bullet / number are no list', () => { + const f = pptxFormat({ b: false, i: true, u: false, strike: true, sz: 18, algn: 'justify', bullet: 'none', lvl: 0 }) + expect(f).toMatchObject({ italic: true, strike: true, size: 18, align: 'justify', list: null }) + }) + + test('cells: CSS of the active cell, the base font where the cell has none, no lists', () => { + const f = cellFormat({ fontWeight: 700, textDecoration: 'underline line-through', fontSize: '14pt', background: '#ffff00', textAlign: 'right' }, { fontFamily: 'Aptos, sans-serif', fontSize: 11 * (4 / 3) }) + expect(f).toEqual({ bold: true, italic: false, underline: true, strike: true, font: 'Aptos', size: 14, color: undefined, highlight: '#ffff00', align: 'right' }) + expect(cellFormat({}, { fontSize: '11pt' }).size).toBe(11) + expect(cellFormat({ background: 'linear-gradient(red, blue)' }, {}).highlight).toBeUndefined() + }) + + test('cell patches: a toggle flips the current state; what cells lack is null', () => { + const now = cellFormat({ fontWeight: 700 }, {}) + expect(cellPatch({ op: 'toggle', mark: 'bold' }, now)).toEqual({ b: false }) + expect(cellPatch({ op: 'toggle', mark: 'italic' }, now)).toEqual({ i: true }) + expect(cellPatch({ op: 'highlight', color: '#ff0' }, now)).toEqual({ fill: '#ff0' }) + expect(cellPatch({ op: 'size', pt: 9 }, now)).toEqual({ sz: 9 }) + expect(cellPatch({ op: 'clear' }, now)).toEqual({ clear: true }) + expect(cellPatch({ op: 'align', align: 'justify' }, now)).toBeNull() + expect(cellPatch({ op: 'list', list: 'bullet' }, now)).toBeNull() + }) +}) From ce01a8fa8a7ec5f71c2d9a6554e25c7f861ba8f2 Mon Sep 17 00:00:00 2001 From: Markus Date: Tue, 17 Nov 2026 21:41:17 +0100 Subject: [PATCH 22/41] audit: adapt PR9 format tests to accepted PR8 opt-in controller fixture --- e2e/controller.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/e2e/controller.spec.ts b/e2e/controller.spec.ts index b53131f..47fda69 100644 --- a/e2e/controller.spec.ts +++ b/e2e/controller.spec.ts @@ -254,7 +254,7 @@ describe('controller and headless mode', () => { }) test('docx: formatting state and commands through the controller', async () => { - const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true, headless: true }) + const v = await viewer({ controller: true, src: 'samples/sample.docx', editable: true, onSave: true, headless: true }) const { page } = v await until(v, 's.editing') await v.selectText('document') @@ -277,7 +277,7 @@ describe('controller and headless mode', () => { }) test("xlsx: the active cell's format through the controller", async () => { - const v = await viewer({ src: 'samples/sample.xlsx', editable: true, onSave: true, headless: true }) + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', editable: true, onSave: true, headless: true }) const { page } = v await page.locator('.de-grid').waitFor() await v.typeCell('J10', '12.5') From 8ec37cf2c3d82c2aa36c0f30a8887d64f35542df Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 14 Nov 2026 22:35:46 +0100 Subject: [PATCH 23/41] feat(viewer): headless mode and a controller for host-drawn controls A host that draws its own controls around the document gets ``. `headless` leaves the viewer with the document alone: no top bar, zoom control, outline panel or button, sheet tabs, slide list or Present button. While editing, the formatting toolbar keeps its row, and an explicit `toolbar` brings back the top bar (File menu, comments, Save). The controller (src/react/controller.ts, framework-free) holds the state - kind, loading, editing, canEdit, dirty, saving, canUndo/canRedo, zoom, page, outline (headings, sheets or slides), status - and runs the commands: setEditing, save, undo, redo, zoomIn/zoomOut/setZoom, goto, gotoPage, present, print, fileAction, toggleComments. The viewer and its mounted view publish to it and register their commands; without one from the host the viewer keeps its own, so nothing else changes. When the viewer or its view unmounts, its part of the state is cleared, so a controller that outlives it shows no document. `useViewerState(ctl)` reads the state in React. - DOCX: headings are read for the controller whether or not the outline panel is open (once edits rest), with the current one, which stays the heading jumped to while its page is in view; DocxEditor reports its undo/redo history after each step, offered only while editing. - XLSX: the visible sheets as the outline; undo/redo counted per edit, cleared when a sheet is added, deleted, moved, renamed or imported, as the worker's history is. A sheet switched to through the controller keeps a formula being typed open, for cross-sheet references, as the built-in tabs do. - PPTX: slides titled by their title placeholder, read by a title-only worker call (`pptx.titles`, no layout) only while a host subscribes (`observed`, `watchObserved`), and kept current as slides are edited; symbol-font characters in titles as their Unicode look-alikes. Undo and redo through the controller do nothing outside edit mode. - `onLoad` fires once per opened document, also with an inline callback. - mount() returns the controller; has .controller. - e2e harness: PLAYWRIGHT_CHANNEL picks an installed browser. Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 58 +++++++- e2e/app/main.tsx | 9 +- e2e/controller.spec.ts | 112 +++++++++++++++ e2e/harness.ts | 3 +- src/core/pptx/parser.ts | 31 +++++ src/core/pptx/types.ts | 2 + src/core/worker/engine.ts | 2 + src/core/worker/protocol.ts | 2 + src/embed.ts | 16 ++- src/index.ts | 1 + src/react/DocViewer.tsx | 53 +++++++- src/react/common/Slots.tsx | 7 + src/react/common/Status.tsx | 6 +- src/react/common/ZoomControl.tsx | 8 +- src/react/controller.ts | 227 +++++++++++++++++++++++++++++++ src/react/docx/DocxEditor.ts | 20 ++- src/react/docx/DocxToolbar.tsx | 5 +- src/react/docx/DocxView.tsx | 63 ++++++++- src/react/pptx/PptxView.tsx | 70 +++++++++- src/react/styles.css | 3 + src/react/xlsx/XlsxView.tsx | 59 +++++++- test/controller.test.ts | 79 +++++++++++ test/core.test.ts | 4 + test/docx-edge.test.ts | 12 ++ 24 files changed, 814 insertions(+), 38 deletions(-) create mode 100644 e2e/controller.spec.ts create mode 100644 src/react/controller.ts create mode 100644 test/controller.test.ts diff --git a/docs/api.md b/docs/api.md index 378d58d..b760d71 100644 --- a/docs/api.md +++ b/docs/api.md @@ -81,8 +81,62 @@ CSS is auto-injected, no import needed (or import `@p10node/office-engine/styles | `onDirtyChange` | `(dirty) => void` | – | Whether there are unsaved changes | | `collab` | `CollabOptions` | – | Real-time collaboration, see [collaboration](collaboration.md) | | `comments` | `CommentOptions \| false` | `{}` | Comments (see below); `false` hides them | -| `onLoad` | `(client) => void` | – | | +| `onLoad` | `(client) => void` | – | Once per opened document | | `onError` | `(error) => void` | – | | +| `controller` | `ViewerController` | its own | The viewer's state and commands for the host, see [headless mode](#headless-mode) | +| `headless` | `boolean` | `false` | The document alone: no top bar, zoom control, outline panel, sheet tabs or slide list | +| `icons` | `Partial>` | – | The host's icons by name (`ICON_NAMES`), sized by font-size (1em), instead of the built-in ones | + +### Headless mode + +For a host that draws its own controls around the document: `headless` leaves the viewer with the document alone, and a +`controller` (`createViewerController()`) carries its state and the commands that drive it. While editing, the formatting +toolbar keeps its row above the document; dialogs, the find bar and the comments panel are the viewer's own. `toolbar` +set explicitly brings back the top bar (File menu, comments, Save) and leaves the rest headless. + +```tsx +import { createViewerController, DocViewer, useViewerState } from '@p10node/office-engine' +import { useMemo } from 'react' + +function Viewer({ file }: { file: File }) { + const ctl = useMemo(() => createViewerController(), []) + const s = useViewerState(ctl) + return ( + <> + + {s.zoom && } + {s.canEdit && } + {s.dirty && } + + + ) +} +``` + +| `ViewerState` | Meaning | +|---------------|---------| +| `rev` | counts the changes (the state object is replaced on each) | +| `kind` | `'docx'`, `'xlsx'`, `'pptx'`, or `null` before a document is open | +| `loading` | loading or downloading | +| `editing`, `canEdit` | in edit mode; whether editing is possible (allowed, not view only) | +| `dirty`, `saving` | unsaved changes; a save running | +| `canUndo`, `canRedo` | whether undo / redo can run (spreadsheets count the edits made here; presentations offer redo whenever editing) | +| `zoom` | `{ value: 'fit' \| number, effective }`, `null` for spreadsheets | +| `page` | `{ current, count }` from 1: the page (documents; `count` 0 while laid out) or slide in view; `null` for spreadsheets | +| `outline` | `{ kind, items: [{ id, title, level, current }] }`: a document's headings, a workbook's visible sheets, a presentation's slides (titled by their title placeholder, else "Slide n") | +| `status` | the status line ("Page 2 of 7 · 1,204 words", "Slide 3 of 12", "200 rows × 8 cols") | + +Commands: `setEditing(on)`, `save()`, `undo()`, `redo()`, `zoomIn()`, `zoomOut()`, `setZoom('fit' | number)`, +`goto(outlineId)`, `gotoPage(n)`, `present()` (a slideshow from the slide in view), `print()`, `fileAction(id)` (a File menu +action: `pdf`, `html`, `text:md`, `details`, `rename`…), `toggleComments(open?)`. A command the open document has no use +for does nothing. `subscribe(fn)` returns its unsubscribe; `snapshot()` the current state. Without `react`, `mount()` +returns the controller (`mounted.controller`), and `` has it as `element.controller`. ### Comments @@ -296,7 +350,7 @@ Document content stays in its original language. Default new sheet names, the au ``` -``: attributes `src`, `name`, `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `locale="en-GB"` (number/date formatting), `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`; properties `.file = File`, `.icons` (map or resolver, as `icons` above) and `.strings = { … }` (see [UI texts](#ui-texts)); events `load`, `error`, `comment` (`detail`: a `CommentEvent`). +``: attributes `src`, `name`, `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `locale="en-GB"` (number/date formatting), `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`, `headless`; properties `.file = File`, `.icons` (map or resolver, as `icons` above), `.strings = { … }` (see [UI texts](#ui-texts)), `.controller` (see [headless mode](#headless-mode)); events `load`, `error`, `comment` (`detail`: a `CommentEvent`). ## Core API (no React) diff --git a/e2e/app/main.tsx b/e2e/app/main.tsx index f3ffbb2..1573173 100644 --- a/e2e/app/main.tsx +++ b/e2e/app/main.tsx @@ -5,10 +5,11 @@ * &icons=1: every icon from a host resolver, as `` * texts: &locale=de-DE opts into the explicitly imported German table, &fileLabel=… overrides the File label * &components=1: the host's own Button, Separator, Dialog and Toast (`data-host-*` markers) + * &headless=1: the document alone; the viewer is driven through window.__ctl (its controller) either way */ import { useState } from 'react' import { createRoot } from 'react-dom/client' -import { DocViewer, type DocViewerProps, type FileMenuItem, type UIComponents } from '../../src' +import { createViewerController, DocViewer, type DocViewerProps, type FileMenuItem, type UIComponents, type ViewerController } from '../../src' import { de } from '../../src/locales/de' type Ev = { type: string; [k: string]: unknown } @@ -18,9 +19,13 @@ declare global { __setProps: (p: Partial) => void __setLanguage: (language: 'en' | 'de-DE') => void __german: typeof de + __ctl: ViewerController } } window.__events = [] +window.__ctl = createViewerController() +// a host reading the state, as the tests do through snapshot(): views read slide titles only for one +window.__ctl.subscribe(() => {}) const log = (e: Ev) => window.__events.push(e) const q = new URLSearchParams(location.search) @@ -99,6 +104,8 @@ const initial: DocViewerProps = { injectStyles: flag('injectStyles'), locale: (texts ? undefined : q.get('locale') as DocViewerProps['locale']) ?? undefined, strings: q.has('fileLabel') ? { ...texts, file: { ...(texts?.file ?? {}), menu: q.get('fileLabel')! } } : texts, + headless: flag('headless'), + controller: window.__ctl, onSave: q.has('onSave') ? async (blob, name) => void log({ type: 'save', name, b64: await b64(blob) }) : undefined, onDirtyChange: (dirty) => log({ type: 'dirty', dirty }), onRename: (name) => log({ type: 'rename', name }), diff --git a/e2e/controller.spec.ts b/e2e/controller.spec.ts new file mode 100644 index 0000000..ea4d760 --- /dev/null +++ b/e2e/controller.spec.ts @@ -0,0 +1,112 @@ +import { describe, expect, test } from 'bun:test' +import type { ViewerState } from '../src' +import { useBrowser, viewer, type Viewer } from './harness' + +useBrowser() + +const state = (v: Viewer) => v.page.evaluate(() => window.__ctl.snapshot()) as Promise +/** waits until the controller's state passes `check` (run in the page) */ +const until = (v: Viewer, check: string) => v.page.waitForFunction(`(() => { const s = window.__ctl.snapshot(); return ${check} })()`, null, { timeout: 15_000 }) + +describe('controller and headless mode', () => { + test('docx: zoom, pages and headings through the controller; no chrome of its own', async () => { + const v = await viewer({ src: 'samples/sample.docx', headless: true }) + const { page } = v + expect(await page.locator('.de-bar').count()).toBe(0) + expect(await page.locator('.de-zoom').count()).toBe(0) + expect(await page.locator('.de-outline-toggle').count()).toBe(0) + + await until(v, "s.kind === 'docx' && s.page && s.page.count > 0 && s.outline && s.outline.items.length > 0") + const s = await state(v) + expect(s.zoom?.value).toBe('fit') + expect(s.status).toMatch(/Page 1 of \d+/) + expect(s.outline?.kind).toBe('headings') + expect(s.outline?.items.map((i) => i.title)).toContain('1. Highlights') + + // a heading further down: the view scrolls there and marks it current + const table = s.outline!.items.find((i) => /Table/.test(i.title))! + await page.evaluate((id) => window.__ctl.goto(id), table.id) + await until(v, `s.outline.items.find((i) => i.id === ${JSON.stringify(table.id)}).current`) + + // zoom in widens the page + const w0 = (await page.locator('.de-page').first().boundingBox())!.width + await page.evaluate(() => window.__ctl.zoomIn()) + await until(v, "typeof s.zoom.value === 'number'") + await page.waitForTimeout(200) + expect((await page.locator('.de-page').first().boundingBox())!.width).toBeGreaterThan(w0) + expect(v.errors).toEqual([]) + }) + + test('docx: editing and saving through the controller', async () => { + const v = await viewer({ src: 'samples/sample.docx', headless: true, onSave: true }) + const { page } = v + await until(v, 's.canEdit') + await page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.editing') + // the formatting toolbar keeps its row in a headless viewer, without the outline button + await page.locator('.de-ebar').waitFor() + expect(await page.locator('.de-ebar [title="Document outline"]').count()).toBe(0) + await page.evaluate(() => window.__ctl.save()) + const saved = await v.waitEvent('save') + expect(saved.name).toBe('sample.docx') + await page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing') + expect(v.errors).toEqual([]) + }) + + test('docx: undo is offered only while editing', async () => { + const v = await viewer({ src: 'samples/sample.docx', headless: true }) + await until(v, 's.canEdit') + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.editing') + await v.selectText('Quarterly Report', 'end') + await v.page.keyboard.type('!!') + await until(v, 's.canUndo') + await v.page.evaluate(() => window.__ctl.setEditing(false)) + await until(v, '!s.editing && !s.canUndo && !s.canRedo') + await v.page.evaluate(() => window.__ctl.setEditing(true)) + await until(v, 's.editing && s.canUndo') + expect(v.errors).toEqual([]) + }) + + test('xlsx: the sheets as the outline, no tabs of its own', async () => { + const v = await viewer({ src: 'samples/sample.xlsx', headless: true }) + const { page } = v + expect(await page.locator('.de-tabs').isVisible()).toBe(false) + await until(v, "s.kind === 'xlsx' && s.outline && s.outline.kind === 'sheets'") + const s = await state(v) + expect(s.zoom).toBeNull() + expect(s.outline!.items.map((i) => i.title)).toEqual(['Sales', 'Notes', 'Data']) + expect(s.outline!.items[0].current).toBe(true) + await page.evaluate((id) => window.__ctl.goto(id), s.outline!.items[1].id) + await until(v, 's.outline.items[1].current') + expect(v.errors).toEqual([]) + }) + + test('pptx: slides, zoom and the slide in view; no thumbnails, zoom or Present button', async () => { + const v = await viewer({ src: 'samples/sample.pptx', headless: true }) + const { page } = v + expect(await page.locator('.de-thumbs').count()).toBe(0) + expect(await page.locator('.de-zoom').count()).toBe(0) + expect(await page.locator('.de-present-btn').count()).toBe(0) + await until(v, "s.kind === 'pptx' && s.page && s.outline && s.outline.kind === 'slides'") + const s = await state(v) + expect(s.page!.current).toBe(1) + expect(s.outline!.items.length).toBe(s.page!.count) + await page.evaluate(() => window.__ctl.gotoPage(3)) + await until(v, 's.page.current === 3') + // slide titles arrive from the slides' title placeholders + await until(v, "s.outline.items.some((i) => !/^Slide \\d+$/.test(i.title))") + expect(v.errors).toEqual([]) + }) + + test('with chrome: the controller still follows the view', async () => { + const v = await viewer({ src: 'samples/sample.docx' }) + const { page } = v + expect(await page.locator('.de-bar').count()).toBe(1) + await until(v, "s.kind === 'docx' && s.zoom") + await page.locator('button[aria-label="Zoom in"]').click() + await until(v, "typeof s.zoom.value === 'number'") + expect(v.errors).toEqual([]) + }) +}) diff --git a/e2e/harness.ts b/e2e/harness.ts index 99ccf4f..5fdbf82 100644 --- a/e2e/harness.ts +++ b/e2e/harness.ts @@ -38,7 +38,8 @@ export function useBrowser() { beforeAll(async () => { server = await createServer({ configFile: 'vite.e2e.config.ts', server: { port: 0, strictPort: false } }) await server.listen() - const browser = await chromium.launch() + // PLAYWRIGHT_CHANNEL=chrome / msedge: an installed browser instead of Playwright's own Chromium + const browser = await chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || undefined }) shared = { base: server.resolvedUrls!.local[0], browser } }) afterEach(async () => { diff --git a/src/core/pptx/parser.ts b/src/core/pptx/parser.ts index f2da5ed..af18afe 100644 --- a/src/core/pptx/parser.ts +++ b/src/core/pptx/parser.ts @@ -157,6 +157,22 @@ function phOf(el: XEl): { type: string; idx?: string } | undefined { return { type: ph.a.type ?? 'body', idx: ph.a.idx } } +// A slide title as plain text: symbol-font characters (Wingdings arrows, check marks) have no glyph +// outside their font, so the usual ones become their Unicode look-alikes and the rest are dropped. +const TITLE_SYMBOLS: Record = { + '\uF0E0': '➔', '\uF0E8': '➔', '\uF0F0': '⇨', '\uF0D8': '➢', '\uF0FC': '✓', '\uF0FB': '✗', '\uF0B7': '•', '\uF0A7': '▪', '\uF06C': '●', +} +const plainTitle = (paras: string[]) => paras.join(' ').replace(/[\uF000-\uF0FF]/g, (c) => TITLE_SYMBOLS[c] ?? '').replace(/\s+/g, ' ').trim() + +/** the text of the title placeholder in a slide's shape tree (groups included), or '' */ +function titleOf(tree: XEl | undefined): string { + for (const c of tree?.c ?? []) { + const t = c.n === 'grpSp' ? titleOf(c) : c.n === 'sp' && ['title', 'ctrTitle'].includes(phOf(c)?.type ?? '') ? plainTitle(kids(kid(c, 'txBody'), 'p').map(textOf)) : '' + if (t) return t + } + return '' +} + const masterType = (t: string) => (t === 'ctrTitle' ? 'title' : t === 'subTitle' || t === 'obj' ? 'body' : t) function indexPlaceholders(spTree: XEl | undefined) { @@ -312,9 +328,17 @@ export class PptxPresentation { bg: r.background(), els, hidden: slide.root.a.show === '0', + title: r.title, } } + /** every slide's title placeholder text ('' where there is none): its XML only, nothing laid out */ + async titles(): Promise { + const out: string[] = [] + for (const s of this.meta.slides) out.push(titleOf((await this.part(s.path)).spTree)) + return out + } + get defaults() { return this.defaultTextStyle } @@ -458,6 +482,8 @@ function readXfrm(x: XEl | undefined): Box | undefined { } class SlideRenderer { + /** the text of the slide's title placeholder, once walked */ + title: string | undefined constructor( private pres: PptxPresentation, private slide: Part, @@ -873,6 +899,11 @@ class SlideRenderer { const idAttr = path(el, 'nvSpPr', 'cNvPr')?.a.id const sid = part === this.slide && el.n === 'sp' && idAttr ? Number(idAttr) : undefined const text = el.n === 'sp' ? this.textBody(kid(el, 'txBody'), chain, ph, kid(style, 'fontRef'), part, sid) : undefined + // the slide's own title placeholder names the slide (outline, slide list) + if (text && part === this.slide && this.title === undefined && (ph?.type === 'title' || ph?.type === 'ctrTitle')) { + const t = plainTitle(text.paras.map((p) => p.runs.map((r) => r.text).join(''))) + if (t) this.title = t + } if ((!fill || fill.t === 'none') && !stroke && !text) return out.push({ t: 'shape', box, geom, adj, fill, stroke, text, path: pathD, sid }) } diff --git a/src/core/pptx/types.ts b/src/core/pptx/types.ts index 810a008..b7513c1 100644 --- a/src/core/pptx/types.ts +++ b/src/core/pptx/types.ts @@ -124,6 +124,8 @@ export interface SlideModel { els: SlideEl[] notes?: string hidden?: boolean + /** the text of its title placeholder */ + title?: string } export interface PresentationMeta { diff --git a/src/core/worker/engine.ts b/src/core/worker/engine.ts index a797e98..d44f399 100644 --- a/src/core/worker/engine.ts +++ b/src/core/worker/engine.ts @@ -238,6 +238,8 @@ export class Engine { return addSlideImage(this.need(this.pptx), args[0] as number, new Uint8Array(args[1] as ArrayBuffer), args[2] as string) case 'pptx.slide': return this.need(this.pptx).slide(args[0] as number) + case 'pptx.titles': + return this.need(this.pptx).titles() case 'pptx.undo': return undoShapes(this.need(this.pptx), !!args[0]) } diff --git a/src/core/worker/protocol.ts b/src/core/worker/protocol.ts index 4be56bb..8c99142 100644 --- a/src/core/worker/protocol.ts +++ b/src/core/worker/protocol.ts @@ -100,6 +100,8 @@ export interface Methods { 'xlsx.undo'(): XlsxEditResult | null 'xlsx.redo'(): XlsxEditResult | null 'pptx.slide'(index: number): SlideModel + /** every slide's title placeholder text ('' where there is none), read without laying out the slides */ + 'pptx.titles'(): string[] 'pptx.setText'(index: number, sid: number, paras: PParaSpec[]): SlideModel 'pptx.shapes'(index: number, ops: ShapeOp[]): SlideModel 'pptx.slides'(op: SlideOp): PresentationMeta diff --git a/src/embed.ts b/src/embed.ts index 02eb3db..57c9589 100644 --- a/src/embed.ts +++ b/src/embed.ts @@ -4,12 +4,15 @@ import './core/default-worker' import { DocViewer, type DocViewerProps } from './react/DocViewer' import type { Icons } from './react/edit/Toolbar' import type { StringsOverride } from './react/strings' +import { ViewerController } from './react/controller' export type MountOptions = Omit const THEMES = ['light', 'dark', 'auto'] as const export interface MountedViewer { + /** the viewer's state and commands (the one passed in `options.controller`, else its own) */ + controller: ViewerController update(next: Partial): void destroy(): void } @@ -18,10 +21,12 @@ export interface MountedViewer { export function mount(el: HTMLElement, options: MountOptions): MountedViewer { let root: Root | null = createRoot(el) let props = options + const controller = options.controller ?? new ViewerController() const shadow = el.getRootNode() instanceof ShadowRoot ? (el.getRootNode() as ShadowRoot) : undefined - const render = () => root?.render(createElement(DocViewer, { ...props, styleTarget: shadow })) + const render = () => root?.render(createElement(DocViewer, { ...props, controller, styleTarget: shadow })) render() return { + controller, update(next) { props = { ...props, ...next } render() @@ -41,9 +46,10 @@ export function mount(el: HTMLElement, options: MountOptions): MountedViewer { * real-time collaboration: collab (hub WebSocket URL), room, user (display name), base (snapshot seq `src` was opened at). * Properties: `file` (File/Blob/ArrayBuffer) for local data; `icons` (map or resolver, as DocViewer's `icons`); * `strings` (texts replacing English or the enclosing provider's). + * `controller` (ViewerController) for state and commands; `headless` displays the document alone. */ export class OfficeViewerElement extends HTMLElement { - static observedAttributes = ['src', 'name', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments', 'locale'] + static observedAttributes = ['src', 'name', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments', 'locale', 'headless'] private viewer?: MountedViewer private _file?: Blob | ArrayBuffer private _icons?: Icons @@ -51,6 +57,8 @@ export class OfficeViewerElement extends HTMLElement { // Keep event callbacks stable across attribute/property updates: changing UI texts must not replay load/error events. private onLoad: NonNullable = (client) => this.dispatchEvent(new CustomEvent('load', { detail: { kind: client.kind, name: client.name } })) private onError: NonNullable = (error) => this.dispatchEvent(new CustomEvent('error', { detail: error })) + /** the viewer's state and commands, the same object for the element's whole life */ + readonly controller = new ViewerController() get file() { return this._file @@ -99,7 +107,7 @@ export class OfficeViewerElement extends HTMLElement { return { src: this._file ?? this.getAttribute('src'), name: this.getAttribute('name') ?? undefined, - toolbar: this.getAttribute('toolbar') !== 'false', + toolbar: this.hasAttribute('toolbar') ? this.getAttribute('toolbar') !== 'false' : undefined, thumbnails: this.getAttribute('thumbnails') !== 'false', editable: this.hasAttribute('editable') && this.getAttribute('editable') !== 'false', allowSave: this.getAttribute('save') !== 'false', @@ -111,6 +119,8 @@ export class OfficeViewerElement extends HTMLElement { icons: this._icons, locale: this.getAttribute('locale') ?? undefined, strings: this._strings, + headless: this.hasAttribute('headless') && this.getAttribute('headless') !== 'false', + controller: this.controller, collab: this.getAttribute('collab') && this.getAttribute('room') ? { diff --git a/src/index.ts b/src/index.ts index 84bc54b..3eafcee 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,6 +13,7 @@ export { THEME_TOKENS, createTheme, themeStyle, useThemeRoot, type Theme, type T export { Icon, IconsProvider, ICON_NAMES, type DropOption, type IconName, type Icons } from './react/edit/Toolbar' export { OfficeUIProvider, UIComponentsProvider, type ButtonProps, type DialogAction, type DialogProps, type SelectProps, type ToastProps, type UIComponents } from './react/ui' export { StringsProvider, useStrings, resolveStrings, en, type Strings, type StringsOverride, type Locale } from './react/strings' +export { ViewerController, createViewerController, useViewerState, type ViewerState, type ViewerOutline, type OutlineItem } from './react/controller' export { DocumentClient, setDefaultWorker, type OpenOptions } from './core/worker/client' export type { DocSource } from './core/source' diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx index e605850..ab9feab 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -8,6 +8,7 @@ import { StatusContext } from './common/Status' import { ConfirmDialog, PromptDialog, Toast } from './common/Dialog' import { download, Icon, IconsProvider, type Icons } from './edit/Toolbar' import { UIComponentsProvider, type UIComponents } from './ui' +import { ViewerController } from './controller' import { DetailsDialog } from './file/DetailsDialog' import { FileMenu, useFileActions, type FileMenuItem } from './file/FileMenu' import { importFile, type Imported } from './file/importFile' @@ -122,6 +123,17 @@ export interface DocViewerProps { locale?: Locale /** Texts replacing the enclosing provider's or English texts, key by key (see `Strings`): a group may be given in part, e.g. `{ file: { menu: 'Datei' } }`. */ strings?: StringsOverride + /** + * The viewer's state and commands for the host (`createViewerController()`): zoom, page, outline, editing, unsaved + * changes, save, undo… Subscribe to it to draw your own controls; see `headless`. + */ + controller?: ViewerController + /** + * The document alone: no top bar, zoom control, outline panel, sheet tabs or slide list (the host draws its own, + * driven by `controller`). While editing, the formatting toolbar keeps its row. The top bar shows when `toolbar` is + * set explicitly. Default false. + */ + headless?: boolean } const EXT: Record = { docx: '.docx', xlsx: '.xlsx', pptx: '.pptx' } @@ -153,7 +165,12 @@ export function DocViewer(props: DocViewerProps) { function Viewer(props: DocViewerProps) { const t = useStrings() const fmtBytes = (n: number) => formatBytes(t, n) - const { src, name, className, style, toolbar = true, toolbarExtra, zoom, thumbnails, headers, credentials, worker, styleTarget, theme, onLoad, onError } = props + const { src, name, className, style, toolbarExtra, zoom, thumbnails, headers, credentials, worker, styleTarget, theme, onLoad, onError } = props + const headless = !!props.headless + const toolbar = props.toolbar ?? !headless + // without a controller from the host the viewer keeps its own: the view publishes to one either way + const ownCtl = useMemo(() => new ViewerController(), []) + const ctl = props.controller ?? ownCtl const root = useThemeRoot(theme, style) const { allowEdit = true, allowSave = true, allowDownload = true, fileMenu = true, allowOpen = true, captureSelectAll = true, onSave, onDirtyChange } = props const [editing, setEditing] = useState(!!props.editable) @@ -305,9 +322,12 @@ function Viewer(props: DocViewerProps) { cmCtl.select(root) }, [cmCtl, cmFocus, cmState.rev]) + // once per opened document, also when the host passes a new callback on every render + const onLoadRef = useRef(onLoad) + onLoadRef.current = onLoad useEffect(() => { - if (client) onLoad?.(client) - }, [client, onLoad]) + if (client) onLoadRef.current?.(client) + }, [client]) useEffect(() => { if (error) onError?.(error) }, [error, onError]) @@ -385,8 +405,8 @@ function Viewer(props: DocViewerProps) { // next to its source, the document is a preview: it is edited through the source const docEditable = editing && canEdit && !codeShown const api = useMemo( - () => ({ bar: barEl, editable: docEditable, setDirty: setDocDirty, save, canDownload: allowDownload, client, fileOps, selectAll }), - [barEl, docEditable, setDocDirty, save, allowDownload, client], + () => ({ bar: barEl, editable: docEditable, setDirty: setDocDirty, save, canDownload: allowDownload, client, fileOps, selectAll, ctl, headless }), + [barEl, docEditable, setDocDirty, save, allowDownload, client, ctl, headless], ) const editSource = (text: string) => { @@ -541,6 +561,25 @@ function Viewer(props: DocViewerProps) { const busy = loading || (!!progress && pct < 100) const title = renamed ?? client?.name ?? docName ?? (typeof src === 'string' ? decodeURIComponent(src.split(/[?#]/)[0].split('/').pop() ?? '') : (src as File | undefined)?.name) ?? '' + // ---- controller: the viewer's part of the state, and its commands ---- + const editAllowed = allowEdit && !readOnly && !codeShown + useEffect(() => { + ctl.update({ kind: client?.kind ?? null, loading: busy, editing: docEditable, canEdit: editAllowed && canEdit, dirty, saving }) + }, [ctl, client, busy, docEditable, editAllowed, canEdit, dirty, saving]) + const commands = useRef({ editAllowed, save, fileActions, cmCtl }) + commands.current = { editAllowed, save, fileActions, cmCtl } + useEffect(() => { + ctl.attachViewer({ + setEditing: (on) => { + if (!on || commands.current.editAllowed) setEditing(on) + }, + save: () => commands.current.save(), + fileAction: (id) => commands.current.fileActions.run(id), + toggleComments: (open) => commands.current.cmCtl?.toggle(open), + }) + return () => ctl.attachViewer(null) + }, [ctl]) + let body: ReactNode if (error) { body = ( @@ -568,7 +607,7 @@ function Viewer(props: DocViewerProps) { return ( -
+
{toolbar && (
{client && {client.info?.from ?? client.info?.converted ?? (client.info?.imported ? IMPORTED_BADGE[client.info.imported] : client.kind)}} @@ -622,7 +661,7 @@ function Viewer(props: DocViewerProps) {
)} - {toolbar && client && docEditable &&
} + {(toolbar || headless) && client && docEditable &&
}
{codeShown && (
diff --git a/src/react/common/Slots.tsx b/src/react/common/Slots.tsx index b5541e5..f55aafa 100644 --- a/src/react/common/Slots.tsx +++ b/src/react/common/Slots.tsx @@ -3,6 +3,7 @@ import { createPortal } from 'react-dom' import { ToolbarRow } from '../edit/Toolbar' import type { DocumentClient } from '../../core/worker/client' import type { Printable } from '../file/print' +import type { ViewerController } from '../controller' /** What the active view offers to the File menu. */ export interface FileOps { @@ -33,6 +34,10 @@ export interface ViewerApi { fileOps: { current: FileOps | null } /** set by the mounted view (see useSelectAll): Ctrl/⌘+A */ selectAll: { current: (() => void) | null } + /** the viewer's controller: the view publishes its state and registers its commands there */ + ctl: ViewerController | null + /** the host draws the controls: the view shows no zoom, outline, sheet tabs or slide list of its own */ + headless: boolean } export const ViewerContext = createContext({ @@ -44,6 +49,8 @@ export const ViewerContext = createContext({ client: null, fileOps: { current: null }, selectAll: { current: null }, + ctl: null, + headless: false, }) export const useViewer = () => useContext(ViewerContext) diff --git a/src/react/common/Status.tsx b/src/react/common/Status.tsx index 61b8bce..a1cefea 100644 --- a/src/react/common/Status.tsx +++ b/src/react/common/Status.tsx @@ -1,13 +1,17 @@ import { createContext, useContext, useEffect } from 'react' import { createPortal } from 'react-dom' +import { useViewer } from './Slots' /** Toolbar slot provided by DocViewer; views portal their status text into it (no parent re-render). */ export const StatusContext = createContext(null) +/** The view's status line: in the viewer's top bar, and in its controller's state (a headless viewer has no bar). */ export function Status({ text, onStatus }: { text: string; onStatus?: (s: string) => void }) { const el = useContext(StatusContext) + const { ctl } = useViewer() useEffect(() => { onStatus?.(text) - }, [text, onStatus]) + ctl?.update({ status: text }) + }, [text, onStatus, ctl]) return el ? createPortal(text, el) : null } diff --git a/src/react/common/ZoomControl.tsx b/src/react/common/ZoomControl.tsx index 2e8ac0d..c90cb94 100644 --- a/src/react/common/ZoomControl.tsx +++ b/src/react/common/ZoomControl.tsx @@ -5,10 +5,14 @@ export type Zoom = number | 'fit' const STEPS = [0.25, 0.33, 0.5, 0.67, 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3] +/** the zoom step after `effective` in direction `dir`, or undefined at the end of the range */ +export function stepZoom(effective: number, dir: 1 | -1): number | undefined { + return dir > 0 ? STEPS.find((s) => s > effective + 0.001) : [...STEPS].reverse().find((s) => s < effective - 0.001) +} + export function ZoomControl({ zoom, effective, onChange }: { zoom: Zoom; effective: number; onChange: (z: Zoom) => void }) { const step = (dir: 1 | -1) => { - const cur = effective - const next = dir > 0 ? STEPS.find((s) => s > cur + 0.001) : [...STEPS].reverse().find((s) => s < cur - 0.001) + const next = stepZoom(effective, dir) if (next) onChange(next) } const t = useStrings() diff --git a/src/react/controller.ts b/src/react/controller.ts new file mode 100644 index 0000000..e7af907 --- /dev/null +++ b/src/react/controller.ts @@ -0,0 +1,227 @@ +/** + * A viewer's controller: what the shown document's view is doing (zoom, page, outline, editing, unsaved changes) and the + * commands that drive it, for a host that draws its own controls around a headless viewer + * (``). Framework-free: `subscribe` + `snapshot` (for `useSyncExternalStore` or any + * store), state replaced as a whole on every change (`rev` counts them). The viewer and its mounted view publish their + * state and register the commands they can run; a command with nobody to run it does nothing. + */ +import { useEffect, useSyncExternalStore } from 'react' +import type { DocKind } from '../core/opc' +import { stepZoom, type Zoom } from './common/ZoomControl' +import { useLatest } from './common/hooks' + +/** an entry of the outline: a document's heading, a workbook's sheet, a presentation's slide */ +export interface OutlineItem { + id: string + title: string + /** 0 for the top level (headings only go deeper) */ + level: number + /** the one in view */ + current: boolean +} + +export interface ViewerOutline { + kind: 'headings' | 'sheets' | 'slides' + items: OutlineItem[] +} + +export interface ViewerState { + /** counts the changes */ + rev: number + /** the open document's kind, null before one is open */ + kind: DocKind | null + /** loading or downloading */ + loading: boolean + editing: boolean + /** whether editing is possible (allowed, and the file is not view only) */ + canEdit: boolean + /** unsaved changes */ + dirty: boolean + saving: boolean + canUndo: boolean + canRedo: boolean + /** `value` as set ('fit' or a factor), `effective` the factor it comes to; null where the view has no zoom (spreadsheets) */ + zoom: { value: Zoom; effective: number } | null + /** the page or slide in view, from 1, and how many there are (0 while a document is still being laid out) */ + page: { current: number; count: number } | null + outline: ViewerOutline | null + /** the view's status line ("Page 2 of 7 · 1,204 words") */ + status: string +} + +/** commands a mounted view runs (each optional: a spreadsheet has no zoom) */ +export interface ViewCommands { + setZoom?(z: Zoom): void + goto?(id: string): void + gotoPage?(n: number): void + undo?(): void + redo?(): void + present?(): void +} + +/** commands the viewer runs */ +export interface ViewerCommands { + setEditing(on: boolean): void + save(): Promise + fileAction(id: string): void + toggleComments(open?: boolean): void +} + +/** the view's part of the state, cleared when a view goes */ +const VIEW_STATE = { canUndo: false, canRedo: false, zoom: null, page: null, outline: null, status: '' } as const + +/** the viewer's part of the state, cleared when the viewer goes, so a controller that outlives it shows no document */ +const VIEWER_STATE = { kind: null, loading: false, editing: false, canEdit: false, dirty: false, saving: false } as const + +const EMPTY: ViewerState = { rev: 0, ...VIEWER_STATE, ...VIEW_STATE } + +/** equal for the state's purposes: the same primitive, or the same JSON (small objects and the outline) */ +function same(a: unknown, b: unknown): boolean { + if (a === b) return true + if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false + return JSON.stringify(a) === JSON.stringify(b) +} + +export class ViewerController { + private state: ViewerState = EMPTY + private subs = new Set<() => void>() + private watchers = new Set<() => void>() + private view: ViewCommands | null = null + private viewer: ViewerCommands | null = null + + subscribe = (fn: () => void) => { + const first = this.subs.size === 0 + this.subs.add(fn) + if (first) for (const w of this.watchers) w() + return () => { + this.subs.delete(fn) + } + } + + /** whether a host reads the state: views skip work that only the controller's state needs while nobody does */ + get observed(): boolean { + return this.subs.size > 0 + } + + /** calls `fn` when the first subscriber arrives */ + watchObserved(fn: () => void): () => void { + this.watchers.add(fn) + return () => { + this.watchers.delete(fn) + } + } + + snapshot = () => this.state + + // ---------------------------------------------------------------- commands + + setEditing(on: boolean) { + this.viewer?.setEditing(on) + } + + /** builds the edited file and hands it to `onSave` (or downloads it) */ + save(): Promise { + return this.viewer?.save() ?? Promise.resolve() + } + + undo() { + this.view?.undo?.() + } + + redo() { + this.view?.redo?.() + } + + setZoom(z: Zoom) { + this.view?.setZoom?.(z) + } + + zoomIn() { + this.zoomStep(1) + } + + zoomOut() { + this.zoomStep(-1) + } + + /** shows an outline entry: scrolls to a heading, shows a sheet or a slide */ + goto(id: string) { + this.view?.goto?.(id) + } + + /** scrolls to a page or slide, from 1 */ + gotoPage(n: number) { + this.view?.gotoPage?.(n) + } + + /** a presentation as a slideshow, from the slide in view */ + present() { + this.view?.present?.() + } + + print() { + this.fileAction('print') + } + + /** a File menu action by its id: 'pdf', 'html', 'text:md', 'details', 'rename'… (see FileMenu) */ + fileAction(id: string) { + this.viewer?.fileAction(id) + } + + /** the comments panel open (true), closed (false) or the other way round */ + toggleComments(open?: boolean) { + this.viewer?.toggleComments(open) + } + + private zoomStep(dir: 1 | -1) { + const z = this.state.zoom + const next = z && stepZoom(z.effective, dir) + if (next) this.setZoom(next) + } + + // ---------------------------------------------------------------- published by the viewer and its view + + /** @internal the state changed: only what differs counts as a change */ + update(p: Partial>) { + let changed = false + for (const k of Object.keys(p) as (keyof typeof p)[]) { + if (!same(this.state[k], p[k])) { + changed = true + break + } + } + if (!changed) return + this.state = { ...this.state, ...p, rev: this.state.rev + 1 } + for (const fn of this.subs) fn() + } + + /** @internal the mounted view's commands; null when it goes (its state is cleared) */ + attachView(c: ViewCommands | null) { + this.view = c + if (!c) this.update(VIEW_STATE) + } + + /** @internal the viewer's commands; null when it goes (its state is cleared) */ + attachViewer(c: ViewerCommands | null) { + this.viewer = c + if (!c) this.update(VIEWER_STATE) + } +} + +export const createViewerController = () => new ViewerController() + +/** The controller's state, rendering again whenever it changes: for a host's own controls in React. */ +export function useViewerState(ctl: ViewerController): ViewerState { + return useSyncExternalStore(ctl.subscribe, ctl.snapshot, ctl.snapshot) +} + +/** Registers a view's commands (the latest closures each render) while it is mounted. */ +export function useViewCommands(ctl: ViewerController | null, commands: ViewCommands) { + const latest = useLatest(commands) + useEffect(() => { + if (!ctl) return + const call = (k: K) => ((...a: unknown[]) => (latest.current[k] as ((...x: unknown[]) => void) | undefined)?.(...a)) as ViewCommands[K] + ctl.attachView({ setZoom: call('setZoom'), goto: call('goto'), gotoPage: call('gotoPage'), undo: call('undo'), redo: call('redo'), present: call('present') }) + return () => ctl.attachView(null) + }, [ctl, latest]) +} diff --git a/src/react/docx/DocxEditor.ts b/src/react/docx/DocxEditor.ts index d99a918..7e5442e 100644 --- a/src/react/docx/DocxEditor.ts +++ b/src/react/docx/DocxEditor.ts @@ -204,6 +204,8 @@ export class DocxEditor implements RichHost { /** paragraphs whose look on screen may be behind their style / list: a conversion was asked, none was applied yet */ private stale = new Set() onState?: (s: FormatState | null) => void + /** whether undo / redo can run, after every change of the selection or the document (the viewer's controller) */ + onHistory?: (canUndo: boolean, canRedo: boolean) => void /** image selection changed (overlay with resize handles) */ onImage?: (img: FormatState['img'] | null) => void /** style list changed (a built-in style was added to the document, a style got another look) */ @@ -732,7 +734,18 @@ export class DocxEditor implements RichHost { return list.map((b) => (b.t === 'p' && b.pid !== undefined && cur.has(b.pid) ? cur.get(b.pid)! : b)) } + // the state published while an entry is applied comes before its move to the other stack: publish again after undo() { + this.undoStep() + this.onHistory?.(this.canUndo, this.canRedo) + } + + redo() { + this.redoStep() + this.onHistory?.(this.canUndo, this.canRedo) + } + + private undoStep() { const e = this.history.pop() if (!e) return if (e.group) { @@ -740,7 +753,7 @@ export class DocxEditor implements RichHost { for (const part of [...e.group].reverse()) { this.history.push(part) const n = this.future.length - this.undo() + this.undoStep() if (this.future.length > n) this.future.pop() } this.future.push(e) @@ -768,14 +781,14 @@ export class DocxEditor implements RichHost { this.future.push(e) } - redo() { + private redoStep() { const e = this.future.pop() if (!e) return if (e.group) { for (const part of e.group) { this.future.push(part) const n = this.history.length - this.redo() + this.redoStep() if (this.history.length > n) this.history.pop() } this.history.push(e) @@ -1882,6 +1895,7 @@ export class DocxEditor implements RichHost { const st = sel ? this.state(sel) : null this.onState?.(st) this.onImage?.(st?.img ?? null) + this.onHistory?.(this.canUndo, this.canRedo) } onSelection(sel: Sel | null) { diff --git a/src/react/docx/DocxToolbar.tsx b/src/react/docx/DocxToolbar.tsx index 719bdf4..cbb6950 100644 --- a/src/react/docx/DocxToolbar.tsx +++ b/src/react/docx/DocxToolbar.tsx @@ -101,7 +101,8 @@ export function DocxToolbar(props: { styles: StyleInfo[] onFind: () => void outline: boolean - onOutline: () => void + /** the outline panel opened / closed; no button without it (a headless viewer: the host shows the outline) */ + onOutline?: () => void painter: boolean onLink: () => void image: ImageActions @@ -302,7 +303,7 @@ export function DocxToolbar(props: { editor.insertPageBreak()} /> editor.clearFormat()} /> - + {props.onOutline && } ) diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index 4d9d137..2559af9 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -8,6 +8,7 @@ import { claimFocus, lowerIndex, useForceUpdate, useIsoLayoutEffect, useScroll, import { useFileOps, useSelectAll, useViewer } from '../common/Slots' import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' +import { useViewCommands } from '../controller' import { ContextMenu, MOD, type MenuItem } from '../common/ContextMenu' import { PromptDialog, Toast, type PromptSpec } from '../common/Dialog' import { domFromPos, getSel, opInsert, posFromDom, selPoints } from '../edit/input' @@ -751,12 +752,19 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp // eslint-disable-next-line react-hooks/exhaustive-deps [outline, version, titleId], ) - const topBlock = pages[Math.max(0, cur - 1)]?.start ?? 0 - const activeHeading = headings.reduce((acc, h, i) => (h.bi <= Math.max(topBlock, caretBi) ? i : acc), -1) + // the heading jumped to counts as current while its page is the one in view, though it may sit + // below headings further up that page + const [jumpBi, setJumpBi] = useState(-1) + const curPage = pages[Math.max(0, cur - 1)] + const topBlock = curPage?.start ?? 0 + const jumped = curPage && jumpBi >= curPage.start && jumpBi < curPage.end ? jumpBi : -1 + const atBlock = Math.max(topBlock, caretBi, jumped) + const activeHeading = headings.reduce((acc, h, i) => (h.bi <= atBlock ? i : acc), -1) const gotoBlock = (bi: number) => { const sc = scrollRef.current const pi = pages.findIndex((p) => bi >= p.start && bi < p.end) if (!sc || pi < 0) return + setJumpBi(bi) sc.scrollTop = Math.max(0, tops[pi] - 16) requestAnimationFrame(() => requestAnimationFrame(() => { @@ -767,6 +775,51 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp ) } + // ---- controller: zoom, page, headings, undo ---- + const { ctl, headless } = viewer + // the headings for the controller: read again once the document stops changing, not on every keystroke + const [ctlHeadings, setCtlHeadings] = useState<{ bi: number; lvl: number; text: string }[]>([]) + useEffect(() => { + if (!ctl) return + const id = setTimeout(() => setCtlHeadings(outlineOf(st.blocks, titleId)), 150) + return () => clearTimeout(id) + }, [ctl, version, titleId, st]) + const ctlActive = ctlHeadings.reduce((acc, h, i) => (h.bi <= atBlock ? i : acc), -1) + useEffect(() => { + ctl?.update({ zoom: { value: zoom, effective: z } }) + }, [ctl, zoom, z]) + useEffect(() => { + ctl?.update({ page: { current: cur, count: pageCount } }) + }, [ctl, cur, pageCount]) + useEffect(() => { + ctl?.update({ outline: { kind: 'headings', items: ctlHeadings.map((h, i) => ({ id: String(h.bi), title: h.text, level: h.lvl, current: i === ctlActive })) } }) + }, [ctl, ctlHeadings, ctlActive]) + // undo and redo run only while editing (below), so they are offered only then + useEffect(() => { + if (!ctl) return + const publish = (canUndo: boolean, canRedo: boolean) => ctl.update({ canUndo: isEditing && canUndo, canRedo: isEditing && canRedo }) + publish(editor.canUndo, editor.canRedo) + editor.onHistory = publish + return () => { + editor.onHistory = undefined + } + }, [ctl, editor, isEditing]) + useViewCommands(ctl, { + setZoom, + goto: (id) => gotoBlock(Number(id)), + gotoPage: (n) => { + const sc = scrollRef.current + const top = tops[Math.min(Math.max(1, n), tops.length) - 1] + if (sc && top !== undefined) sc.scrollTop = Math.max(0, top - 16) + }, + undo: () => { + if (isEditing) editor.undo() + }, + redo: () => { + if (isEditing) editor.redo() + }, + }) + return (
setFind((f) => ({ ...f, open: true }))} outline={outline} - onOutline={() => setOutline((o) => !o)} + onOutline={headless ? undefined : () => setOutline((o) => !o)} painter={painter} onLink={askLink} image={imageActions} @@ -909,7 +962,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp onNotice={setToast} /> )} - {!isEditing && done && ( + {!isEditing && done && !headless && ( @@ -922,7 +975,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp {prompt && setPrompt(null)} />} {toast && setToast(null)} />} {cmMarks.length > 0 && } - + {!headless && }
) diff --git a/src/react/pptx/PptxView.tsx b/src/react/pptx/PptxView.tsx index 31c8666..f3ddb07 100644 --- a/src/react/pptx/PptxView.tsx +++ b/src/react/pptx/PptxView.tsx @@ -6,6 +6,7 @@ import { useFileOps, useViewer, useSelectAll } from '../common/Slots' import { slidesToText } from '../file/text' import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' +import { useViewCommands } from '../controller' import { getSel } from '../edit/input' import { PptxEditor } from './PptxEditor' import { PptxToolbar, type AlignTo, type Arrange, type Rotate, type SlideCmd } from './PptxToolbar' @@ -23,21 +24,24 @@ interface SlideCache { models: Map pending: Map> listeners: Map void>> + /** told of every replaced slide, whichever its index */ + edits: Set<(index: number, m: SlideModel) => void> } const caches = new WeakMap() function cacheFor(client: DocumentClient): SlideCache { let c = caches.get(client) - if (!c) caches.set(client, (c = { models: new Map(), pending: new Map(), listeners: new Map() })) + if (!c) caches.set(client, (c = { models: new Map(), pending: new Map(), listeners: new Map(), edits: new Set() })) return c } -/** replaces a cached slide (after an edit) and notifies mounted views */ +/** replaces a cached slide (after an edit, here or a collaborator's) and notifies mounted views */ function putSlide(client: DocumentClient, index: number, m: SlideModel) { const c = cacheFor(client) c.models.set(index, m) for (const fn of c.listeners.get(index) ?? []) fn(m) + for (const fn of c.edits) fn(index, m) } /** forget every cached slide (after slides were added / removed / reordered) */ @@ -209,7 +213,7 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t const thumbRef = useRef(null) const thumbScroll = useScroll(thumbRef) const [zoom, setZoom] = useState(initialZoom) - const showThumbs = thumbnails && rootSize.w >= 720 && meta.count > 1 + const showThumbs = thumbnails && !viewer.headless && rootSize.w >= 720 && meta.count > 1 const [, bump] = useForceUpdate() const caretAt = useRef<{ x: number; y: number } | null>(null) const textRoot = useRef(null) @@ -593,6 +597,62 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t if (el) el.scrollTop = PAD + Math.max(0, Math.min(meta.count - 1, i)) * pitch - Math.max(0, (size.h - slideH) / 2) } + // ---- controller: zoom, slide, the slides as the outline, undo, slideshow ---- + const { ctl, headless } = viewer + // slide titles for the outline, read only while a host reads the controller: from the slides' XML in one call + // once the first slides are shown, then from each slide model an edit puts in the cache + const [observed, setObserved] = useState(() => !!ctl?.observed) + useEffect(() => { + if (!ctl) return + if (ctl.observed) setObserved(true) + return ctl.watchObserved(() => setObserved(true)) + }, [ctl]) + const [titles, setTitles] = useState([]) + useEffect(() => { + if (!observed) return + let live = true + const timer = setTimeout(() => { + client + .call('pptx.titles') + .then((t) => live && setTitles(t)) + .catch(() => {}) + }, 800) + return () => { + live = false + clearTimeout(timer) + } + }, [observed, client, meta.count, slidesVer]) + useEffect(() => { + if (!observed) return + const edits = cacheFor(client).edits + const on = (i: number, m: SlideModel) => setTitles((t) => (t[i] === (m.title ?? '') ? t : Object.assign([...t], { [i]: m.title ?? '' }))) + edits.add(on) + return () => { + edits.delete(on) + } + }, [observed, client]) + useEffect(() => { + ctl?.update({ zoom: { value: zoom, effective: scale } }) + }, [ctl, zoom, scale]) + useEffect(() => { + ctl?.update({ + page: { current: current + 1, count: meta.count }, + outline: { kind: 'slides', items: Array.from({ length: meta.count }, (_, i) => ({ id: String(i), title: titles[i] || `${str.pptx.slide} ${i + 1}`, level: 0, current: i === current })) }, + }) + }, [ctl, current, meta.count, titles, str]) + // as the toolbar's buttons: undo while there is a shape edit or text is being edited; redo whenever editing (no redo depth is kept) + useEffect(() => { + ctl?.update({ canUndo: viewer.editable && (undoDepth > 0 || editor.active), canRedo: viewer.editable }) + }) + useViewCommands(ctl, { + setZoom, + goto: (id) => go(Number(id)), + gotoPage: (n) => go(n - 1), + undo: () => viewer.editable && (editor.active ? editor.undo() : void undoShapes(false)), + redo: () => viewer.editable && (editor.active ? editor.redo() : void undoShapes(true)), + present: () => setPresenting(current), + }) + // ---- comments: a thread points at a point of a slide ---- const cm = useCommentsCtl() const cmState = useCommentsState(cm) @@ -788,8 +848,8 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t {slots}
- - {!viewer.editable && ( + {!headless && } + {!viewer.editable && !headless && (
} {phase < 2 && } diff --git a/e2e/collab.spec.ts b/e2e/collab.spec.ts index a3c83b3..dc26187 100644 --- a/e2e/collab.spec.ts +++ b/e2e/collab.spec.ts @@ -1,7 +1,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test' import { readFileSync } from 'node:fs' import { rebuildZip } from '../src/core/zipwrite' -import { SAMPLES, useBrowser, viewer, fromB64, xlsxSheet } from './harness' +import { SAMPLES, useBrowser, viewer, fromB64, xlsxSheet, docxParas, paraText, runsOf } from './harness' useBrowser() @@ -182,3 +182,37 @@ describe('docx: a built-in style the document lacks', () => { expect(v.errors).toEqual([]) }) }) + + +test('docx: host format uses the published selection after a peer inserts an earlier paragraph', async () => { + const id = await room('sample.docx') + const joinDoc = (user: string) => viewer({ src: `${HTTP}/rooms/${id}/file?seq=0`, name: 'shared.docx', collab: `ws://localhost:${PORT}/collab`, room: id, user, base: 0, editable: true, controller: true, onSave: true }) + const a = await joinDoc('Ann') + const b = await joinDoc('Bob') + for (const v of [a, b]) await v.page.locator('.de-collab-live').waitFor({ timeout: 20_000 }) + await b.selectText('document') + await b.page.evaluate(() => { + const input = document.createElement('input') + input.id = 'collab-format-host'; input.style.cssText = 'position:fixed;top:0;left:0;z-index:999999' + document.body.append(input) + }) + await b.page.locator('#collab-format-host').click() + await a.selectText('Quarterly Report', 'start') + await a.page.keyboard.type('Peer prefix') + await a.page.keyboard.press('Enter') + await b.page.waitForFunction(() => document.querySelector('.de-pages')?.textContent?.includes('Peer prefix')) + await b.page.waitForTimeout(500) + expect(await b.page.locator('#collab-format-host').evaluate((el) => el === document.activeElement)).toBe(true) + expect(await b.page.evaluate(() => window.__ctl.snapshot().format)).not.toBeNull() + await b.page.evaluate(() => window.__ctl.format({ op: 'size', pt: 31 })) + await b.page.waitForTimeout(800) + expect(await b.page.evaluate(() => window.__ctl.snapshot().format?.size)).toBe(31) + expect(await b.page.locator('#collab-format-host').evaluate((el) => el === document.activeElement)).toBe(true) + for (const v of [a, b]) { + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save')).b64 as string) + const p = (await docxParas(bytes)).find((p) => paraText(p).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text === 'document')?.s.sz).toBe(31) + expect(v.errors).toEqual([]) + } +}) diff --git a/e2e/format-controls.spec.ts b/e2e/format-controls.spec.ts index aca280a..a29f276 100644 --- a/e2e/format-controls.spec.ts +++ b/e2e/format-controls.spec.ts @@ -1,9 +1,11 @@ +import { strFromU8, unzipSync } from 'fflate' import { expect, test } from 'bun:test' -import { docxParas, fromB64, openFile, paraText, runsOf, useBrowser, viewer, type Viewer } from './harness' +import { docxParas, fromB64, openFile, xlsxSheet, paraText, runsOf, useBrowser, viewer, type Viewer } from './harness' useBrowser() const state = (v: Viewer) => v.page.evaluate(() => window.__ctl.snapshot()) const settle = (v: Viewer) => v.page.waitForTimeout(150) +const formatting = (s: Awaited>) => ({ format: s.format, dirty: s.dirty, canUndo: s.canUndo, canRedo: s.canRedo }) async function selectTarget(v: Viewer, kind: 'docx' | 'pptx', index = 0) { if (kind === 'docx' && index === 0) return v.selectText('document') @@ -176,3 +178,187 @@ for (const kind of ['docx', 'pptx'] as const) { expect(v.errors).toEqual([]) }) } + + +test('xlsx: live host number input retains focus and saved cell value through typing and Backspace', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.xlsx', editable: true, headless: true, onSave: true }) + await v.typeCell('B2', 'keep-value') + await v.clickCell('B2') + await v.page.evaluate(() => { + const input = document.createElement('input') + input.type = 'number'; input.id = 'host-size'; input.value = '' + input.style.cssText = 'position:fixed;top:0;left:0;z-index:999999' + input.oninput = () => window.__ctl.format({ op: 'size', pt: input.valueAsNumber }) + document.body.append(input) + }) + const input = v.page.locator('#host-size') + await input.click() + await v.page.keyboard.type('14', { delay: 200 }) + await settle(v) + expect(await input.inputValue()).toBe('14') + expect(await input.evaluate((el) => el === document.activeElement)).toBe(true) + await v.page.keyboard.press('Backspace') + await settle(v) + expect(await input.inputValue()).toBe('1') + await v.page.keyboard.type('4') + await settle(v) + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save')).b64 as string) + expect((await xlsxSheet(bytes)).cell('B2')).toBe('keep-value') + expect((await state(v)).format?.size).toBe(14) + expect(strFromU8(unzipSync(bytes)['xl/styles.xml'])).toContain('val="14"') + // Direct calls retain whichever element the host focused; the grid's keyboard still works afterward. + await v.page.evaluate(() => window.__ctl.format({ op: 'size', pt: 18 })) + await settle(v) + expect(await input.evaluate((el) => el === document.activeElement)).toBe(true) + await v.page.evaluate(() => window.__ctl.undo()) + await settle(v) + expect((await state(v)).format?.size).toBe(14) + await v.page.evaluate(() => window.__ctl.redo()) + await settle(v) + expect((await state(v)).format?.size).toBe(18) + await v.page.evaluate(() => window.__ctl.undo()) + await settle(v) + await v.page.evaluate((data) => window.__setProps({ src: new Blob([new Uint8Array(data)]), name: 'reopened.xlsx' }), Array.from(bytes)) + await v.waitEvent('load', 2) + await v.page.locator('.de-grid').waitFor() + await settle(v) + await v.clickCell('B2') + expect(await v.shown('B2')).toBe('keep-value') + expect((await state(v)).format?.size).toBe(14) + await v.page.keyboard.press('ArrowRight') + expect(await v.page.locator('.de-fx-ref').innerText()).toBe('C2') + await v.page.evaluate(() => window.__ctl.goto('1')) + await settle(v) + expect((await state(v)).outline?.items.find((i) => i.current)?.id).toBe('1') + + expect(v.errors).toEqual([]) +}) + +test('docx: controlled host rerenders with inline callbacks preserve the logical target', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', editable: true, headless: true, onSave: true, renderHost: true }) + await v.selectText('document') + const input = v.page.getByLabel('React host size') + await input.click() + await settle(v) + expect(await input.isEnabled()).toBe(true) + await input.selectText() + await v.page.keyboard.type('14', { delay: 200 }) + await settle(v) + expect(await input.inputValue()).toBe('14') + expect((await state(v)).format?.size).toBe(14) + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save')).b64 as string) + expect(runsOf((await docxParas(bytes)).find((p) => paraText(p).startsWith('This document'))!).find((r) => r.text === 'document')?.s.sz).toBe(14) +}) + +test('docx without controller: Ctrl+S then Ctrl+K preserves selection and saves the link', async () => { + const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true }) + await v.selectText('document') + await v.page.keyboard.press('Control+s') + await v.waitEvent('save') + await v.page.keyboard.press('Control+k') + await v.page.locator('.de-dialog input').fill('https://example.org/after-save') + await v.page.keyboard.press('Enter') + await settle(v) + const bytes = (await v.save()).bytes + const p = (await docxParas(bytes)).find((p) => paraText(p).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text === 'document')?.href).toBe('https://example.org/after-save') + expect(v.errors).toEqual([]) +}) + +for (const kind of ['docx', 'pptx'] as const) { + test(`${kind}: a host format command does not suppress later undo caret restoration`, async () => { + const v = await viewer({ controller: true, src: `samples/sample.${kind}`, editable: true, headless: true, onSave: true }) + await selectTarget(v, kind) + const original = (await state(v)).format!.size + await v.page.evaluate(() => { + const input = document.createElement('input') + input.id = 'focus-host'; input.style.cssText = 'position:fixed;top:0;left:0;z-index:999999' + const undo = document.createElement('button') + undo.id = 'undo-host'; undo.textContent = 'Undo host' + undo.style.cssText = 'position:fixed;top:0;left:220px;z-index:999999' + undo.onclick = window.__ctl.undo + document.body.append(input, undo) + }) + await v.page.locator('#focus-host').click() + await v.page.evaluate(() => window.__ctl.format({ op: 'size', pt: 35 })) + await settle(v) + expect(await v.page.locator('#focus-host').evaluate((el) => el === document.activeElement)).toBe(true) + await v.page.locator('#undo-host').click() + await settle(v) + expect(await v.page.evaluate(() => document.activeElement?.matches('.de-pages, .de-txt-edit'))).toBe(true) + expect((await state(v)).format?.size).toBe(original) + expect(await v.page.evaluate(() => getSelection()?.toString())).toBe(kind === 'docx' ? 'document' : 'office-engine') + await v.page.evaluate(() => window.__ctl.redo()) + await settle(v) + expect((await state(v)).format?.size).toBe(35) + expect(v.errors).toEqual([]) + }) +} + +for (const kind of ['docx', 'xlsx', 'pptx'] as const) { + test(`${kind}: invalid runtime commands preserve dirty/history/XML and opaque colors save and reopen`, async () => { + const v = await viewer({ controller: true, src: `samples/sample.${kind}`, editable: true, headless: true, onSave: true }) + if (kind === 'xlsx') await v.clickCell('B2') + else await selectTarget(v, kind) + const invalid = async () => { + await v.page.evaluate(() => { + const commands = [ + { op: 'bold' }, { op: 'font', name: '' }, { op: 'font', name: ' ' }, + ...['red', 'rgb(255,0,0)', '#ff000080'].flatMap((color) => [{ op: 'color', color }, { op: 'highlight', color }]), + ...[0.5, 1000, NaN, Infinity, Number.MIN_VALUE, Number.MAX_VALUE].map((pt) => ({ op: 'size', pt })), + ] + commands.forEach((c) => (window.__ctl.format as (c: unknown) => void)(c)) + }) + await settle(v) + } + const before = await state(v) + await invalid() + expect(formatting(await state(v))).toEqual(formatting(before)) + const path = kind === 'docx' ? 'word/document.xml' : kind === 'pptx' ? 'ppt/slides/slide1.xml' : 'xl/styles.xml' + const saveXML = async () => { + const count = (await v.events('save')).length + await v.page.evaluate(() => window.__ctl.save()) + const bytes = fromB64((await v.waitEvent('save', count + 1)).b64 as string) + return { bytes, xml: strFromU8(unzipSync(bytes)[path]) } + } + const initial = await saveXML() + await v.page.evaluate(() => { + window.__ctl.format({ op: 'color', color: '#123456ff' }) + window.__ctl.format({ op: 'highlight', color: '#abc' }) + }) + await v.page.waitForTimeout(kind === 'pptx' ? 550 : 200) + const colored = await saveXML() + expect(colored.xml).not.toBe(initial.xml) + expect(colored.xml).toMatch(/123456/i) + expect(colored.xml).toMatch(/AABBCC/i) + const stable = await state(v) + await invalid() + expect(formatting(await state(v))).toEqual(formatting(stable)) + expect((await saveXML()).xml).toBe(colored.xml) + await v.page.evaluate((data) => window.__setProps({ src: new Blob([new Uint8Array(data.bytes)]), name: `reopened.${data.kind}` }), { bytes: Array.from(colored.bytes), kind }) + await v.waitEvent('load', 2) + await v.page.waitForTimeout(500) + if (kind === 'xlsx') await v.clickCell('B2') + else await selectTarget(v, kind) + expect((await state(v)).format?.color?.toLowerCase()).toBe('#123456') + expect((await state(v)).format?.highlight?.toLowerCase()).toBe('#aabbcc') + expect(v.errors).toEqual([]) + }) +} + +test('shared SizeBox retains decimal-comma semantics and commits half points once', async () => { + const v = await viewer({ controller: true, src: 'samples/sample.docx', editable: true, onSave: true }) + await v.selectText('document') + const size = v.page.getByRole('textbox', { name: 'Font size', exact: true }) + await size.fill('12,5') + await size.press('Enter') + await settle(v) + expect((await state(v)).format?.size).toBe(12.5) + const p = (await docxParas((await v.save()).bytes)).find((p) => paraText(p).startsWith('This document'))! + expect(runsOf(p).find((r) => r.text === 'document')?.s.sz).toBe(12.5) + await v.page.evaluate(() => window.__ctl.undo()) + await settle(v) + expect((await state(v)).canUndo).toBe(false) +}) diff --git a/src/collab/docx.ts b/src/collab/docx.ts index e19d2c3..08fdd29 100644 --- a/src/collab/docx.ts +++ b/src/collab/docx.ts @@ -666,7 +666,7 @@ export class DocxCollab implements Adapter { /** remembers the selection (by paragraph id + text) before the model changes */ private capture() { if (this.snap || !this.host) return - const focused = !!this.ed.input.readSel() + const focused = this.ed.input.focused && !!this.ed.input.readSel() const sel = this.ed.input.sel() const a = sel && this.toD(sel.a) const f = sel && this.toD(sel.f) @@ -709,6 +709,7 @@ export class DocxCollab implements Adapter { // keep the caret where the user was; never steal focus from other controls this.ed.pendingSel = s.focused ? sel : null if (!s.focused) this.ed.input.lastSel = sel + this.ed.onSelection(sel) } // ---------------------------------------------------------------- presence diff --git a/src/react/controller.ts b/src/react/controller.ts index 7934541..7eb8172 100644 --- a/src/react/controller.ts +++ b/src/react/controller.ts @@ -6,6 +6,7 @@ * state and register the commands they can run; a command with nobody to run it does nothing. */ import { useEffect, useMemo, useSyncExternalStore } from 'react' +import { formatCommand } from './edit/format-values' import type { DocKind } from '../core/opc' import { stepZoom, type Zoom } from './common/ZoomControl' import { useLatest } from './common/hooks' @@ -73,13 +74,14 @@ export interface TextFormat { export type FormatCommand = | { op: 'toggle'; mark: 'bold' | 'italic' | 'underline' | 'strike' } | { op: 'font'; name: string } - /** finite, positive points; invalid sizes do nothing */ + /** 1–400 points, rounded to half points; invalid sizes do nothing */ | { op: 'size'; pt: number } + /** Opaque #rgb, #rrggbb or #rrggbbff; null removes the color. Other CSS colors do nothing. */ | { op: 'color'; color: string | null } | { op: 'highlight'; color: string | null } | { op: 'align'; align: 'left' | 'center' | 'right' | 'justify' } - /** toggles the kind off when already applied; DOCX checks all selected paragraphs, PPTX the first */ - | { op: 'list'; list: 'bullet' | 'number' } + /** Sets every selected paragraph to this kind; null explicitly removes lists. Repeating is idempotent. */ + | { op: 'list'; list: 'bullet' | 'number' | null } | { op: 'clear' } /** the editors' names for the marks */ @@ -218,8 +220,8 @@ export class InternalViewerController { /** formats the selection while editing: `format({ op: 'toggle', mark: 'bold' })`, `format({ op: 'size', pt: 14 })` */ format = (cmd: FormatCommand) => { - if (cmd.op === 'size' && (!Number.isFinite(cmd.pt) || cmd.pt <= 0)) return - this.view?.format?.(cmd) + const command = formatCommand(cmd) + if (command) this.view?.format?.(command) } print = () => { diff --git a/src/react/docx/DocxEditor.ts b/src/react/docx/DocxEditor.ts index 5c4599d..e14c104 100644 --- a/src/react/docx/DocxEditor.ts +++ b/src/react/docx/DocxEditor.ts @@ -194,6 +194,7 @@ export type DocxCommit = { kind: 'paras'; before: Paragraph[]; next: Paragraph[] export class DocxEditor implements RichHost { readonly input: RichInput pendingSel: Sel | null = null + pendingNoRefocus = false styles: StyleInfo[] = [] private history: Entry[] = [] private future: Entry[] = [] @@ -439,6 +440,7 @@ export class DocxEditor implements RichHost { // a collaborator's paragraphs may come with the look a style had before it changed if (opts.label === 'collab') this.catchUp() this.pendingSel = sel + this.pendingNoRefocus = this.input.formatting this.onDirty?.() this.changed() // the caret may not move (formatting): refresh the toolbar from the new runs @@ -895,7 +897,7 @@ export class DocxEditor implements RichHost { } clearFormat() { - this.format({ b: false, i: false, u: 'none', strike: false, hl: undefined }, { b: false, i: false, u: 'none', strike: false, color: null, hl: null, va: null }, { want: true }) + this.format({ b: false, i: false, u: 'none', strike: false, hl: undefined, shd: undefined }, { b: false, i: false, u: 'none', strike: false, color: null, hl: null, va: null }, { want: true }) } setPara(patch: ParaDirty, optimistic: Partial = {}, sel = this.input.sel()) { @@ -910,6 +912,17 @@ export class DocxEditor implements RichHost { this.replace(r.pas, next, sel, { label: 'para', want: true }) } + /** Host API setter; the built-in toolbar retains toggleList. */ + setList(kind: 'bullet' | 'number' | null) { + const sel = this.input.sel() + const r = sel && this.selectedParas(sel) + if (!r || r.pas.every((pa) => { + const p = this.para(pa) + return (p?.pd?.list ?? p?.lst ?? 'none') === (kind ?? 'none') + })) return + this.setPara({ list: kind ?? 'none', ilvl: kind ? 0 : undefined }, {}, sel) + } + toggleList(kind: 'bullet' | 'number') { const sel = this.input.sel() if (!sel) return @@ -1764,6 +1777,7 @@ export class DocxEditor implements RichHost { if (!sel) return this.patchObjects(sel, (x) => (x.t === 'img' ? fn(x) : x)) this.pendingSel = sel + this.pendingNoRefocus = this.input.formatting } /** exact size in pt */ @@ -1881,12 +1895,12 @@ export class DocxEditor implements RichHost { u: !!rs.u && rs.u !== 'none', strike: !!rs.strike, color: rs.color, - hl: rs.hl, + hl: rs.hl ?? rs.shd, sz: rs.sz ?? p.markSz ?? this.defaultSz, font: rs.font ?? p.markFont ?? this.defaultFont, align: p.ps.align ?? 'left', style: p.sid, - lst: p.lst, + lst: p.pd?.list === 'none' ? undefined : p.pd?.list ?? p.lst, canUndo: this.canUndo, canRedo: this.canRedo, } diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index e0b8501..0935dee 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -14,7 +14,7 @@ import { ContextMenu, MOD, type MenuItem } from '../common/ContextMenu' import { PromptDialog, Toast, type PromptSpec } from '../common/Dialog' import { domFromPos, getSel, opInsert, posFromDom, selPoints } from '../edit/input' import { download, Icon, pickFiles } from '../edit/Toolbar' -import { runsText, type RRun } from '../edit/rich' +import { runsText, type RRun, type Sel } from '../edit/rich' import { DocxEditor, type CommentRange, type DocState, type FormatState } from './DocxEditor' import { markCss, useCommentsCtl, useCommentsState, type CommentHost, type PlacedThread } from '../comments/Comments' import { COMMENT_KEYS } from '../comments/CommentsPanel' @@ -271,7 +271,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp // ---- editing wiring ---- useEffect(() => { const el = pagesRef.current - if (!isEditing || !el) return + if (!isEditing || !el) { editor.input.clearSelection(); return } editor.input.attach(el) editor.onDirty = () => viewer.setDirty(true) return () => editor.input.detach() @@ -336,7 +336,9 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp useIsoLayoutEffect(() => { const sel = editor.pendingSel if (!sel || !pagesRef.current) return - if (!editor.input.restore(sel)) { + const noRefocus = editor.pendingNoRefocus + editor.pendingNoRefocus = false + if (!editor.input.restore(sel, noRefocus ? 'preserve' : true)) { // caret paragraph not rendered (scrolled away): bring its page into view, retry next render const bi = Number(sel.f.pa.split('.')[0]) const pi = pages.findIndex((p) => bi >= p.start && bi < p.end) @@ -345,6 +347,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp return } editor.pendingSel = null + if (noRefocus) return // keep the caret visible const ds = getSel(pagesRef.current) const range = ds?.rangeCount ? ds.getRangeAt(0) : null @@ -806,6 +809,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp editor.onHistory = undefined } }, [ctl, editor, isEditing]) + const publishedSelection = useRef(null) const publishFormat = useViewCommands(ctl, { setZoom, goto: (id) => gotoBlock(Number(id)), @@ -821,18 +825,22 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp if (isEditing) editor.redo() }, format: (c) => { - if (isEditing && editor.input.formatSelection()) { - editor.input.preserveControlFocus() - applyDocx(editor, c) - } + const sel = publishedSelection.current + if (isEditing && sel) editor.input.withFormatSelection(sel, () => applyDocx(editor, c)) }, }) useEffect(() => { if (!ctl) return if (!isEditing) return publishFormat(null) - const off = editor.subscribeState((s) => publishFormat(s && editor.input.formatSelection() ? docxFormat(s) : null)) + const off = editor.subscribeState((s) => { + const sel = s && editor.input.formatSelection() + publishedSelection.current = sel + const current = sel && editor.state(sel) + publishFormat(current ? docxFormat(current) : null) + }) return () => { off() + publishedSelection.current = null publishFormat(null) } }, [ctl, editor, isEditing, publishFormat]) diff --git a/src/react/edit/Toolbar.tsx b/src/react/edit/Toolbar.tsx index fbafebe..6220ef4 100644 --- a/src/react/edit/Toolbar.tsx +++ b/src/react/edit/Toolbar.tsx @@ -17,6 +17,7 @@ import { type ReactNode, type RefObject, } from 'react' +import { fontSize } from './format-values' import { cssColor } from '../../core/color' import { useStrings } from '../strings' import { useHostUI, type ButtonProps, type SelectProps } from '../ui' @@ -502,7 +503,8 @@ export function SizeBox(props: { value?: number; placeholder?: number; sizes?: n const set = (n: number) => { setText(null) setOpen(false) - if (Number.isFinite(n) && n >= 1 && n <= 400) props.onChange(Math.round(n * 2) / 2) + const value = fontSize(n) + if (value !== null) props.onChange(value) } const done = () => { if (text !== null) set(parseFloat(text)) diff --git a/src/react/edit/format-values.ts b/src/react/edit/format-values.ts new file mode 100644 index 0000000..2378c47 --- /dev/null +++ b/src/react/edit/format-values.ts @@ -0,0 +1,46 @@ +import type { FormatCommand } from '../controller' + +/** Shared with SizeBox: 1–400 points, rounded to the nearest half point. */ +export function fontSize(pt: number): number | null { + if (!Number.isFinite(pt) || pt < 1 || pt > 400) return null + const value = Math.round(pt * 2) / 2 + // Check the integer units used by both Office text writers before changing history. + return [2, 100].every((scale) => Number.isSafeInteger(Math.round(value * scale)) && Math.round(value * scale) > 0) ? value : null +} + +/** Only opaque hex is part of the write contract. CSS names/functions and transparency are rejected. */ +function color(value: unknown): string | null | undefined { + if (value === null) return null + if (typeof value !== 'string') return undefined + const s = value.trim().toLowerCase() + if (/^#[0-9a-f]{3}$/.test(s)) return '#' + s.slice(1).replace(/./g, '$&$&') + if (/^#[0-9a-f]{6}$/.test(s)) return s + if (/^#[0-9a-f]{6}ff$/.test(s)) return s.slice(0, 7) + return undefined +} + +/** Runtime validation also covers JavaScript and web-component hosts. Never turn an unknown op into clear. */ +export function formatCommand(cmd: FormatCommand): FormatCommand | null { + if (!cmd || typeof cmd !== 'object') return null + switch (cmd.op) { + case 'toggle': return ['bold', 'italic', 'underline', 'strike'].includes(cmd.mark) ? cmd : null + case 'font': { + if (typeof cmd.name !== 'string') return null + const name = cmd.name.trim() + return name && !/[\u0000-\u001f\u007f]/.test(name) ? { ...cmd, name } : null + } + case 'size': { + const pt = fontSize(cmd.pt) + return pt === null ? null : { ...cmd, pt } + } + case 'color': + case 'highlight': { + const c = color(cmd.color) + return c === undefined ? null : { ...cmd, color: c } + } + case 'align': return ['left', 'center', 'right', 'justify'].includes(cmd.align) ? cmd : null + case 'list': return cmd.list === null || cmd.list === 'bullet' || cmd.list === 'number' ? cmd : null + case 'clear': return cmd + default: return null + } +} diff --git a/src/react/edit/format.ts b/src/react/edit/format.ts index 26da818..462c317 100644 --- a/src/react/edit/format.ts +++ b/src/react/edit/format.ts @@ -2,6 +2,7 @@ import type { FmtPatch } from '../../core/xlsx/types' import { MARK_KEY, type FormatCommand, type TextFormat } from '../controller' import type { DocxEditor, FormatState } from '../docx/DocxEditor' import type { PptxEditor, PptxFormat } from '../pptx/PptxEditor' +import { formatCommand } from './format-values' import { fontName } from './Toolbar' // The editors' formatting states as the controller's TextFormat, and its commands as editor calls: one formatting @@ -17,15 +18,17 @@ export function docxFormat(s: FormatState): TextFormat { } export function applyDocx(ed: DocxEditor, c: FormatCommand) { - if (c.op === 'size' && !validSize(c.pt, 2)) return + const command = formatCommand(c) + if (!command) return + c = command if (c.op === 'toggle') ed.toggle(MARK_KEY[c.mark]) else if (c.op === 'font') ed.setFont(c.name) else if (c.op === 'size') ed.setSize(c.pt) else if (c.op === 'color') ed.setColor(c.color) else if (c.op === 'highlight') ed.setHighlight(c.color) else if (c.op === 'align') ed.setPara({ align: c.align }, { align: c.align }) - else if (c.op === 'list') ed.toggleList(c.list) - else ed.clearFormat() + else if (c.op === 'list') ed.setList(c.list) + else if (c.op === 'clear') ed.clearFormat() } export function pptxFormat(s: PptxFormat): TextFormat { @@ -33,15 +36,17 @@ export function pptxFormat(s: PptxFormat): TextFormat { } export function applyPptx(ed: PptxEditor, c: FormatCommand) { - if (c.op === 'size' && !validSize(c.pt, 100)) return + const command = formatCommand(c) + if (!command) return + c = command if (c.op === 'toggle') ed.toggle(MARK_KEY[c.mark]) else if (c.op === 'font') ed.setFont(c.name) else if (c.op === 'size') ed.setSize(c.pt) else if (c.op === 'color') ed.setColor(c.color) else if (c.op === 'highlight') ed.setHighlight(c.color) else if (c.op === 'align') ed.setAlign(c.align) - else if (c.op === 'list') ed.toggleBullet(c.list) - else ed.clearFormat() + else if (c.op === 'list') ed.setList(c.list) + else if (c.op === 'clear') ed.clearFormat() } /** a CSS font size (px number or 'pt' string) in points */ @@ -66,20 +71,15 @@ export function cellFormat(css: Record, base: { fontFam /** a command as a cell format patch; null for what cells do not have (lists, justified text) */ export function cellPatch(c: FormatCommand, now: TextFormat): FmtPatch | null { + const command = formatCommand(c) + if (!command) return null + c = command if (c.op === 'toggle') return { [MARK_KEY[c.mark]]: !now[c.mark] } if (c.op === 'font') return { font: c.name } - if (c.op === 'size') return validSize(c.pt) ? { sz: c.pt } : null + if (c.op === 'size') return { sz: c.pt } if (c.op === 'color') return { color: c.color } if (c.op === 'highlight') return { fill: c.color } if (c.op === 'align') return c.align === 'justify' ? null : { align: c.align } if (c.op === 'clear') return { clear: true } return null } - -const validSize = (pt: number, unitsPerPoint?: number) => { - if (!Number.isFinite(pt) || pt <= 0) return false - if (unitsPerPoint === undefined) return true - // DOCX stores half points and PPTX hundredths: validate the writer's rounded units before editing history. - const units = Math.round(pt * unitsPerPoint) - return Number.isSafeInteger(units) && units > 0 -} diff --git a/src/react/edit/input.ts b/src/react/edit/input.ts index 41d4cf0..e3dded8 100644 --- a/src/react/edit/input.ts +++ b/src/react/edit/input.ts @@ -341,7 +341,9 @@ export class RichInput { lastSel: Sel | null = null /** A live formatting target may move to a native control, but never survive a real selection loss. */ private formatTarget: Sel | null = null - private formatControl: Element | null = null + private attachedRoot: HTMLElement | null = null + private commandSelection: Sel | null = null + formatting = false /** select all: the model selection covers every paragraph, the DOM one only what is rendered */ private override: { model: Sel; dom: Sel } | null = null @@ -350,6 +352,8 @@ export class RichInput { attach(root: HTMLElement) { if (this.root === root) return this.detach() + if (this.attachedRoot !== root) this.clearSelection() + this.attachedRoot = root this.root = root root.addEventListener('beforeinput', this.onBeforeInput) root.addEventListener('compositionstart', this.onCompStart) @@ -369,12 +373,20 @@ export class RichInput { cancelAnimationFrame(this.raf) this.raf = 0 // or the next selection change waits forever for a frame that was cancelled this.root = null + } + + clearSelection() { this.override = null this.formatTarget = null - this.formatControl = null this.lastSel = null } + get focused() { + const root = this.root + const active = (root?.getRootNode() as Document | ShadowRoot | undefined)?.activeElement + return !!root && (active === root || !!active && root.contains(active)) + } + get isComposing() { return !!this.composing } @@ -391,7 +403,7 @@ export class RichInput { /** current selection, falling back to the last known one (e.g. after focusing a toolbar control) */ sel(): Sel | null { - return this.override?.model ?? this.readSel() ?? this.lastSel + return this.commandSelection ?? this.override?.model ?? this.readSel() ?? this.lastSel } /** Native controls have their own selection; keep the editor target while the host edits a value. */ @@ -403,13 +415,19 @@ export class RichInput { return active && !root.contains(active) && /^(INPUT|TEXTAREA|SELECT)$/.test(active.tagName) ? active : null } - /** Controller formatting can restore asynchronously; leave the initiating native control alone. */ - preserveControlFocus() { - this.formatControl = this.activeControl() + /** Use the exact published logical target for one command, without affecting later undo/navigation. */ + withFormatSelection(sel: Sel, apply: () => void) { + this.commandSelection = sel + this.formatting = true + this.lastSel = sel + try { apply() } finally { + this.commandSelection = null + this.formatting = false + } } formatSelection(): Sel | null { - const sel = this.activeControl() ? this.formatTarget : this.readSel() + const sel = this.activeControl() ? (this.formatTarget && this.lastSel) : (this.override?.model ?? this.readSel()) return sel && this.host.para(sel.a.pa) && this.host.para(sel.f.pa) ? sel : null } @@ -436,11 +454,11 @@ export class RichInput { } /** Applies a model selection to the DOM; false when its paragraph isn't rendered. */ - restore(sel: Sel | null, focus = true): boolean { + restore(sel: Sel | null, focus: boolean | 'preserve' = this.formatting ? 'preserve' : true): boolean { const root = this.root if (!root || !sel) return false - // Re-rendering a format change must not replace a host input's focus or its selection. - if (focus && this.formatControl && (this.activeControl() === this.formatControl || !this.formatSelection())) { + const active = (root.getRootNode() as Document | ShadowRoot).activeElement + if (focus === 'preserve' && active !== root && !root.contains(active)) { this.lastSel = sel return true } @@ -451,8 +469,7 @@ export class RichInput { this.lastSel = sel return false } - const active = (root.getRootNode() as Document | ShadowRoot).activeElement - if (focus && active !== root && !root.contains(active)) root.focus({ preventScroll: true }) + if (focus === true && active !== root && !root.contains(active)) root.focus({ preventScroll: true }) const s = getSel(root) try { s?.setBaseAndExtent(a[0], a[1], f[0], f[1]) @@ -609,7 +626,6 @@ export class RichInput { this.raf = 0 const dom = this.readSel() const control = this.activeControl() - if (dom && !control) this.formatControl = null const ov = this.override const active = (this.root?.getRootNode() as Document | ShadowRoot | undefined)?.activeElement // select all stays until the selection moves somewhere else (losing it to a re-render keeps it, like lastSel) diff --git a/src/react/pptx/PptxEditor.ts b/src/react/pptx/PptxEditor.ts index 9847718..c3cf521 100644 --- a/src/react/pptx/PptxEditor.ts +++ b/src/react/pptx/PptxEditor.ts @@ -84,6 +84,7 @@ export class PptxEditor implements RichHost { slide = -1 sid = -1 pendingSel: Sel | null = null + pendingNoRefocus = false private history: Entry[] = [] private future: Entry[] = [] private pend: { s: Partial; d: PRunSet; at: { pa: string; o: number } } | null = null @@ -132,6 +133,7 @@ export class PptxEditor implements RichHost { clearTimeout(this.timer) if (this.sid >= 0 && this.changedSinceCommit) this.commitInBackground() this.input.detach() + this.input.clearSelection() this.sid = -1 this.slide = -1 this.body = undefined @@ -210,6 +212,7 @@ export class PptxEditor implements RichHost { this.future = [] } this.pendingSel = sel + this.pendingNoRefocus = this.input.formatting this.changedSinceCommit = true this.onDirty?.() clearTimeout(this.timer) @@ -233,6 +236,7 @@ export class PptxEditor implements RichHost { private restore(paras: EPara[], sel: Sel) { this.paras = paras this.pendingSel = sel + this.pendingNoRefocus = this.input.formatting this.changedSinceCommit = true this.onDirty?.() clearTimeout(this.timer) @@ -339,14 +343,21 @@ export class PptxEditor implements RichHost { } /** applies a paragraph-level change to the selected paragraphs */ - private paraOp(fn: (p: EPara) => EPara, label: string) { + private paraOp(fn: (p: EPara) => EPara, label: string, list?: 'bullet' | 'number' | 'none') { const sel = this.input.sel() if (!sel) return const [a, b] = ordered(this, sel) const pas = this.span(a.pa, b.pa) + if (list && pas.every((pa) => bulletOf(this.para(pa)) === list)) return this.replace(pas, pas.map((pa) => fn(this.para(pa))), sel, { label }) } + /** Host API setter; the built-in toolbar retains toggleBullet. */ + setList(kind: 'bullet' | 'number' | null) { + const next = kind ?? 'none' + this.paraOp((p) => ({ ...p, pp: { ...p.pp, bullet: next } }), 'bullet', next) + } + toggleBullet(kind: 'bullet' | 'number') { const st = this.state() const next = st?.bullet === kind ? 'none' : kind diff --git a/src/react/pptx/PptxView.tsx b/src/react/pptx/PptxView.tsx index 215249f..6fa5bf1 100644 --- a/src/react/pptx/PptxView.tsx +++ b/src/react/pptx/PptxView.tsx @@ -8,6 +8,7 @@ import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' import { useViewCommands, useControllerObserved } from '../controller' import { applyPptx, pptxFormat } from '../edit/format' +import type { Sel } from '../edit/rich' import { getSel } from '../edit/input' import { PptxEditor } from './PptxEditor' import { PptxToolbar, type AlignTo, type Arrange, type Rotate, type SlideCmd } from './PptxToolbar' @@ -352,7 +353,9 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t const sel = editor.pendingSel if (sel) { editor.pendingSel = null - editor.input.restore(sel) + const noRefocus = editor.pendingNoRefocus + editor.pendingNoRefocus = false + editor.input.restore(sel, noRefocus ? 'preserve' : true) } }) @@ -640,6 +643,7 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t useEffect(() => { ctl?.update({ canUndo: viewer.editable && (undoDepth > 0 || editor.active), canRedo: viewer.editable }) }) + const publishedSelection = useRef(null) const publishFormat = useViewCommands(ctl, { setZoom, goto: (id) => go(Number(id)), @@ -648,19 +652,23 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t redo: () => viewer.editable && (editor.active ? editor.redo() : void undoShapes(true)), present: () => setPresenting(current), format: (c) => { - if (viewer.editable && editor.active && editor.input.formatSelection()) { - editor.input.preserveControlFocus() - applyPptx(editor, c) - } + const sel = publishedSelection.current + if (viewer.editable && editor.active && sel) editor.input.withFormatSelection(sel, () => applyPptx(editor, c)) }, }) // formatting reaches text being edited; a shape that is only selected has none useEffect(() => { if (!ctl) return if (!viewer.editable) return publishFormat(null) - const off = editor.subscribeState((s) => publishFormat(s && editor.input.formatSelection() ? pptxFormat(s) : null)) + const off = editor.subscribeState((s) => { + const sel = s && editor.input.formatSelection() + publishedSelection.current = sel + const current = sel && editor.state(sel) + publishFormat(current ? pptxFormat(current) : null) + }) return () => { off() + publishedSelection.current = null publishFormat(null) } }, [ctl, editor, viewer.editable, publishFormat]) diff --git a/src/react/xlsx/XlsxToolbar.tsx b/src/react/xlsx/XlsxToolbar.tsx index 021a726..ef8acd8 100644 --- a/src/react/xlsx/XlsxToolbar.tsx +++ b/src/react/xlsx/XlsxToolbar.tsx @@ -1,8 +1,9 @@ import { useState } from 'react' +import { cellFormat } from '../edit/format' import type { BorderKind, FmtPatch } from '../../core/xlsx/types' import { MOD } from '../common/ContextMenu' import { EditorBar } from '../common/Slots' -import { Btn, ColorBtn, Dropdown, fontName, fontOptions, Icon, Menu, Pop, Select, Sep, SizeBox, type IconName } from '../edit/Toolbar' +import { Btn, ColorBtn, Dropdown, fontOptions, Icon, Menu, Pop, Select, Sep, SizeBox, type IconName } from '../edit/Toolbar' import { useStrings, type Strings } from '../strings' type FormatName = keyof Strings['xlsx']['formats'] @@ -105,13 +106,12 @@ export function XlsxToolbar(props: { const { css, onFormat: f } = props const [bColor, setBColor] = useState('#000000') const [bStyle, setBStyle] = useState<(typeof BORDER_STYLES)[number]['value']>('thin') - const deco = String(css.textDecoration ?? '') - const align = (css.textAlign as string | undefined) ?? '' + const look = cellFormat(css, props.base) + const align = look.align ?? '' const valign = css.alignItems === 'flex-start' ? 'top' : css.alignItems === 'center' ? 'center' : 'bottom' const rot = Number(css.textRotate ?? 0) - const pt = (v: unknown) => (typeof v === 'string' && v.endsWith('pt') ? parseFloat(v) : typeof v === 'number' ? Math.round(v * 0.75 * 2) / 2 : undefined) - const sz = pt(css.fontSize) ?? pt(props.base.fontSize) - const font = fontName((css.fontFamily ?? props.base.fontFamily) as string | undefined) + const sz = look.size + const font = look.font ?? '' const t = useStrings() const kb = (label: string, keys: string) => t.edit.keyed(label, keys) const known = FORMATS.find((x) => x.value === props.format) @@ -134,13 +134,13 @@ export function XlsxToolbar(props: { f({ sz: v })} /> - props.onToggle('b')} /> - props.onToggle('i')} /> - props.onToggle('u')} /> - props.onToggle('strike')} /> - f({ color: c })} noneLabel={t.edit.automatic} /> + props.onToggle('b')} /> + props.onToggle('i')} /> + props.onToggle('u')} /> + props.onToggle('strike')} /> + f({ color: c })} noneLabel={t.edit.automatic} /> - f({ fill: c })} noneLabel={t.format.noFill} /> + f({ fill: c })} noneLabel={t.format.noFill} /> {(close) => (
diff --git a/src/react/xlsx/XlsxView.tsx b/src/react/xlsx/XlsxView.tsx index 8ef1f24..a82d362 100644 --- a/src/react/xlsx/XlsxView.tsx +++ b/src/react/xlsx/XlsxView.tsx @@ -1228,8 +1228,7 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g focusGrid() } const toggle = (k: 'b' | 'i' | 'u' | 'strike') => { - const on = - k === 'b' ? activeCss.fontWeight === 700 : k === 'i' ? activeCss.fontStyle === 'italic' : String(activeCss.textDecoration ?? '').includes(k === 'u' ? 'underline' : 'line-through') + const on = cellFmt[k === 'b' ? 'bold' : k === 'i' ? 'italic' : k === 'u' ? 'underline' : 'strike'] fmt({ [k]: !on }) } const undo = () => void run(client.call('xlsx.undo'), 'undo') @@ -1242,7 +1241,7 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g redo: () => editable && redo(), format: (c) => { const patch = editable && cellPatch(c, cellFmt) - if (patch) fmt(patch) + if (patch) void run(client.call('xlsx.format', sheet, rect, patch)) }, } const h = store.history diff --git a/test/controller.test.ts b/test/controller.test.ts index d937dfb..26f751b 100644 --- a/test/controller.test.ts +++ b/test/controller.test.ts @@ -143,12 +143,13 @@ describe('viewer controller', () => { expect(ctl.snapshot().format).toBeNull() }) - test('invalid sizes never reach a view command; positive finite sizes keep their value', () => { + test('invalid sizes never reach a view command; valid sizes use the shared half-point range', () => { const ctl = new InternalViewerController() const sizes: number[] = [] mount(ctl).view.attachView({ format: (c) => { if (c.op === 'size') sizes.push(c.pt) } }) - for (const pt of [NaN, Infinity, -Infinity, 0, -1, 0.25, 12.5, 1000]) ctl.format({ op: 'size', pt }) - expect(sizes).toEqual([0.25, 12.5, 1000]) + const { format } = ctl + for (const pt of [NaN, Infinity, -Infinity, 0, -1, 0.25, 0.5, 1, 12.26, 12.5, 400, 400.1, 1000]) format({ op: 'size', pt }) + expect(sizes).toEqual([1, 12.5, 12.5, 400]) }) test('structural mocks and wrappers fail clearly before mounting', () => { diff --git a/test/format-commands.test.ts b/test/format-commands.test.ts index 42df536..aaae8d8 100644 --- a/test/format-commands.test.ts +++ b/test/format-commands.test.ts @@ -7,7 +7,7 @@ import { PptxEditor } from '../src/react/pptx/PptxEditor' import { applyDocx, applyPptx, cellPatch, cellFormat } from '../src/react/edit/format' const file = async (kind: string) => new Blob([await Bun.file(`${import.meta.dir}/../playground/public/samples/sample.${kind}`).arrayBuffer()]) -const invalid = [NaN, Infinity, -Infinity, 0, -1] +const invalid = [NaN, Infinity, -Infinity, 0, -1, 0.25, 0.5, 400.1, 1000] const invalidConverted = [Number.MAX_VALUE, Number.MIN_VALUE, Number.MAX_SAFE_INTEGER] const xml = async (client: DocumentClient, path: string) => (await ZipArchive.open(new BlobSource(await client.call('save')))).text(path) async function documentEditor() { @@ -48,6 +48,10 @@ test('DOCX: invalid public sizes leave model, history and saved XML untouched; f expect(saved).toContain('w:sz w:val="25"') expect(saved).not.toMatch(/NaN|Infinity/) expect(ed.state()?.sz).toBe(12.5) + for (const pt of [1, 400, 12.26]) { + applyDocx(ed, { op: 'size', pt }); await settled(ed) + expect(await xml(client, 'word/document.xml')).toContain(`w:sz w:val="${Math.round(pt * 2)}"`) + } } finally { client.destroy() } }) @@ -68,6 +72,10 @@ test('PPTX: invalid public sizes leave model, history and saved XML untouched; f ed.commit() const saved = await xml(client, 'ppt/slides/slide1.xml') expect(saved).toContain('sz="1250"') + for (const pt of [1, 400, 12.26]) { + applyPptx(ed, { op: 'size', pt }); ed.commit() + expect(await xml(client, 'ppt/slides/slide1.xml')).toContain(`sz="${Math.round(pt * 2) * 50}"`) + } expect(saved).not.toMatch(/NaN|Infinity/) } finally { ed.end(); client.destroy() } }) @@ -85,11 +93,15 @@ test('XLSX: invalid public sizes produce no mutation; fractional size survives s await client.call('xlsx.format', 0, { r0: 1, c0: 1, r1: 1, c1: 1 }, cellPatch({ op: 'size', pt: 12.5 }, now)!) const saved = await xml(client, 'xl/styles.xml') expect(saved).toContain('val="12.5"') + for (const pt of [1, 400, 12.26]) { + await client.call('xlsx.format', 0, { r0: 1, c0: 1, r1: 1, c1: 1 }, cellPatch({ op: 'size', pt }, now)!) + expect(await xml(client, 'xl/styles.xml')).toContain(`val="${Math.round(pt * 2) / 2}"`) + } expect(saved).not.toMatch(/NaN|Infinity/) } finally { client.destroy() } }) -test('DOCX lists toggle collectively across a mixed selection; repetition removes the list', async () => { +test('DOCX list setters cover mixed selection, are idempotent and explicitly remove lists', async () => { const { client, ed } = await documentEditor() try { const first = ed.input.lastSel!.a.pa @@ -103,22 +115,101 @@ test('DOCX lists toggle collectively across a mixed selection; repetition remove expect([ed.para(first)?.lst, ed.para(second)?.lst]).toEqual(['bullet', 'bullet']) applyDocx(ed, { op: 'list', list: 'bullet' }) await settled(ed) + expect([ed.para(first)?.lst, ed.para(second)?.lst]).toEqual(['bullet', 'bullet']) + applyDocx(ed, { op: 'list', list: null }) + await settled(ed) expect([ed.para(first)?.lst, ed.para(second)?.lst]).toEqual([undefined, undefined]) // Read the converted model directly: subscription refresh after conversion depends on inherited #19. expect(ed.state()?.lst).toBeUndefined() } finally { client.destroy() } }) -test('PPTX mixed lists toggle from the first paragraph and repetition removes the list', async () => { +test('PPTX list setters cover mixed selection, are idempotent and explicitly remove lists', async () => { const { client, ed, body, sid } = await presentationEditor() try { ed.begin(0, sid, { ...body, paras: [{ ...body.paras[0], buKind: 'bullet' }, { ...body.paras[0], buKind: 'none' }] }) ed.input.lastSel = { a: { pa: '0', o: 0 }, f: { pa: '1', o: 1 } } applyPptx(ed, { op: 'list', list: 'bullet' }) - expect(ed.paras.map((p) => p.pp?.bullet)).toEqual(['none', 'none']) + expect(ed.paras.map((p) => p.pp?.bullet)).toEqual(['bullet', 'bullet']) applyPptx(ed, { op: 'list', list: 'number' }) expect(ed.paras.map((p) => p.pp?.bullet)).toEqual(['number', 'number']) applyPptx(ed, { op: 'list', list: 'number' }) + expect(ed.paras.map((p) => p.pp?.bullet)).toEqual(['number', 'number']) + applyPptx(ed, { op: 'list', list: null }) + expect(ed.paras.map((p) => p.pp?.bullet)).toEqual(['none', 'none']) + ed.toggleBullet('bullet') + ed.toggleBullet('bullet') expect(ed.paras.map((p) => p.pp?.bullet)).toEqual(['none', 'none']) } finally { ed.end(); client.destroy() } }) + +const invalidCommands = [ + { op: 'bold' }, { op: 'toggle', mark: 'unknown' }, { op: 'align', align: 'unknown' }, { op: 'list', list: 'unknown' }, + { op: 'font', name: '' }, { op: 'font', name: ' ' }, { op: 'font', name: 'Arial\u0000' }, + ...['red', 'rgb(255,0,0)', '#ff000080', '#1234', 'var(--brand)', 'not-a-color'].flatMap((color) => [{ op: 'color', color }, { op: 'highlight', color }]), +] as unknown as import('../src/react/controller').FormatCommand[] + +for (const kind of ['docx', 'pptx'] as const) { + test(`${kind}: invalid JS commands, empty fonts and unsupported CSS colors preserve model, dirty, history and XML`, async () => { + const { client, ed } = kind === 'docx' ? await documentEditor() : await presentationEditor() + const apply = (c: import('../src/react/controller').FormatCommand) => kind === 'docx' ? applyDocx(ed as DocxEditor, c) : applyPptx(ed as PptxEditor, c) + const path = kind === 'docx' ? 'word/document.xml' : 'ppt/slides/slide1.xml' + try { + let dirty = 0 + ed.onDirty = () => dirty++ + const before = await xml(client, path) + const model = JSON.stringify(ed instanceof DocxEditor ? ed.state() : ed.text()) + for (const c of invalidCommands) apply(c) + expect(dirty).toBe(0) + expect(JSON.stringify(ed instanceof DocxEditor ? ed.state() : ed.text())).toBe(model) + if (ed instanceof DocxEditor) expect(ed.canUndo).toBe(false) + else ed.commit() + ed.undo(); ed.redo() + expect(await xml(client, path)).toBe(before) + // Opaque alpha normalizes to writable RGB; shorthand highlight is also expanded. + apply({ op: 'color', color: '#123456ff' }) + apply({ op: 'highlight', color: '#abc' }) + apply({ op: 'font', name: ' Arial ' }) + if (ed instanceof DocxEditor) await settled(ed) + else ed.commit() + const colored = await xml(client, path) + expect(colored).toMatch(/123456/i) + expect(colored).toMatch(/AABBCC/i) + expect(colored).toContain('Arial') + // Rejected colors cannot erase an existing color or add an undo step. + const dirtyBefore = dirty + for (const c of invalidCommands) apply(c) + expect(dirty).toBe(dirtyBefore) + if (ed instanceof PptxEditor) ed.commit() + expect(await xml(client, path)).toBe(colored) + ed.undo() + if (ed instanceof DocxEditor) await settled(ed) + else ed.commit() + expect(await xml(client, path)).toMatch(/123456/i) + } finally { if (ed instanceof PptxEditor) ed.end(); client.destroy() } + }) +} + +test('XLSX: invalid commands cannot reach worker history; opaque colors survive actual saved XML', async () => { + const client = await DocumentClient.open(await file('xlsx'), { worker: false }) + try { + const loaded = new Promise((r) => client.on('xlsx:progress', (p) => p.sheet === 0 && p.done && r())) + await client.call('xlsx.load', 0); await loaded + const range = { r0: 1, c0: 1, r1: 1, c1: 1 } + const now = cellFormat({}, {}) + for (const c of invalidCommands) expect(cellPatch(c, now)).toBeNull() + for (const c of [{ op: 'color', color: '#123456ff' }, { op: 'highlight', color: '#abc' }] as const) { + await client.call('xlsx.format', 0, range, cellPatch(c, now)!) + } + const saved = await xml(client, 'xl/styles.xml') + expect(saved).toMatch(/FF123456/i) + expect(saved).toMatch(/FFAABBCC/i) + for (const c of invalidCommands) { + const patch = cellPatch(c, now) + if (patch) await client.call('xlsx.format', 0, range, patch) + } + expect(await xml(client, 'xl/styles.xml')).toBe(saved) + await client.call('xlsx.undo') + expect(await xml(client, 'xl/styles.xml')).toMatch(/FF123456/i) + } finally { client.destroy() } +}) diff --git a/test/format.test.ts b/test/format.test.ts index 871c844..a857473 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -26,7 +26,7 @@ describe('formatting as TextFormat', () => { const now = cellFormat({ fontWeight: 700 }, {}) expect(cellPatch({ op: 'toggle', mark: 'bold' }, now)).toEqual({ b: false }) expect(cellPatch({ op: 'toggle', mark: 'italic' }, now)).toEqual({ i: true }) - expect(cellPatch({ op: 'highlight', color: '#ff0' }, now)).toEqual({ fill: '#ff0' }) + expect(cellPatch({ op: 'highlight', color: '#ff0' }, now)).toEqual({ fill: '#ffff00' }) expect(cellPatch({ op: 'size', pt: 9 }, now)).toEqual({ sz: 9 }) expect(cellPatch({ op: 'clear' }, now)).toEqual({ clear: true }) expect(cellPatch({ op: 'align', align: 'justify' }, now)).toBeNull() From 9df4ad75c586ba4a98f5bdb92cf89aedc328a282 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 18 Nov 2026 21:03:43 +0100 Subject: [PATCH 29/41] fix: scope controller ownership and complete review follow-ups --- docs/api.md | 8 +- e2e/app/main.tsx | 16 ++- e2e/collab.spec.ts | 36 ++++++- e2e/controller.spec.ts | 157 ++++++++++++++++++++++++++++-- src/collab/hosts.ts | 17 ++++ src/collab/xlsx.ts | 11 ++- src/core/pptx/parser.ts | 4 +- src/react/DocViewer.tsx | 19 ++-- src/react/common/Slots.tsx | 4 +- src/react/controller.ts | 130 ++++++++++++++++++------- src/react/docx/DocxView.tsx | 7 +- src/react/file/FileMenu.tsx | 4 +- src/react/xlsx/XlsxView.tsx | 45 ++++++--- test/collab-xlsx.test.ts | 29 ++++++ test/controller.test.ts | 189 ++++++++++++++++++++---------------- test/core.test.ts | 15 +++ 16 files changed, 522 insertions(+), 169 deletions(-) diff --git a/docs/api.md b/docs/api.md index a270853..f1911a9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -105,7 +105,7 @@ function Viewer({ file }: { file: File }) { <>