From 681892095ad528db7d6851589ba6745d52cc0eb8 Mon Sep 17 00:00:00 2001 From: Markus Date: Tue, 17 Nov 2026 21:57:05 +0100 Subject: [PATCH] fix(docx): refresh formatting after async conversion (#19) --- e2e/docx.spec.ts | 16 +++++ src/react/docx/DocxEditor.ts | 17 +++-- test/docx-state.test.ts | 128 +++++++++++++++++++++++++++++++++++ 3 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 test/docx-state.test.ts diff --git a/e2e/docx.spec.ts b/e2e/docx.spec.ts index 23a0e76..b0b632f 100644 --- a/e2e/docx.spec.ts +++ b/e2e/docx.spec.ts @@ -102,6 +102,22 @@ describe('docx editing', () => { expect(p.marker?.text).toMatch(/^1[.)]$/) }) + test('removing bullets refreshes the toolbar without reselection (#19)', async () => { + const v = await open() + await v.selectText('document') + const bullets = v.btn('Bulleted list') + const active = v.page.locator('button[aria-label^="Bulleted list"][aria-pressed="true"]') + await bullets.click() + await active.waitFor() + await bullets.click() + await active.waitFor({ state: 'hidden' }) + expect(await bullets.getAttribute('aria-pressed')).toBe('false') + const p = (await docxParas((await v.save()).bytes)).find((x) => paraText(x).startsWith('This document'))! + expect(p.lst).toBeUndefined() + expect(p.marker).toBeUndefined() + expect(v.errors).toEqual([]) + }) + test('text and highlight colors', async () => { const v = await open() await v.selectText('document') diff --git a/src/react/docx/DocxEditor.ts b/src/react/docx/DocxEditor.ts index b0ac161..960643e 100644 --- a/src/react/docx/DocxEditor.ts +++ b/src/react/docx/DocxEditor.ts @@ -499,11 +499,17 @@ export class DocxEditor implements RichHost { const sent = new Set(next) const op: EditOp = { anchor, list: specs, remove, want: convert } this.inflight++ + let applied = false this.client .call('docx.edit', op) - .then((res) => this.applyResult(res, sent)) + .then((res) => { applied = this.applyResult(res, sent) }) .catch((e) => console.error('[office-engine] edit failed', e)) - .finally(() => this.inflight--) + .finally(() => { + this.inflight-- + // Conversion can change the look after replace's optimistic notification. Use the selection now, + // after completing the edit, so the toolbar also sees the current history and busy state. + if (applied) this.emitState(this.input.sel()) + }) } get busy() { @@ -662,8 +668,8 @@ export class DocxEditor implements RichHost { } } - private applyResult(res: EditResult, sent: Set) { - if (this.input.isComposing) return + private applyResult(res: EditResult, sent: Set): boolean { + if (this.input.isComposing) return false let touched = false // the caret inside a rebuilt paragraph is put back after the render (same offsets: the text is the same) const sel = this.input.readSel() @@ -700,9 +706,10 @@ export class DocxEditor implements RichHost { touched = true } } - if (!touched) return + if (!touched) return false if (sel && !this.pendingSel && (rebuilt.has(sel.a.pa) || rebuilt.has(sel.f.pa))) this.pendingSel = sel this.changed() + return true } // ---------------------------------------------------------------- history diff --git a/test/docx-state.test.ts b/test/docx-state.test.ts new file mode 100644 index 0000000..4b8d35c --- /dev/null +++ b/test/docx-state.test.ts @@ -0,0 +1,128 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import type { EditOp, EditResult } from '../src/core/docx/types' +import { DocumentClient } from '../src/core/worker/client' +import { DocxEditor, type DocState, type FormatState } from '../src/react/docx/DocxEditor' +import type { Sel } from '../src/react/edit/rich' + +const clients: DocumentClient[] = [] +afterEach(() => { + for (const client of clients.splice(0)) client.destroy() +}) + +async function editor(src: Blob = Bun.file(`${import.meta.dir}/../playground/public/samples/sample.docx`)) { + const client = await DocumentClient.open(src, { worker: false }) + clients.push(client) + const st: DocState = { blocks: [], heights: new WeakMap(), dirty: new Set(), frontier: 0 } + client.on('docx:blocks', (blocks) => st.blocks.push(...blocks)) + await client.call('docx.start') + const ed = new DocxEditor(client, st, () => {}) + const pa = String(st.blocks.findIndex((b) => b.t === 'p' && b.runs.some((r) => r.t === 'text' && r.text.startsWith('This document')))) + const sel: Sel = { a: { pa, o: 0 }, f: { pa, o: 4 } } + ed.input.lastSel = sel + const states: { state: FormatState | null; busy: boolean }[] = [] + ed.onState = (state) => states.push({ state, busy: ed.busy }) + return { client, ed, sel, states } +} + +async function settle(ed: DocxEditor) { + for (let i = 0; ed.busy && i < 1000; i++) await Bun.sleep(1) + expect(ed.busy).toBe(false) +} + +/** Let the engine finish normally, but control when the editor receives each response. */ +function holdEdits(client: DocumentClient) { + const pending: { result: Promise; release: () => void }[] = [] + client.interceptor = (method, args) => { + if (method !== 'docx.edit') return + const result = client.direct('docx.edit', args[0] as EditOp) + let release!: () => void + const gate = new Promise((r) => { release = r }) + pending.push({ result, release }) + return result.then(async (res) => { + await gate + return res + }) + } + return pending +} + +describe('DOCX conversion state notifications (#19)', () => { + for (const kind of ['bullet', 'number'] as const) test(`${kind} removal, undo and redo publish the saved formatting without reselection`, async () => { + const { client, ed, sel, states } = await editor() + ed.toggleList(kind) + await settle(ed) + const added = states.at(-1) + + ed.toggleList(kind) + await settle(ed) + expect(ed.para(sel.a.pa)?.lst).toBeUndefined() + expect(ed.para(sel.a.pa)?.marker).toBeUndefined() + const reopened = await editor(await client.call('save')) + expect(reopened.ed.para(reopened.sel.a.pa)?.lst).toBeUndefined() + expect(reopened.ed.para(reopened.sel.a.pa)?.marker).toBeUndefined() + expect(states.at(-1)).toMatchObject({ state: { lst: undefined }, busy: false }) + expect(added).toMatchObject({ state: { lst: kind, canUndo: true, canRedo: false }, busy: false }) + + ed.undo() + await settle(ed) + expect(states.at(-1)).toMatchObject({ state: { lst: kind, canUndo: true, canRedo: true }, busy: false }) + ed.redo() + await settle(ed) + expect(states.at(-1)).toMatchObject({ state: { lst: undefined, canUndo: true, canRedo: false }, busy: false }) + expect(ed.input.lastSel).toEqual(sel) + expect(ed.pendingSel).toEqual(sel) + }) + + for (const selected of [true, false]) test(`completion uses the ${selected ? 'new selection' : 'cleared selection'}`, async () => { + const { client, ed, states } = await editor() + const pending = holdEdits(client) + ed.toggleList('bullet') + await pending[0].result + // The first render consumed pendingSel; then the selection moved or was cleared. + ed.pendingSel = null + const now: Sel | null = selected ? { a: { pa: '0', o: 0 }, f: { pa: '0', o: 4 } } : null + ed.input.lastSel = now + ed.onSelection(now) + const expected = now ? ed.state(now) : null + const count = states.length + pending[0].release() + await settle(ed) + expect(states).toHaveLength(count + 1) + expect(states.at(-1)).toEqual({ state: expected, busy: false }) + expect(ed.input.lastSel).toEqual(now) + expect(ed.pendingSel).toBeNull() + }) + + test('an obsolete conversion does not republish; the accepted replacement publishes current formatting', async () => { + const { client, ed, sel, states } = await editor() + const pending = holdEdits(client) + ed.setPara({ align: 'center' }) + const old = await pending[0].result + // Alignment has no marker side effects: the whole obsolete result will be ignored. + expect(old.markers).toEqual({}) + ed.setPara({ align: 'right' }) + await pending[1].result + const current = ed.para(sel.a.pa) + const count = states.length + pending[0].release() + // Drain the ignored response without releasing the still-pending replacement. + await Bun.sleep(0) + expect(ed.busy).toBe(true) + expect(states).toHaveLength(count) + expect(ed.para(sel.a.pa)).toBe(current) + pending[1].release() + await settle(ed) + expect(states).toHaveLength(count + 1) + expect(states.at(-1)).toMatchObject({ state: { align: 'right' }, busy: false }) + expect(ed.para(sel.a.pa)?.ps.align).toBe('right') + }) + + test('an edit with no returned conversion or marker changes keeps its synchronous notification', async () => { + const { ed, states } = await editor() + ed.toggle('b') + const count = states.length + await settle(ed) + expect(states).toHaveLength(count) + expect(states.at(-1)?.state?.b).toBe(true) + }) +})