diff --git a/e2e/docx-table.spec.ts b/e2e/docx-table.spec.ts index 7e369aa..775e046 100644 --- a/e2e/docx-table.spec.ts +++ b/e2e/docx-table.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from 'bun:test' -import type { Table } from '../src/core/docx/types' +import type { Paragraph, Table } from '../src/core/docx/types' import { gridOf } from '../src/react/docx/tables' -import { docxBlocks, useBrowser, viewer, type Viewer } from './harness' +import { docxBlocks, paraText, useBrowser, viewer, type Viewer } from './harness' useBrowser() @@ -113,4 +113,41 @@ describe('docx table formatting', () => { expect(after.reduce((a, b) => a + b, 0)).toBeCloseTo(before.reduce((a, b) => a + b, 0), 0) expect(v.errors).toEqual([]) }) + + test('a list in a table inserted this session is shown and can be taken away again (#27)', async () => { + const v = await open() + await v.selectText('Quarterly Report', 'end') + await v.btn('Insert table').click() + // 2 × 2: 8 cells per picker row + await v.page.locator('.de-gridpick button').nth(8 + 1).click() + await v.page.waitForTimeout(300) + await v.page.keyboard.insertText('Item') + await v.page.waitForTimeout(200) + const bullets = v.btn('Bulleted list') + const pressed = v.page.locator('button[aria-label^="Bulleted list"][aria-pressed="true"]') + const marker = v.page.locator('.de-pages td', { hasText: 'Item' }).locator('.de-marker') + const itemPara = async () => { + const t = (await docxBlocks((await v.save()).bytes)).find((b): b is Table => b.t === 'tbl' && b.rows[0].cells[0].blocks.some((p) => p.t === 'p' && paraText(p) === 'Item'))! + return t.rows[0].cells[0].blocks[0] as Paragraph + } + + await bullets.click() + await pressed.waitFor() + await marker.waitFor() + expect((await marker.textContent())?.trim()).toBe('•') + let p = await itemPara() + expect(p.lst).toBe('bullet') + expect(p.marker?.text).toBe('•') + + // saving moved the focus to the Save button: caret back in the cell, then the same button takes the list away + await v.selectText('Item', 'end') + await pressed.waitFor() + await bullets.click() + await pressed.waitFor({ state: 'hidden' }) + await marker.waitFor({ state: 'detached' }) + p = await itemPara() + expect(p.lst).toBeUndefined() + expect(p.marker).toBeUndefined() + expect(v.errors).toEqual([]) + }) }) diff --git a/src/core/docx/parser.ts b/src/core/docx/parser.ts index 1126e86..1ff7671 100644 --- a/src/core/docx/parser.ts +++ b/src/core/docx/parser.ts @@ -779,6 +779,8 @@ export interface DocxStreamCallbacks { export interface PInfo extends ParaRecord { item: number ord: number + /** a paragraph of a table the editor regenerates: the XML it was last converted from (not converted again while the same) */ + xml?: string } /** Splits document.xml into prefix / body items / suffix while streaming, keeping exact source text. */ @@ -875,6 +877,12 @@ export class DocxDocument { genXml = new Map() /** whole body items replaced by the editor (regenerated tables; '' = deleted) */ itemXml = new Map() + /** + * The paragraphs of the tables the editor regenerates, in document order (list numbering counts them there): a table + * of the file by its body item (none once deleted), a new one by its id (placed in a paragraph group). + */ + itemTables = new Map() + newTables = new Map() /** styles the editor changed → their definition in the file as opened (parsed, and as source) */ styleOrig = new Map() /** page setup of the final section as opened, and the changes made to it (written to every section on save) */ @@ -1114,32 +1122,37 @@ export class DocxDocument { recomputeMarkers(): Map { const changed = new Map() this.numbering.reset() + const visit = (pid: number) => { + const inf = this.info.get(pid) + if (!inf) return + let next: ListMarker | undefined + let lst: 'bullet' | 'number' | undefined + if (inf.num) { + const base = inf.marker?.s ?? {} + const m = markerOf(this.numbering, inf.num, base) + if (m) { + next = { ...m.marker, s: inf.marker?.s ?? m.marker.s } + lst = m.lst + } + } + if ((next?.text ?? null) !== (inf.marker?.text ?? null) || lst !== inf.lst) { + inf.marker = next + inf.lst = lst + changed.set(pid, inf) + } + } const items = [...this.itemParas.keys()].sort((a, b) => a - b) for (const item of items) { + const regenerated = this.itemTables.get(item) + if (regenerated) { + regenerated.forEach(visit) + continue + } const arr = this.itemParas.get(item)! for (let ord = 0; ord < arr.length; ord++) { const pid0 = arr[ord] if (pid0 === undefined) continue - const pids = this.groups.get(`${item}:${ord}`) ?? [pid0] - for (const pid of pids) { - const inf = this.info.get(pid) - if (!inf) continue - let next: ListMarker | undefined - let lst: 'bullet' | 'number' | undefined - if (inf.num) { - const base = inf.marker?.s ?? {} - const m = markerOf(this.numbering, inf.num, base) - if (m) { - next = { ...m.marker, s: inf.marker?.s ?? m.marker.s } - lst = m.lst - } - } - if ((next?.text ?? null) !== (inf.marker?.text ?? null) || lst !== inf.lst) { - inf.marker = next - inf.lst = lst - changed.set(pid, inf) - } - } + for (const pid of this.groups.get(`${item}:${ord}`) ?? [pid0]) (this.newTables.get(pid) ?? [pid]).forEach(visit) } } return changed diff --git a/src/core/docx/types.ts b/src/core/docx/types.ts index 4abf61f..0ffec45 100644 --- a/src/core/docx/types.ts +++ b/src/core/docx/types.ts @@ -222,6 +222,8 @@ export interface TableOp { anchor?: number /** null deletes the table */ spec: TableSpec | null + /** paragraphs of the table whose re-converted blocks to return (after style / list changes), as `EditOp.want` */ + want?: number[] } export interface EditOp { diff --git a/src/core/docx/writer.ts b/src/core/docx/writer.ts index f3df9cd..06b6de2 100644 --- a/src/core/docx/writer.ts +++ b/src/core/docx/writer.ts @@ -791,8 +791,12 @@ export async function applyEdit(doc: DocxDocument, op: EditOp): Promise doc.info.get(x.pid)?.num) - const changed = listy2 ? doc.recomputeMarkers() : new Map() + return editResult(doc, blocks, listy || op.list.some((x) => doc.info.get(x.pid)?.num)) +} + +/** The answer to an edit: the blocks converted, and the list markers it changed anywhere (`listy`: it may have). */ +function editResult(doc: DocxDocument, blocks: Record, listy: boolean): EditResult { + const changed = listy ? doc.recomputeMarkers() : new Map() const markers: EditResult['markers'] = {} for (const [pid, inf] of changed) markers[pid] = inf.marker ? { ...inf.marker, lst: inf.lst } : null // returned blocks carry the final markers @@ -897,8 +901,11 @@ function rawCells(tr: RNode): RNode[] { return out } -/** Regenerates a whole table from the editor model, reusing original row/cell properties. */ -export async function genTable(doc: DocxDocument, spec: TableSpec): Promise { +/** + * Regenerates a whole table from the editor model, reusing original row/cell properties. `paras` receives the XML each + * paragraph of the cells is written as, in document order. + */ +export async function genTable(doc: DocxDocument, spec: TableSpec, paras: { spec: ParaSpec; xml: string; map: GenRun[] }[] = []): Promise { let orig: RNode | undefined if (spec.item !== undefined) { const nodes = parseRaw(doc.items[spec.item] ?? '') @@ -965,12 +972,13 @@ export async function genTable(doc: DocxDocument, spec: TableSpec): Promise${tcPrFor(cell.src, g, span, cell.rowSpan > 1 ? 'restart' : undefined, cell.shd, cell)}${paras || `<${W}p/>`}` + out += `<${W}tc>${tcPrFor(cell.src, g, span, cell.rowSpan > 1 ? 'restart' : undefined, cell.shd, cell)}${content || `<${W}p/>`}` if (cell.rowSpan > 1) cont[g] = { left: cell.rowSpan - 1, span, src: cell.src, cell } g += span } @@ -979,29 +987,54 @@ export async function genTable(doc: DocxDocument, spec: TableSpec): Promise` } -export async function applyTable(doc: DocxDocument, op: TableOp): Promise { +/** + * Writes a table regenerated by the editor (`spec` null: deletes it). Its paragraphs are converted as `applyEdit` does + * and numbered with the document's lists: the answer is the same as an edit's (`op.want`: the blocks to return). + */ +export async function applyTable(doc: DocxDocument, op: TableOp): Promise { if (!doc.ready) throw new Error('Document is still loading') doc.markEdited() - const xml = op.spec ? await genTable(doc, op.spec) : '' + const paras: { spec: ParaSpec; xml: string; map: GenRun[] }[] = [] + const xml = op.spec ? await genTable(doc, op.spec, paras) : '' + const pids = paras.map((p) => p.spec.pid) + // the paragraphs it held: a list among them numbered the lists after it + const was = (op.item !== undefined ? (doc.itemTables.get(op.item) ?? doc.itemParas.get(op.item)) : doc.newTables.get(op.tid)) ?? [] + const listy = paras.some((p) => p.spec.pd) || was.some((pid) => doc.info.get(pid)?.num) if (op.item !== undefined) { doc.itemXml.set(op.item, xml) - return - } - // new table living inside a paragraph group - let key: string | undefined - for (const [k, g] of doc.groups) if (g.includes(op.tid)) key = k - if (!op.spec) { - if (key) doc.groups.get(key)!.splice(doc.groups.get(key)!.indexOf(op.tid), 1) - doc.genXml.delete(op.tid) - return + doc.itemTables.set(op.item, pids) + } else { + // new table living inside a paragraph group + let key: string | undefined + for (const [k, g] of doc.groups) if (g.includes(op.tid)) key = k + if (!op.spec) { + if (key) doc.groups.get(key)!.splice(doc.groups.get(key)!.indexOf(op.tid), 1) + doc.genXml.delete(op.tid) + doc.newTables.delete(op.tid) + } else { + if (!key) { + const anchor = op.anchor !== undefined ? doc.info.get(op.anchor) : undefined + if (!anchor || op.anchor === undefined) throw new Error('Table anchor paragraph not found') + const g = groupFor(doc, `${anchor.item}:${anchor.ord}`) + g.splice(g.indexOf(op.anchor) + 1, 0, op.tid) + } + doc.genXml.set(op.tid, xml) + doc.newTables.set(op.tid, pids) + } } - if (!key) { - const anchor = op.anchor !== undefined ? doc.info.get(op.anchor) : undefined - if (!anchor || op.anchor === undefined) throw new Error('Table anchor paragraph not found') - const g = groupFor(doc, `${anchor.item}:${anchor.ord}`) - g.splice(g.indexOf(op.anchor) + 1, 0, op.tid) + const want = new Set(op.want) + const blocks: Record = {} + for (const { spec, xml, map } of paras) { + const prev = doc.info.get(spec.pid) + const tpl = doc.info.get(spec.from) ?? prev + if (!tpl || (prev?.xml === xml && !want.has(spec.pid))) continue + const { blocks: bl, rec } = doc.reconvert(spec.pid, xml, map, tpl.layer, prev?.marker) + // (never an edit's anchor: the place kept is only there to have one) + const { item, ord } = prev ?? tpl + doc.info.set(spec.pid, { ...rec, item, ord, marker: prev?.marker, lst: prev?.lst, xml }) + if (want.has(spec.pid)) blocks[spec.pid] = bl } - doc.genXml.set(op.tid, xml) + return editResult(doc, blocks, listy || pids.some((pid) => doc.info.get(pid)?.num)) } // ---------------------------------------------------------------- page setup diff --git a/src/core/worker/protocol.ts b/src/core/worker/protocol.ts index f2ba4c9..e4f4688 100644 --- a/src/core/worker/protocol.ts +++ b/src/core/worker/protocol.ts @@ -59,7 +59,7 @@ export interface Methods { 'plain.source'(): string | null 'docx.start'(): void 'docx.edit'(op: EditOp): EditResult - 'docx.table'(op: TableOp): void + 'docx.table'(op: TableOp): EditResult 'docx.image'(bytes: ArrayBuffer, ext: string): { rid: string; path: string } 'docx.link'(url: string): string /** id of a built-in paragraph style, created in styles.xml when missing */ diff --git a/src/react/docx/DocxEditor.ts b/src/react/docx/DocxEditor.ts index d292804..3af5b0c 100644 --- a/src/react/docx/DocxEditor.ts +++ b/src/react/docx/DocxEditor.ts @@ -4,7 +4,8 @@ */ import { paraSpec, tableSpec } from '../../core/docx/spec' import type { - Block, CanonStyle, EditOp, EditResult, HeaderFooters, HFSet, HFSetResult, Inline, PageSet, PageSetResult, PageSetup, Paragraph, ParaDirty, ParaStyle, RunSet, RunStyle, StyleInfo, StyleLook, Table, + Block, CanonStyle, EditOp, EditResult, HeaderFooters, HFSet, HFSetResult, Inline, PageSet, PageSetResult, PageSetup, Paragraph, ParaDirty, ParaSpec, ParaStyle, RunSet, RunStyle, StyleInfo, StyleLook, Table, + TableOp, } from '../../core/docx/types' import { cssFont } from '../../core/fonts' import type { DocumentClient } from '../../core/worker/client' @@ -220,6 +221,15 @@ export class DocxEditor implements RichHost { private inflight = 0 /** paragraphs whose look on screen may be behind their style / list: a conversion was asked, none was applied yet */ private stale = new Set() + /** + * Counts the writes sent to the worker; paragraph id → the last write that carried the paragraph. An answer is about + * the paragraphs as its write had them: one written again since is the later answer's (whatever else replaced the + * paragraph object meanwhile: a marker, another conversion, the same object brought back by undo). + */ + private writes = 0 + private writtenIn = new Map() + /** answers that came during an IME composition, applied when it ends */ + private held: { res: EditResult; seq: number }[] = [] onState?: (s: FormatState | null) => void /** image selection changed (overlay with resize handles) */ onImage?: (img: FormatState['img'] | null) => void @@ -467,7 +477,7 @@ export class DocxEditor implements RichHost { if (c.at < this.st.frontier) this.st.frontier++ } if (c.cell && (this.st.blocks[c.cell[0]] as Table).tid !== undefined) this.commitTable(c.cell[0]) - else this.send('docx.edit', { anchor: p.pid, list: [paraSpec(this.partsOf(list, p.pid, c.at))] } as EditOp) + else this.sendParas(p.pid, [paraSpec(this.partsOf(list, p.pid, c.at))]) this.onDirty?.() this.changed() } @@ -483,8 +493,9 @@ export class DocxEditor implements RichHost { private commit(pa: string, before: Paragraph[], next: Paragraph[], want?: boolean) { const c = this.container(pa)! + const structural = want || next.some((p) => p.pd !== before.find((b) => b.pid === p.pid)?.pd) if (c.cell && (this.st.blocks[c.cell[0]] as Table).tid !== undefined) { - this.commitTable(c.cell[0]) + this.commitTable(c.cell[0], structural ? [...before, ...next].map((p) => p.pid!) : []) return } const list = c.list @@ -509,30 +520,51 @@ export class DocxEditor implements RichHost { const lost = [...had].filter((id) => !kept.has(id)) if (lost.length) this.remark(new Set(lost), new Set([...pids, ...remove, ...before.map((b) => b.pid!)])) } - const structural = want || next.some((p) => p.pd !== before.find((b) => b.pid === p.pid)?.pd) - // also while an earlier conversion is still due: its answer comes back after this edit and can't be applied (see applyResult) - const convert = structural || specs.some((x) => this.stale.has(x.pid)) - if (convert) for (const x of specs) this.stale.add(x.pid) - const sent = new Set(next) - const op: EditOp = { anchor, list: specs, remove, want: convert } + this.sendParas(anchor, specs, remove, structural) + } + + /** writes paragraphs (`remove`: taken out); `want`: their style or list changed, their conversion is needed */ + private sendParas(anchor: number, list: ParaSpec[], remove: number[] = [], want = false) { + // also while an earlier conversion is still due: its answer comes back after this write and can't be applied (see applyResult) + const convert = want || list.some((x) => this.stale.has(x.pid)) + const pids = list.map((x) => x.pid) + this.send('docx.edit', { anchor, list, remove, want: convert }, [...pids, ...remove], convert ? pids : []) + } + + /** + * Sends a write to the worker: `pids` the paragraphs it carries, `convert` those whose conversion it asks for (they + * are `stale` until one is applied). The answer is applied to the paragraphs no later write carried (applyResult). + */ + private send(method: 'docx.edit' | 'docx.table', op: EditOp | TableOp, pids: number[], convert: number[]) { + const seq = ++this.writes + for (const pid of pids) this.writtenIn.set(pid, seq) + for (const pid of convert) this.stale.add(pid) this.inflight++ - let applied = false - this.client - .call('docx.edit', op) - .then((res) => { applied = this.applyResult(res, sent) }) - .catch((e) => console.error('[office-engine] edit failed', e)) - .finally(() => { - this.inflight-- + ;(this.client.call as (m: string, op: EditOp | TableOp) => Promise)(method, op) + .finally(() => this.inflight--) + .then((res) => { // 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()) + // after completing the edit, so the toolbar also sees the current history and busy state. The last answer + // in is told even when it changed nothing (an obsolete one): what is published then is the model as it + // stands, no longer busy, never the look of an obsolete answer. + if (this.applyResult(res, seq) || this.settled) this.emitState(this.input.sel()) }) + // (a listener that throws included: reported here, not left as an unhandled rejection) + .catch((e) => console.error('[office-engine] edit failed', e)) } get busy() { return this.inflight > 0 } + /** + * Every write answered and taken in. An answer held for an IME composition is not: the state is published when the + * composition ends and the answer is applied (composed), not before, with the look it is about to replace. + */ + private get settled() { + return !this.inflight && !this.held.length + } + /** * Paragraphs still written as they were read (with the comment marks of the file) that hold text of threads `ids` * are written from the model from now on: each marks its own part of the range, which saving joins into one. @@ -548,7 +580,7 @@ export class DocxEditor implements RichHost { const parts = this.partsOf(list, b.pid, i) for (const p of parts) p.edited = true if (bi !== undefined && (this.st.blocks[bi] as Table).tid !== undefined) tables.add(bi) - else this.send('docx.edit', { anchor: b.pid, list: [paraSpec(parts)] } as EditOp) + else this.sendParas(b.pid, [paraSpec(parts)]) }) } visit(this.st.blocks, undefined) @@ -685,8 +717,15 @@ export class DocxEditor implements RichHost { } } - private applyResult(res: EditResult, sent: Set): boolean { - if (this.input.isComposing) return false + /** applies the answer to write `seq`; true when something changed */ + private applyResult(res: EditResult, seq: number): boolean { + // never rebuild paragraphs under an IME composition: the answer waits for its end (composed) + if (this.input.isComposing) { + this.held.push({ res, seq }) + return false + } + // written again since: the paragraph stays `stale`, so that write asked for the conversion too and its answer is the one applied + const again = (pid: number) => (this.writtenIn.get(pid) ?? 0) > seq 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() @@ -694,17 +733,13 @@ export class DocxEditor implements RichHost { // re-converted paragraphs (style / list changes): only if not edited again meanwhile for (const [k, blocks] of Object.entries(res.blocks)) { const pid = Number(k) + if (again(pid)) continue + this.stale.delete(pid) const locs = this.locate(pid) - const cur = locs.map((l) => l.list[l.index] as Paragraph) const paras = blocks.filter((b): b is Paragraph => b.t === 'p') - // edited again: the paragraph stays `stale`, so that edit asked for the conversion too and its answer is the one applied - let again = false - for (const x of sent) again ||= x.pid === pid && cur.length > 0 && !cur.includes(x) - if (again) continue - this.stale.delete(pid) - if (!locs.length || paras.length !== locs.length || !cur.every((x) => sent.has(x))) continue + if (!locs.length || paras.length !== locs.length) continue locs.forEach((l, i) => { - const was = cur[i] + const was = l.list[l.index] as Paragraph const p = { ...paras[i], from: was.from, orig: was.orig, pd: was.pd, edited: was.edited, keepSect: was.keepSect, ver: was.ver, pb: was.pb } this.put(l.pa, p) // converted with the styles as they are by now @@ -714,12 +749,17 @@ export class DocxEditor implements RichHost { }) touched = true } - // list numbering changes anywhere in the document + // list numbering changes anywhere in the document. A paragraph converted above but written again since gets its + // marker with that later write's conversion (the marker it has then may be this one, so it is not in that answer's). for (const [k, m] of Object.entries(res.markers)) { - for (const loc of this.locate(Number(k))) { + const pid = Number(k) + if (pid in res.blocks && again(pid)) continue + for (const loc of this.locate(pid)) { const p = loc.list[loc.index] as Paragraph if ((loc.list[loc.index - 1] as Paragraph | undefined)?.pid === p.pid) continue - this.put(loc.pa, { ...p, marker: m ? { text: m.text, s: m.s, tab: m.tab } : undefined, lst: m?.lst }) + const q = { ...p, marker: m ? { text: m.text, s: m.s, tab: m.tab } : undefined, lst: m?.lst } + this.put(loc.pa, q) + this.heir.set(p, q) touched = true } } @@ -729,6 +769,13 @@ export class DocxEditor implements RichHost { return true } + /** an IME composition ended (its text is in): the answers that came meanwhile are applied, the toolbar told */ + composed() { + let applied = false + for (const { res, seq } of this.held.splice(0)) applied = this.applyResult(res, seq) || applied + if (applied || this.settled) this.emitState(this.input.sel()) + } + // ---------------------------------------------------------------- history /** current address of the first block of `list` (paragraphs by pid, tables by identity), `empty` for an empty list; undefined when gone */ @@ -1018,18 +1065,14 @@ export class DocxEditor implements RichHost { return undefined } - private commitTable(bi: number) { + /** writes the table at `bi` whole; `want`: paragraphs of it whose style or list changed (as sendParas) */ + private commitTable(bi: number, want: number[] = []) { const t = this.st.blocks[bi] as Table if (t?.t !== 'tbl' || t.tid === undefined) return - this.send('docx.table', { tid: t.tid, item: t.item, anchor: t.item === undefined ? this.prevParaPid(bi) : undefined, spec: tableSpec(t) }) - } - - private send(method: 'docx.table' | 'docx.edit', op: unknown) { - this.inflight++ - ;(this.client.call as (m: string, ...a: unknown[]) => Promise)(method, op) - .then((res) => method === 'docx.edit' && this.applyResult(res as EditResult, new Set())) - .catch((e) => console.error('[office-engine] edit failed', e)) - .finally(() => this.inflight--) + const spec = tableSpec(t) + const pids = spec.rows.flatMap((r) => r.cells.flatMap((c) => c.paras.map((p) => p.pid))) + const convert = pids.filter((pid) => want.includes(pid) || this.stale.has(pid)) + this.send('docx.table', { tid: t.tid, item: t.item, anchor: t.item === undefined ? this.prevParaPid(bi) : undefined, spec, want: convert }, pids, convert) } /** Replaces top-level blocks (table insert/delete/restructure) with history + write-back. */ @@ -1053,9 +1096,9 @@ export class DocxEditor implements RichHost { const changed = next.some((b) => b.t === 'p' && b.pid !== undefined && beforeObj.has(key(b)) && beforeObj.get(key(b)) !== b) if (anchorP && (added.length || removed.length || changed)) { const list = next.filter((b): b is Paragraph => b.t === 'p' && b.pid !== undefined) - this.send('docx.edit', { anchor: anchorP.pid, list: list.map((p) => paraSpec([p])), remove: removed.map((p) => p.pid) } as EditOp) + this.sendParas(anchorP.pid!, list.map((p) => paraSpec([p])), removed.map((p) => p.pid!)) } - for (const b of before) if (b.t === 'tbl' && !nextKeys.has(key(b)) && (b.tid !== undefined || b.item !== undefined)) this.send('docx.table', { tid: b.tid ?? -1, item: b.item, spec: null }) + for (const b of before) if (b.t === 'tbl' && !nextKeys.has(key(b)) && (b.tid !== undefined || b.item !== undefined)) this.send('docx.table', { tid: b.tid ?? -1, item: b.item, spec: null }, [], []) next.forEach((b, i) => { if (b.t !== 'tbl') return // an original table coming back (undo of its deletion) is regenerated from the model like a new one diff --git a/src/react/edit/input.ts b/src/react/edit/input.ts index e96e69a..2fdc0bb 100644 --- a/src/react/edit/input.ts +++ b/src/react/edit/input.ts @@ -56,6 +56,8 @@ export interface RichHost

{ all?(): Sel | null /** deletes a range that spans other blocks (tables): applies the change and returns the caret, or null when unsupported */ deleteAcross?(s: Pos, e: Pos): Pos | null + /** an IME composition ended and its text was put in: what waited for the end of it can be applied */ + composed?(): void } const NAV = new Set(['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown']) @@ -598,6 +600,7 @@ export class RichInput { if (e.data) opInsert(this.host, sel, e.data, { remount: true }) else opInsert(this.host, sel, '', { remount: true }) setTimeout(() => (this.justComposed = ''), 0) + this.host.composed?.() } private onKeyDown = (e: KeyboardEvent) => { diff --git a/test/docx-state.test.ts b/test/docx-state.test.ts index 4b8d35c..0b4f74b 100644 --- a/test/docx-state.test.ts +++ b/test/docx-state.test.ts @@ -1,8 +1,8 @@ -import { afterEach, describe, expect, test } from 'bun:test' -import type { EditOp, EditResult } from '../src/core/docx/types' +import { afterEach, describe, expect, spyOn, test } from 'bun:test' +import type { Block, EditOp, EditResult, Paragraph, Table } 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' +import { runsText, type RRun, type Sel } from '../src/react/edit/rich' const clients: DocumentClient[] = [] afterEach(() => { @@ -21,7 +21,7 @@ async function editor(src: Blob = Bun.file(`${import.meta.dir}/../playground/pub 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 } + return { client, ed, sel, st, states } } async function settle(ed: DocxEditor) { @@ -29,12 +29,12 @@ async function settle(ed: DocxEditor) { expect(ed.busy).toBe(false) } -/** Let the engine finish normally, but control when the editor receives each response. */ +/** Let the engine finish normally, but control when the editor receives each response (paragraph and table writes). */ 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) + if (method !== 'docx.edit' && method !== 'docx.table') return + const result = (client.direct as (m: string, op: unknown) => Promise)(method, args[0] as EditOp) let release!: () => void const gate = new Promise((r) => { release = r }) pending.push({ result, release }) @@ -117,12 +117,333 @@ describe('DOCX conversion state notifications (#19)', () => { 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 () => { + test('an edit with no returned conversion or marker changes keeps its synchronous notification; its answer only ends busy (#29)', async () => { const { ed, states } = await editor() ed.toggle('b') const count = states.length + expect(states.at(-1)).toMatchObject({ state: { b: true }, busy: true }) await settle(ed) + // the same formatting, told once more so that the toolbar does not stay busy + expect(states).toHaveLength(count + 1) + expect(states.at(-1)).toEqual({ state: states.at(-2)!.state, busy: false }) + }) +}) + +/** a caret (or a range up to `f`) in paragraph `pa` */ +const at = (pa: string, o = 0, f = o): Sel => ({ a: { pa, o }, f: { pa, o: f } }) + +/** address of the top-level paragraph starting with `text` */ +const paraAt = (st: DocState, text: string) => String(st.blocks.findIndex((b) => b.t === 'p' && runsText(b.runs as RRun[]).startsWith(text))) + +/** delivers held response `i` and lets the editor take it in */ +async function deliver(pending: ReturnType, i: number) { + await pending[i].result + pending[i].release() + await Bun.sleep(1) +} + +/** the editor's input on a stand-in for the page, so that composition events can be sent to it */ +function attachInput(ed: DocxEditor) { + const on = new Map void>() + const g = globalThis as Record + const doc = g.document + g.document = { addEventListener() {}, removeEventListener() {} } + try { + ed.input.attach({ + addEventListener: (type: string, fn: (e: unknown) => void) => on.set(type, fn), + removeEventListener() {}, + contains: () => false, + querySelectorAll: () => [], + getRootNode: () => ({}), + ownerDocument: { getSelection: () => null }, + } as unknown as HTMLElement) + } finally { + g.document = doc + } + return { + start: () => on.get('compositionstart')!({}), + end: (data: string) => on.get('compositionend')!({ data }), + } +} + +/** text, list kind and marker of every paragraph (table cells too), in document order */ +function lists(blocks: Block[]) { + const out: string[] = [] + const para = (p: Paragraph) => out.push(`${runsText(p.runs as RRun[]).slice(0, 12)}|${p.lst ?? ''}|${p.marker?.text ?? ''}`) + for (const b of blocks) { + if (b.t === 'p') para(b) + else if (b.t === 'tbl') for (const r of b.rows) for (const c of r.cells) for (const x of c.blocks) if (x.t === 'p') para(x) + } + return out +} + +describe('DOCX conversion answers that cross other edits (#26, #29)', () => { + test('a second edit sent before the first conversion returns gets its own conversion (#26)', async () => { + const { client, ed, sel, states } = await editor() + const pending = holdEdits(client) + ed.toggleList('bullet') + ed.setPara({ align: 'center' }) + // the first answer comes while the second edit is still on its way + await deliver(pending, 0) + await deliver(pending, 1) + await settle(ed) + const p = ed.para(sel.a.pa)! + expect([p.ps.align, p.lst, p.marker?.text]).toEqual(['center', 'bullet', '•']) + expect(states.at(-1)).toMatchObject({ state: { align: 'center', lst: 'bullet' }, busy: false }) + // the file says the same + const reopened = await editor(await client.call('save')) + const q = reopened.ed.para(reopened.sel.a.pa)! + expect([q.ps.align, q.lst, q.marker?.text]).toEqual(['center', 'bullet', '•']) + }) + + test('the second edit is converted when the first answer comes after it too (#26)', async () => { + const { client, ed, sel, states } = await editor() + const pending = holdEdits(client) + ed.toggleList('bullet') + ed.setPara({ align: 'right' }) + await deliver(pending, 1) + await deliver(pending, 0) + await settle(ed) + const p = ed.para(sel.a.pa)! + expect([p.ps.align, p.lst, p.marker?.text]).toEqual(['right', 'bullet', '•']) + // published with the second answer (the first one still on its way); the first one, obsolete and the last in, + // tells the same state once more, no longer busy (#29) + expect(states.slice(-2)).toEqual([ + { state: expect.objectContaining({ align: 'right', lst: 'bullet' }), busy: true }, + { state: expect.objectContaining({ align: 'right', lst: 'bullet' }), busy: false }, + ]) + }) + + test('an obsolete list answer publishes nothing: a list turned on and undone never shows as on (#29)', async () => { + const { client, ed, sel, states } = await editor() + const pending = holdEdits(client) + ed.toggleList('bullet') + ed.undo() + await deliver(pending, 0) + await deliver(pending, 1) + await settle(ed) + // the list asked for (not known yet), the undo, the undo's conversion: never a pressed list button + expect(states.map((s) => ({ lst: s.state?.lst, busy: s.busy }))).toEqual([ + { lst: undefined, busy: true }, + { lst: undefined, busy: true }, + { lst: undefined, busy: false }, + ]) + expect(ed.para(sel.a.pa)?.lst).toBeUndefined() + expect(ed.para(sel.a.pa)?.marker).toBeUndefined() + }) + + test('the undo answered before the list it undoes: no list shown, and the last notification is not busy (#29)', async () => { + const { client, ed, sel, states } = await editor() + const pending = holdEdits(client) + ed.toggleList('bullet') + ed.undo() + await deliver(pending, 1) + await deliver(pending, 0) + await settle(ed) + // the list asked for, the undo, the undo's conversion (the list's answer still out), then that obsolete answer, + // the last in: the model as it stands, no longer busy + expect(states.map((s) => ({ lst: s.state?.lst, busy: s.busy }))).toEqual([ + { lst: undefined, busy: true }, + { lst: undefined, busy: true }, + { lst: undefined, busy: true }, + { lst: undefined, busy: false }, + ]) + expect(states.at(-1)).toEqual({ state: ed.state(sel), busy: false }) + expect(ed.para(sel.a.pa)?.lst).toBeUndefined() + expect(ed.para(sel.a.pa)?.marker).toBeUndefined() + }) + + test('the numbering of other paragraphs in an obsolete answer is still shown (#29)', async () => { + const { client, ed, st } = await editor() + const hire = paraAt(st, 'Hire the platform team') + const ship = paraAt(st, 'Ship the viewer engine') + const pending = holdEdits(client) + ed.input.lastSel = at(hire, 0, 4) + // the item leaves the list (the next ones count from 1), and is typed in before the answer comes + ed.toggleList('number') + ed.input.lastSel = at(hire, 4) + ed.insertText('!') + await deliver(pending, 0) + await deliver(pending, 1) + await settle(ed) + expect(ed.para(hire)?.lst).toBeUndefined() + expect(ed.para(ship)?.marker?.text).toBe('1.') + expect(lists(st.blocks)).toEqual(lists((await editor(await client.call('save'))).st.blocks)) + }) + + test('a throwing state listener does not make a conversion an unhandled rejection (#29)', async () => { + const { client, ed } = await editor() + const pending = holdEdits(client) + ed.toggleList('bullet') + const unhandled: unknown[] = [] + const onUnhandled = (e: unknown) => unhandled.push(e) + process.on('unhandledRejection', onUnhandled) + const logged = spyOn(console, 'error').mockImplementation(() => {}) + try { + ed.onState = () => { + throw new Error('listener failed') + } + await deliver(pending, 0) + await settle(ed) + await Bun.sleep(20) + expect(unhandled).toEqual([]) + expect(logged).toHaveBeenCalled() + } finally { + process.off('unhandledRejection', onUnhandled) + logged.mockRestore() + } + }) +}) + +describe('DOCX conversion answers during an IME composition (#28)', () => { + test('an answer that comes during an IME composition is applied when it ends (#28)', async () => { + const { client, ed, st, states } = await editor() + const ime = attachInput(ed) + const hire = paraAt(st, 'Hire the platform team') + const ship = paraAt(st, 'Ship the viewer engine') + const apac = paraAt(st, 'Expand to APAC') + const intro = paraAt(st, 'This document') + expect([ship, apac].map((pa) => ed.para(pa)?.marker?.text)).toEqual(['2.', '3.']) + const pending = holdEdits(client) + ed.input.lastSel = at(hire, 0, 4) + // the item leaves the list: the ones after it count from 1 + ed.toggleList('number') + // a composition starts in another paragraph before the answer comes + ed.input.lastSel = at(intro) + ime.start() + const count = states.length + await deliver(pending, 0) + expect(ed.input.isComposing).toBe(true) + // nothing rebuilt under the composition, nothing published (not even "no longer busy": the answer is not taken in) + expect(ed.busy).toBe(false) + expect(ed.para(hire)?.lst).toBe('number') expect(states).toHaveLength(count) - expect(states.at(-1)?.state?.b).toBe(true) + ime.end('ă') + expect(runsText(ed.para(intro)!.runs as RRun[])).toStartWith('ăThis') + expect(ed.para(hire)?.lst).toBeUndefined() + expect(ed.para(hire)?.marker).toBeUndefined() + expect([ship, apac].map((pa) => ed.para(pa)?.marker?.text)).toEqual(['1.', '2.']) + // the composed text, then the answer applied at its end + expect(states).toHaveLength(count + 2) + expect(states.at(-1)).toEqual({ state: ed.state(ed.input.sel()), busy: true }) + // the composed text's own answer, the last in, ends busy + await deliver(pending, 1) + await settle(ed) + expect(states).toHaveLength(count + 3) + expect(states.at(-1)).toEqual({ state: ed.state(ed.input.sel()), busy: false }) + expect(lists(st.blocks)).toEqual(lists((await editor(await client.call('save'))).st.blocks)) + }) +}) + +describe('DOCX lists in tables the editor regenerates (#27)', () => { + test('a list in a table inserted this session is shown, published, counted and removed (#27)', async () => { + const { client, ed, sel, st, states } = await editor() + const saved = async () => (await editor(await client.call('save'))).st.blocks + ed.input.lastSel = at(sel.a.pa) + ed.insertTable(2, 1) + const bi = Number(sel.a.pa) + 1 + expect(st.blocks[bi].t).toBe('tbl') + const a = `${bi}.0.0.0` + const b = `${bi}.1.0.0` + for (const [pa, text] of [[a, 'One'], [b, 'Two']]) { + ed.input.lastSel = at(pa) + ed.insertText(text) + } + await settle(ed) + + ed.input.lastSel = at(a, 0, 3) + ed.toggleList('bullet') + await settle(ed) + expect(ed.para(a)?.lst).toBe('bullet') + expect(ed.para(a)?.marker?.text).toBe('•') + expect(states.at(-1)).toMatchObject({ state: { lst: 'bullet', inTable: true }, busy: false }) + let file = await saved() + expect((file[bi] as Table).rows[0].cells[0].blocks[0]).toMatchObject({ lst: 'bullet', marker: { text: '•' } }) + expect(lists(st.blocks)).toEqual(lists(file)) + + // the second click takes it away again + ed.toggleList('bullet') + await settle(ed) + expect(ed.para(a)?.lst).toBeUndefined() + expect(ed.para(a)?.marker).toBeUndefined() + expect(states.at(-1)).toMatchObject({ state: { lst: undefined, inTable: true }, busy: false }) + file = await saved() + expect((file[bi] as Table).rows[0].cells[0].blocks[0]).not.toHaveProperty('lst') + expect(lists(st.blocks)).toEqual(lists(file)) + + // numbered items in its cells count in document order, with the numbered paragraphs after the table + for (const pa of [a, b, String(bi + 1)]) { + ed.input.lastSel = at(pa, 0, 1) + ed.toggleList('number') + } + await settle(ed) + expect(ed.para(a)?.lst).toBe('number') + const hire = () => ed.para(paraAt(st, 'Hire the platform team'))?.marker?.text + // (the sample's numbered list goes on from them: one list for the numbered paragraphs the editor makes) + expect([a, b, String(bi + 1)].map((pa) => ed.para(pa)?.marker?.text)).toEqual(['1.', '2.', '3.']) + expect(hire()).toBe('4.') + file = await saved() + expect(lists(st.blocks)).toEqual(lists(file)) + + // and with the table taken out, what came after it counts without its items + ed.input.lastSel = at(a) + ed.tableOp('delTable') + await settle(ed) + expect(st.blocks[bi].t).toBe('p') + expect(ed.para(String(bi))?.marker?.text).toBe('1.') + expect(hire()).toBe('2.') + file = await saved() + expect(lists(st.blocks)).toEqual(lists(file)) + }) + + test('a list in a table of the file restructured this session is shown and removed (#27)', async () => { + const { client, ed, st, states } = await editor() + const saved = async () => (await editor(await client.call('save'))).st.blocks + const ti = st.blocks.findIndex((b) => b.t === 'tbl') + const north = `${ti}.1.0.0` + expect(runsText(ed.para(north)!.runs as RRun[])).toBe('North') + // a row added: the table is written whole from now on + ed.input.lastSel = at(north) + ed.tableOp('rowBelow') + await settle(ed) + expect((st.blocks[ti] as Table).tid).toBeDefined() + + ed.input.lastSel = at(north, 0, 5) + ed.toggleList('bullet') + await settle(ed) + expect(ed.para(north)).toMatchObject({ lst: 'bullet', marker: { text: '•' } }) + expect(states.at(-1)).toMatchObject({ state: { lst: 'bullet', inTable: true }, busy: false }) + expect(lists(st.blocks)).toEqual(lists(await saved())) + + ed.toggleList('bullet') + await settle(ed) + expect(ed.para(north)?.lst).toBeUndefined() + expect(ed.para(north)?.marker).toBeUndefined() + expect(states.at(-1)).toMatchObject({ state: { lst: undefined, inTable: true }, busy: false }) + expect(lists(st.blocks)).toEqual(lists(await saved())) + }) + + test('a list turned on in a table cell, then typing in another cell before the answer: both kept (#26, #27)', async () => { + const { client, ed, sel, st } = await editor() + ed.input.lastSel = at(sel.a.pa) + ed.insertTable(1, 2) + const bi = Number(sel.a.pa) + 1 + const a = `${bi}.0.0.0` + const b = `${bi}.0.1.0` + ed.input.lastSel = at(a) + ed.insertText('One') + await settle(ed) + const pending = holdEdits(client) + ed.input.lastSel = at(a, 0, 3) + ed.toggleList('bullet') + ed.input.lastSel = at(b) + ed.insertText('Two') + await deliver(pending, 0) + await deliver(pending, 1) + await settle(ed) + expect(ed.para(a)?.lst).toBe('bullet') + expect(ed.para(a)?.marker?.text).toBe('•') + expect(runsText(ed.para(b)!.runs as RRun[])).toBe('Two') + expect(lists(st.blocks)).toEqual(lists((await editor(await client.call('save'))).st.blocks)) }) })