Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions e2e/docx-table.spec.ts
Original file line number Diff line number Diff line change
@@ -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()

Expand Down Expand Up @@ -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([])
})
})
53 changes: 33 additions & 20 deletions src/core/docx/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -875,6 +877,12 @@ export class DocxDocument {
genXml = new Map<number, string>()
/** whole body items replaced by the editor (regenerated tables; '' = deleted) */
itemXml = new Map<number, string>()
/**
* 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<number, number[]>()
newTables = new Map<number, number[]>()
/** styles the editor changed → their definition in the file as opened (parsed, and as source) */
styleOrig = new Map<string, { x: XEl; raw: RNode }>()
/** page setup of the final section as opened, and the changes made to it (written to every section on save) */
Expand Down Expand Up @@ -1114,32 +1122,37 @@ export class DocxDocument {
recomputeMarkers(): Map<number, PInfo> {
const changed = new Map<number, PInfo>()
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
Expand Down
2 changes: 2 additions & 0 deletions src/core/docx/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
83 changes: 58 additions & 25 deletions src/core/docx/writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -791,8 +791,12 @@ export async function applyEdit(doc: DocxDocument, op: EditOp): Promise<EditResu
doc.info.set(spec.pid, { ...rec, item, ord, marker: prev?.marker, lst: prev?.lst })
if (op.want) blocks[spec.pid] = bl
}
const listy2 = listy || op.list.some((x) => 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<number, Block[]>, 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
Expand Down Expand Up @@ -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<string> {
/**
* 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<string> {
let orig: RNode | undefined
if (spec.item !== undefined) {
const nodes = parseRaw(doc.items[spec.item] ?? '')
Expand Down Expand Up @@ -965,12 +972,13 @@ export async function genTable(doc: DocxDocument, spec: TableSpec): Promise<stri
const cell = cells[k++]
if (!cell) break
const span = Math.max(1, Math.min(cell.colSpan, nCols - g))
let paras = ''
let content = ''
for (const p of cell.paras) {
const orig = p.pristine && p.pid === p.from ? origPara(doc, p.pid) : undefined
paras += orig ? serialize(orig) : (await genParagraph(doc, p)).xml
const x = await paraXml(doc, p)
paras.push({ spec: p, ...x })
content += x.xml
}
out += `<${W}tc>${tcPrFor(cell.src, g, span, cell.rowSpan > 1 ? 'restart' : undefined, cell.shd, cell)}${paras || `<${W}p/>`}</${W}tc>`
out += `<${W}tc>${tcPrFor(cell.src, g, span, cell.rowSpan > 1 ? 'restart' : undefined, cell.shd, cell)}${content || `<${W}p/>`}</${W}tc>`
if (cell.rowSpan > 1) cont[g] = { left: cell.rowSpan - 1, span, src: cell.src, cell }
g += span
}
Expand All @@ -979,29 +987,54 @@ export async function genTable(doc: DocxDocument, spec: TableSpec): Promise<stri
return out + `</${W}tbl>`
}

export async function applyTable(doc: DocxDocument, op: TableOp): Promise<void> {
/**
* 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<EditResult> {
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<number, Block[]> = {}
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
Expand Down
2 changes: 1 addition & 1 deletion src/core/worker/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down
Loading