diff --git a/e2e/pptx-save.spec.ts b/e2e/pptx-save.spec.ts new file mode 100644 index 0000000..7c19552 --- /dev/null +++ b/e2e/pptx-save.spec.ts @@ -0,0 +1,229 @@ +import { expect, test } from 'bun:test' +import { fromB64, openFile, useBrowser, viewer, type Viewer } from './harness' +import type { SlideModel } from '../src/core/pptx/types' + +useBrowser() + +declare global { + interface Window { + __pptxSave: { + holdEdit?: boolean + failEdit?: boolean + failSave?: boolean + holdHost?: boolean + failHost?: boolean + release?: () => void + calls: string[] + } + } +} + +/** Gate actual worker calls, without relying on debounce timing or worker speed. */ +async function controlledViewer(mode: 'holdEdit' | 'failEdit' | 'holdHost') { + const v = await viewer({ editable: true, onSave: true }) + await v.page.evaluate((mode) => { + window.__pptxSave = { [mode]: true, calls: [] } + window.__setProps({ + src: 'samples/sample.pptx', + onLoad(client) { + window.__events.push({ type: 'load', kind: client.kind }) + const call = client.call.bind(client) + client.call = (async (method: string, ...args: unknown[]) => { + const state = window.__pptxSave + if (method === 'pptx.setText' || method === 'save') state.calls.push(method) + if (method === 'pptx.setText') { + if (state.failEdit) throw new Error('Slide commit rejected') + if (state.holdEdit) { + state.holdEdit = false + await new Promise((resolve) => { state.release = resolve }) + } + } + if (method === 'save' && state.failSave) throw new Error('Serialization rejected') + return Reflect.apply(call, client, [method, ...args]) + }) as typeof client.call + }, + onSave: async (blob, name) => { + const state = window.__pptxSave + if (state.failHost) throw new Error('Host write rejected') + const bytes = new Uint8Array(await blob.arrayBuffer()) + let binary = '' + for (const byte of bytes) binary += String.fromCharCode(byte) + window.__events.push({ type: 'save', name, b64: btoa(binary) }) + if (state.holdHost) { + state.holdHost = false + await new Promise((resolve) => { state.release = resolve }) + } + }, + }) + }, mode) + await v.ready('pptx') + return v +} + +async function editTitle(v: Viewer) { + await v.page.locator('.de-slide-frame').first().getByText('office-engine', { exact: true }).click() + await v.page.locator('.de-txt-edit').waitFor() + await v.page.keyboard.press('ControlOrMeta+a') +} + +async function savedRuns(b64: string) { + const { engine } = await openFile(fromB64(b64)) + const slide = await engine.call('pptx.slide', [0]) as SlideModel + return slide.els.flatMap((e) => e.t === 'shape' ? e.text?.paras.flatMap((p) => p.runs) ?? [] : []) +} + +test('immediate keyboard save includes pending slide text and formatting', async () => { + const v = await viewer({ src: 'samples/sample.pptx', editable: true, onSave: true }) + await editTitle(v) + await v.page.keyboard.type('Saved before debounce') + await v.page.keyboard.press('ControlOrMeta+a') + await v.page.keyboard.press('ControlOrMeta+b') + await v.page.keyboard.press('ControlOrMeta+s') + const file = await v.waitEvent('save') + const run = (await savedRuns(file.b64)).find((r) => r.text === 'Saved before debounce') + expect(run).toBeDefined() + expect(run?.b).toBe(true) + await v.page.waitForFunction(() => !document.querySelector('.de-save-dirty')) + expect((await v.events('dirty')).at(-1)?.dirty).toBe(false) + // Undo after a successful save must become dirty again, and flush just like typing. + await v.page.keyboard.press('ControlOrMeta+z') + expect((await v.events('dirty')).at(-1)?.dirty).toBe(true) + await v.page.keyboard.press('ControlOrMeta+s') + const undone = await v.waitEvent('save', 2) + expect((await savedRuns(undone.b64)).find((r) => r.text === 'Saved before debounce')?.b).not.toBe(true) + expect(v.errors).toEqual([]) +}) + +test('save awaits an in-flight commit and newer active edits; repeated shortcuts do not overlap', async () => { + const v = await controlledViewer('holdEdit') + await editTitle(v) + await v.page.keyboard.type('First commit') + await v.page.keyboard.press('Escape') + await v.page.waitForFunction(() => !!window.__pptxSave.release) + // Dispatch in the same turn to exercise the guard before React can render Saving…. + await v.page.evaluate(() => { + for (let i = 0; i < 2; i++) document.activeElement!.dispatchEvent(new KeyboardEvent('keydown', { key: 's', ctrlKey: true, bubbles: true, cancelable: true })) + }) + expect(await v.events('save')).toHaveLength(0) + expect(await v.page.evaluate(() => window.__pptxSave.calls)).toEqual(['pptx.setText']) + await editTitle(v) + await v.page.keyboard.type('Newest commit') + await v.page.evaluate(() => window.__pptxSave.release!()) + const file = await v.waitEvent('save') + expect((await savedRuns(file.b64)).some((r) => r.text === 'Newest commit')).toBe(true) + await v.page.waitForFunction(() => !document.querySelector('.de-save-dirty')) + expect(await v.page.evaluate(() => window.__pptxSave.calls)).toEqual(['pptx.setText', 'pptx.setText', 'save']) + expect(v.errors).toEqual([]) +}) + +test('failed slide commits survive ending text editing; failed serialization also stays dirty for retry', async () => { + const v = await controlledViewer('failEdit') + await editTitle(v) + await v.page.keyboard.type('Retained after failure') + await v.page.keyboard.press('Escape') + await v.page.waitForFunction(() => window.__pptxSave.calls.includes('pptx.setText')) + await v.page.keyboard.press('ControlOrMeta+s') + expect((await v.waitEvent('error')).message).toBe('Slide commit rejected') + expect(await v.events('save')).toHaveLength(0) + expect(await v.page.locator('.de-save-dirty').count()).toBe(1) + expect((await v.events('dirty')).at(-1)?.dirty).toBe(true) + + await v.page.evaluate(() => { window.__pptxSave.failEdit = false; window.__pptxSave.failSave = true }) + await v.page.keyboard.press('ControlOrMeta+s') + expect((await v.waitEvent('error', 2)).message).toBe('Serialization rejected') + expect(await v.events('save')).toHaveLength(0) + expect(await v.page.locator('.de-save-dirty').count()).toBe(1) + + await v.page.evaluate(() => { window.__pptxSave.failSave = false }) + await v.page.keyboard.press('ControlOrMeta+s') + const file = await v.waitEvent('save') + expect((await savedRuns(file.b64)).some((r) => r.text === 'Retained after failure')).toBe(true) + await v.page.waitForFunction(() => !document.querySelector('.de-save-dirty')) + expect(v.errors).toHaveLength(3) + expect(v.errors.every((e) => /Slide commit rejected|Serialization rejected/.test(e))).toBe(true) +}) + +test('edits during host save and host write failures remain dirty until the next successful save', async () => { + const v = await controlledViewer('holdHost') + await editTitle(v) + await v.page.keyboard.type('First saved version') + await v.page.keyboard.press('ControlOrMeta+s') + const first = await v.waitEvent('save') + await v.page.waitForFunction(() => !!window.__pptxSave.release) + await v.page.keyboard.press('ControlOrMeta+a') + await v.page.keyboard.type('Edited during save') + await v.page.keyboard.press('ControlOrMeta+s') + expect(await v.events('save')).toHaveLength(1) + await v.page.evaluate(() => window.__pptxSave.release!()) + await v.page.waitForFunction(() => !document.querySelector('button[title="Save a copy (Ctrl+S)"]:disabled')) + expect((await savedRuns(first.b64)).some((r) => r.text === 'First saved version')).toBe(true) + expect(await v.page.locator('.de-save-dirty').count()).toBe(1) + expect((await v.events('dirty')).at(-1)?.dirty).toBe(true) + + await v.page.evaluate(() => { window.__pptxSave.failHost = true }) + await v.page.keyboard.press('ControlOrMeta+s') + expect((await v.waitEvent('error')).message).toBe('Host write rejected') + expect(await v.page.locator('.de-save-dirty').count()).toBe(1) + await v.page.evaluate(() => { window.__pptxSave.failHost = false }) + await v.page.keyboard.press('ControlOrMeta+s') + const latest = await v.waitEvent('save', 2) + expect((await savedRuns(latest.b64)).some((r) => r.text === 'Edited during save')).toBe(true) + await v.page.waitForFunction(() => !document.querySelector('.de-save-dirty')) + expect(v.errors).toHaveLength(1) + expect(v.errors.every((e) => /Host write rejected/.test(e))).toBe(true) +}) + +test('completion of a save from a replaced document cannot clear the new document dirty state', async () => { + const v = await controlledViewer('holdHost') + await editTitle(v) + await v.page.keyboard.type('Old document') + await v.page.keyboard.press('ControlOrMeta+s') + await v.waitEvent('save') + await v.page.waitForFunction(() => !!window.__pptxSave.release) + await v.page.evaluate(() => window.__setProps({ src: 'samples/sample.xlsx' })) + await v.page.locator('.de-grid').waitFor() + await v.typeCell('J10', 'New document edit') + await v.page.evaluate(() => window.__pptxSave.release!()) + expect(await v.page.locator('.de-save-dirty').count()).toBe(1) + expect((await v.events('dirty')).at(-1)?.dirty).toBe(true) + // The replacement can save independently of the previous save session. + expect((await v.save()).name).toBe('sample.xlsx') + expect(v.errors).toEqual([]) +}) + +test('unmounting the slide view during a flush cancels the stale save without an unhandled rejection', async () => { + const v = await controlledViewer('holdEdit') + await editTitle(v) + await v.page.keyboard.type('Closing document') + await v.page.keyboard.press('Escape') + await v.page.waitForFunction(() => !!window.__pptxSave.release) + await v.page.keyboard.press('ControlOrMeta+s') + await v.page.evaluate(() => window.__setProps({ src: null })) + await v.page.locator('.de-slide-inner').first().waitFor({ state: 'detached' }) + const closed = v.page.waitForEvent('console', { predicate: (m) => /slide edit failed.*Document closed/.test(m.text()) }) + await v.page.evaluate(() => window.__pptxSave.release!()) + // The background commit reports the closed client; save itself must not report a stale error. + await closed + expect(await v.events('save')).toHaveLength(0) + expect(await v.events('error')).toHaveLength(0) + expect(v.errors).toHaveLength(1) + expect(v.errors.every((e) => /slide edit failed.*Document closed/.test(e))).toBe(true) +}) + +test('Office, text and printable exports await the same pending slide work', async () => { + for (const format of ['PowerPoint presentation', 'Plain text', 'Web page']) { + const v = await controlledViewer('holdEdit') + await editTitle(v) + await v.page.keyboard.type('Latest exported text') + await v.page.keyboard.press('Escape') + await v.page.waitForFunction(() => !!window.__pptxSave.release) + const exporting = v.downloadAs(format) + await v.page.waitForFunction(() => !!document.querySelector('.de-file:disabled')) + expect(await v.page.evaluate(() => window.__pptxSave.calls)).toEqual(['pptx.setText']) + await v.page.evaluate(() => window.__pptxSave.release!()) + const file = await exporting + const text = format === 'PowerPoint presentation' ? JSON.stringify(await savedRuns(file.bytes.toString('base64'))) : file.text + expect(text).toContain('Latest exported text') + expect(v.errors).toEqual([]) + } +}) diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx index 8d1f37c..8d6253d 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -185,6 +185,15 @@ export function DocViewer(props: DocViewerProps) { // the name is part of what is loaded: Rename only changes what is shown and saved // a preview of the edited source keeps the one shown until it is ready const { client, error, loading, progress } = useDocument(opened ? opened.src : src, { name: loadName, headers, credentials, worker }, !!opened?.live) + // Save ownership follows the document, including a source change before its client is ready. + const saveSession = useMemo(() => ({ live: true, saving: false, revision: 0 }), [client, src, opened]) + useEffect(() => { + saveSession.live = true + setSaving(false) + return () => { + saveSession.live = false + } + }, [saveSession]) const docName = renamed ?? loadName const collab = useCollab(client, props.collab) const srcFormat = client?.info?.imported @@ -309,12 +318,15 @@ export function DocViewer(props: DocViewerProps) { if (client) openedDirty.current = false }, [client]) const setDirty = useCallback( - (d: boolean) => + (d: boolean) => { + if (!saveSession.live) return + if (d) saveSession.revision++ setDirtyState((prev) => { if (prev !== d) onDirtyChange?.(d) return d - }), - [onDirtyChange], + }) + }, + [onDirtyChange, saveSession], ) const baseName = (renamed ?? (client?.name || docName || 'document')).replace(/\.[^.]+$/, '') const fileName = baseName + (client ? EXT[client.kind] : '') @@ -334,22 +346,30 @@ export function DocViewer(props: DocViewerProps) { }, [client, rebuilds, saveFormat, code]) // saving without onSave means downloading const canSave = allowSave && (!!onSave || allowDownload) - const save = useCallback(async () => { - if (!client || saving || !canSave) return + const saveFile = useCallback(async (original = false) => { + if (!client || !saveSession.live || saveSession.saving || !(original ? allowDownload : canSave)) return + saveSession.saving = true setSaving(true) try { - const blob = saveFormat ? new Blob([await sourceText()], { type: `${PLAIN_FILE[saveFormat].mime};charset=utf-8` }) : await client.call('save') - if (onSave) await onSave(blob, saveName) - else download(blob, saveName) - setDirty(false) + await fileOps.current?.flush?.() + if (!saveSession.live) return + const revision = saveSession.revision + const blob = !original && saveFormat ? new Blob([await sourceText()], { type: `${PLAIN_FILE[saveFormat].mime};charset=utf-8` }) : await client.call('save') + if (!saveSession.live) return + if (!original && onSave) await onSave(blob, saveName) + else download(blob, original ? fileName : saveName) + if (saveSession.live && saveSession.revision === revision && (!original || !onSave)) setDirty(false) } catch (e) { + if (!saveSession.live) return onError?.(e as Error) console.error('[office-engine] save failed', e) setToast((e as Error).message) } finally { - setSaving(false) + saveSession.saving = false + if (saveSession.live) setSaving(false) } - }, [client, saving, canSave, onSave, saveName, saveFormat, sourceText, setDirty, onError]) + }, [client, saveSession, canSave, allowDownload, onSave, fileName, saveName, saveFormat, sourceText, setDirty, onError]) + const save = useCallback(() => saveFile(), [saveFile]) // an edit in the document: its source (Markdown / HTML) is built again when shown or saved const setDocDirty = useCallback( (d: boolean) => { @@ -474,12 +494,7 @@ export function DocViewer(props: DocViewerProps) { importFile(file).then(show, (e: Error) => setToast(e.message)) }), save, - downloadOriginal: async () => { - if (!client) return - download(await client.call('save'), fileName) - // without onSave, saving is downloading - if (!onSave) setDirty(false) - }, + downloadOriginal: () => saveFile(true), picture: isPicture ? { label: 'SVG picture', diff --git a/src/react/common/Slots.tsx b/src/react/common/Slots.tsx index 3816d0d..f584cf0 100644 --- a/src/react/common/Slots.tsx +++ b/src/react/common/Slots.tsx @@ -6,6 +6,8 @@ import type { Printable } from '../file/print' /** What the active view offers to the File menu. */ export interface FileOps { + /** Commit and await pending editor work before serializing the document. Rejects on failure. */ + flush?(): Promise /** all pages, for PDF / print and HTML */ printable(): Promise /** text formats: 'txt' / 'md' / 'html' (documents; 'txt' for presentations), 'csv' / 'tsv' (current sheet; a Blob, as a sheet can be large) */ diff --git a/src/react/file/FileMenu.tsx b/src/react/file/FileMenu.tsx index 65631b7..c6248d9 100644 --- a/src/react/file/FileMenu.tsx +++ b/src/react/file/FileMenu.tsx @@ -146,6 +146,7 @@ export function useFileActions(o: FileActionsOptions): FileActions { if (action === 'original') return c.downloadOriginal() if (action === 'picture') return c.picture?.download() if (!ops) throw new Error('The document is still loading — try again in a moment') + await ops.flush?.() if (action.startsWith('text:')) { const f = TEXT_FORMATS[c.kind].find((x) => 'text:' + x.id === action) if (!f) return diff --git a/src/react/pptx/PptxEditor.ts b/src/react/pptx/PptxEditor.ts index aa6f98d..a74f5ab 100644 --- a/src/react/pptx/PptxEditor.ts +++ b/src/react/pptx/PptxEditor.ts @@ -86,6 +86,8 @@ export class PptxEditor implements RichHost { private pend: { s: Partial; d: PRunSet; at: { pa: string; o: number } } | null = null private timer: ReturnType | undefined private changedSinceCommit = false + private commits: { slide: number; sid: number; specs: PParaSpec[] }[] = [] + private committing?: Promise onChange?: () => void onCommitted?: (slide: number, model: SlideModel) => void onDirty?: () => void @@ -111,7 +113,8 @@ export class PptxEditor implements RichHost { } end() { - if (this.sid >= 0 && this.changedSinceCommit) this.commit() + clearTimeout(this.timer) + if (this.sid >= 0 && this.changedSinceCommit) this.commitInBackground() this.input.detach() this.sid = -1 this.slide = -1 @@ -194,7 +197,7 @@ export class PptxEditor implements RichHost { this.changedSinceCommit = true this.onDirty?.() clearTimeout(this.timer) - this.timer = setTimeout(() => this.commit(), 400) + this.timer = setTimeout(() => this.commitInBackground(), 400) this.onChange?.() this.onState?.(this.state(sel)) } @@ -215,29 +218,54 @@ export class PptxEditor implements RichHost { this.paras = paras this.pendingSel = sel this.changedSinceCommit = true + this.onDirty?.() clearTimeout(this.timer) - this.timer = setTimeout(() => this.commit(), 400) + this.timer = setTimeout(() => this.commitInBackground(), 400) this.onChange?.() this.onState?.(this.state(sel)) } - commit() { + private commitInBackground() { + void this.commit().catch((e) => console.error('[office-engine] slide edit failed', e)) + } + + /** Flush the debounce and any edits made while an earlier commit was in flight. */ + async flush() { + do { + await this.commit() + } while (this.changedSinceCommit || this.commits.length) + } + + commit(): Promise { clearTimeout(this.timer) - if (this.sid < 0 || !this.changedSinceCommit) return - this.changedSinceCommit = false - const slide = this.slide - const specs: PParaSpec[] = this.paras.map((p) => ({ - k: p.k, - algn: p.algnSet ? p.algn : undefined, - ...p.pp, - runs: p.runs.map((r) => - r.t === 'fld' ? { text: '', src: r.src as [number, number], fld: true } : { text: r.text ?? '', src: r.src as [number, number] | undefined, set: r.d as PRunSet | undefined }, - ), - })) - this.client - .call('pptx.setText', slide, this.sid, specs) - .then((m) => this.onCommitted?.(slide, m)) - .catch((e) => console.error('[office-engine] slide edit failed', e)) + if (this.sid >= 0 && this.changedSinceCommit) { + this.changedSinceCommit = false + const specs: PParaSpec[] = this.paras.map((p) => ({ + k: p.k, + algn: p.algnSet ? p.algn : undefined, + ...p.pp, + runs: p.runs.map((r) => + r.t === 'fld' ? { text: '', src: r.src as [number, number], fld: true } : { text: r.text ?? '', src: r.src as [number, number] | undefined, set: r.d as PRunSet | undefined }, + ), + })) + this.commits.push({ slide: this.slide, sid: this.sid, specs }) + } + if (!this.committing) { + this.committing = this.drainCommits().finally(() => { + this.committing = undefined + }) + } + return this.committing + } + + private async drainCommits() { + while (this.commits.length) { + const { slide, sid, specs } = this.commits[0] + const model = await this.client.call('pptx.setText', slide, sid, specs) + // Retain a failed snapshot for retry, including after the active shape changes. + this.commits.shift() + this.onCommitted?.(slide, model) + } } // ---------------------------------------------------------------- formatting diff --git a/src/react/pptx/PptxView.tsx b/src/react/pptx/PptxView.tsx index 63a4d90..9c08447 100644 --- a/src/react/pptx/PptxView.tsx +++ b/src/react/pptx/PptxView.tsx @@ -170,7 +170,9 @@ const THUMB_W = 188 export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = true }: PptxViewProps) { const viewer = useViewer() const meta = client.info.pptx as PresentationMeta + const editor = useMemo(() => new PptxEditor(client), [client]) useFileOps({ + flush: () => editor.flush(), printable: async () => { const m = client.info.pptx as PresentationMeta // hidden flags are known once a slide is parsed: filter on the models @@ -207,7 +209,6 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t const [zoom, setZoom] = useState(initialZoom) const showThumbs = thumbnails && rootSize.w >= 720 && meta.count > 1 const [, bump] = useForceUpdate() - const editor = useMemo(() => new PptxEditor(client), [client]) const caretAt = useRef<{ x: number; y: number } | null>(null) const textRoot = useRef(null) const slidesRef = useRef(null) @@ -269,7 +270,7 @@ export function PptxView({ client, onStatus, initialZoom = 'fit', thumbnails = t if (!viewer.editable) stopEditing() return () => editor.end() // eslint-disable-next-line react-hooks/exhaustive-deps - }, [viewer.editable]) + }, [editor, viewer.editable]) // keyboard first: slide navigation and shortcuts work without a click (a focused host page control keeps the focus) useEffect(() => void claimFocus(scrollRef.current), []) // eslint-disable-line react-hooks/exhaustive-deps