From d627c5352f2dc91d85676d03e002ab036a74e445 Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 11:25:37 +0700 Subject: [PATCH 1/9] feat(docx): keepLines and widowControl are read, from the paragraph, its style and the document defaults Co-Authored-By: Claude Opus 5.5 --- src/core/docx/styles.ts | 2 ++ src/core/docx/types.ts | 4 +++ test/docx-builder.ts | 60 ++++++++++++++++++++++++++++++++ test/docx-keep.test.ts | 76 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 142 insertions(+) create mode 100644 test/docx-builder.ts create mode 100644 test/docx-keep.test.ts diff --git a/src/core/docx/styles.ts b/src/core/docx/styles.ts index f8192bb..9318ad1 100644 --- a/src/core/docx/styles.ts +++ b/src/core/docx/styles.ts @@ -138,6 +138,8 @@ export function readPPr(pPr: XEl | undefined): PPrResult { break } case 'keepNext': ps.keepNext = onOff(c); break + case 'keepLines': ps.keepLines = onOff(c); break + case 'widowControl': ps.widowControl = onOff(c); break case 'contextualSpacing': ps.contextual = onOff(c); break case 'pageBreakBefore': ps.pageBreakBefore = onOff(c); break case 'outlineLvl': ps.outline = num(c.a.val); break diff --git a/src/core/docx/types.ts b/src/core/docx/types.ts index 4abf61f..0d09662 100644 --- a/src/core/docx/types.ts +++ b/src/core/docx/types.ts @@ -41,6 +41,10 @@ export interface ParaStyle { bLeft?: Border bRight?: Border keepNext?: boolean + /** the paragraph is not split across pages (w:keepLines) */ + keepLines?: boolean + /** widow / orphan control (w:widowControl); absent: on, as in Word */ + widowControl?: boolean pageBreakBefore?: boolean outline?: number contextual?: boolean diff --git a/test/docx-builder.ts b/test/docx-builder.ts new file mode 100644 index 0000000..816f30d --- /dev/null +++ b/test/docx-builder.ts @@ -0,0 +1,60 @@ +/** + * The smallest Word documents for tests: document.xml from a body, styles.xml from style elements and document + * defaults. Paragraphs and tables are written as WordprocessingML strings by the helpers below. + */ +import { writeZip } from '../src/core/zipwrite' + +const XML = '\n' +const W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main' +const R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' +const DOCX = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + +export interface DocxParts { + /** elements */ + styles?: string + /** the inside of */ + pPrDefault?: string + /** the inside of */ + rPrDefault?: string + /** the body's section properties (page size, margins): a letter page with 1 inch margins when absent */ + sectPr?: string +} + +const esc = (s: string) => s.replace(/&/g, '&').replace(//g, '>') + +/** a paragraph: `pPr` is the inside of , the text one run (`\n`: a line break) */ +export const para = (text: string, pPr = '') => + `${pPr ? `${pPr}` : ''}${text ? `${text.split('\n').map((t, i) => `${i ? '' : ''}${esc(t)}`).join('')}` : ''}` + +/** a table with a grid line on every cell: `rows[r][c]` the text of a cell; `header` leading rows repeat on each page */ +export function table(rows: string[][], opts: { widths?: number[]; header?: number; trPr?: (r: number) => string; tcPr?: (r: number, c: number) => string } = {}) { + const n = rows[0]?.length ?? 1 + const widths = opts.widths ?? Array(n).fill(Math.floor(9360 / n)) + const line = '' + const trs = rows.map((cells, r) => { + const trPr = `${r < (opts.header ?? 0) ? '' : ''}${opts.trPr?.(r) ?? ''}` + const tcs = cells.map((t, c) => `${opts.tcPr?.(r, c) ?? ''}${para(t)}`) + return `${trPr ? `${trPr}` : ''}${tcs.join('')}` + }) + return `${line}${widths.map((w) => ``).join('')}${trs.join('')}` +} + +const LETTER = '' + +/** a .docx holding `body` (paragraphs and tables) */ +export function bareDocx(body: string, parts: DocxParts = {}): Promise { + const defaults = `${parts.rPrDefault ?? ''}${parts.pPrDefault ?? ''}` + const normal = '' + return writeZip( + new Map( + Object.entries({ + '[Content_Types].xml': `${XML}`, + '_rels/.rels': `${XML}`, + 'word/_rels/document.xml.rels': `${XML}`, + 'word/styles.xml': `${XML}${defaults}${normal}${parts.styles ?? ''}`, + 'word/document.xml': `${XML}${body}${parts.sectPr ?? LETTER}`, + }), + ), + DOCX, + ) +} diff --git a/test/docx-keep.test.ts b/test/docx-keep.test.ts new file mode 100644 index 0000000..5d13413 --- /dev/null +++ b/test/docx-keep.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, test } from 'bun:test' +import { Engine } from '../src/core/worker/engine' +import { paraSpec } from '../src/core/docx/spec' +import type { Block, Paragraph } from '../src/core/docx/types' +import { BlobSource } from '../src/core/source' +import { ZipArchive } from '../src/core/zip' +import { bareDocx, para } from './docx-builder' + +async function open(src: Blob) { + const events: { event: string; data: any }[] = [] + const engine = new Engine((event, data) => events.push({ event, data })) + await engine.open(src, {}) + await engine.call('docx.start', []) + const paras = events.filter((e) => e.event === 'docx:blocks').flatMap((e) => e.data as Block[]).filter((b): b is Paragraph => b.t === 'p') + return { engine, paras } +} + +const text = (p: Paragraph) => p.runs.map((r) => (r.t === 'text' ? r.text : '')).join('') +const keep = (p: Paragraph) => ({ keepLines: p.ps.keepLines, widowControl: p.ps.widowControl }) + +const STYLES = + '' + + '' + +describe('keepLines / widowControl', () => { + test('read from the paragraph, from its style (and the styles it is based on), from the document defaults', async () => { + const body = [ + para('direct', ''), + para('direct off', ''), + para('style', ''), + para('based on', ''), + para('style overridden', ''), + para('plain'), + ].join('') + const { paras } = await open(await bareDocx(body, { styles: STYLES })) + expect(paras.map(text)).toEqual(['direct', 'direct off', 'style', 'based on', 'style overridden', 'plain']) + expect(paras.map(keep)).toEqual([ + { keepLines: true, widowControl: true }, + { keepLines: false, widowControl: false }, + { keepLines: true, widowControl: false }, + { keepLines: true, widowControl: false }, + { keepLines: false, widowControl: true }, + // nothing says: widow control is Word's default (the view treats undefined as on) + { keepLines: undefined, widowControl: undefined }, + ]) + + const defaults = await open(await bareDocx(para('a') + para('b', ''), { pPrDefault: '' })) + expect(defaults.paras.map(keep)).toEqual([ + { keepLines: true, widowControl: false }, + { keepLines: false, widowControl: true }, + ]) + }) + + test('kept when an edited paragraph is written back, and after a save and reopen', async () => { + const body = para('first', '') + para('second', '') + para('third') + const { engine, paras } = await open(await bareDocx(body, { styles: STYLES })) + // the text of each paragraph changes, and the first is split in two (Enter): the new one is made from it + const [p0, p1] = paras + const a = { ...p0, runs: [{ t: 'text' as const, text: 'first edited', s: {} }], edited: true } + const b = { ...p0, runs: [{ t: 'text' as const, text: 'new', s: {} }], pid: 1_000_000_000, from: p0.pid, orig: [], edited: true } + await engine.call('docx.edit', [{ anchor: p0.pid, list: [paraSpec([a]), paraSpec([b])] }]) + await engine.call('docx.edit', [{ anchor: p1.pid, list: [paraSpec([{ ...p1, runs: [{ t: 'text', text: 'second edited', s: {} }], edited: true }])] }]) + const saved = (await engine.call('save', [])) as Blob + const xml = await (await ZipArchive.open(new BlobSource(saved))).text('word/document.xml') + expect(xml.match(//g)?.length).toBe(2) + expect(xml.match(//g)?.length).toBe(2) + const re = await open(saved) + expect(re.paras.map(text)).toEqual(['first edited', 'new', 'second edited', 'third']) + expect(re.paras.map(keep)).toEqual([ + { keepLines: true, widowControl: false }, + { keepLines: true, widowControl: false }, + { keepLines: true, widowControl: false }, + { keepLines: undefined, widowControl: undefined }, + ]) + }) +}) From be61c6711b0f22eadbd9d8a0cde717e12e931842 Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 11:28:11 +0700 Subject: [PATCH 2/9] feat(docx): pagination cuts paragraphs between lines and tables between rows, header rows repeated The pure page cutter, given where each block's lines or rows are: what does not fit a page goes on on the next one, one line or row taller than a page makes its page grow, text columns are filled the same way. Co-Authored-By: Claude Opus 5.5 --- src/react/docx/paginate.ts | 176 ++++++++++++++++++++++++++++++++----- test/docx-paginate.test.ts | 176 +++++++++++++++++++++++++++++++++++++ 2 files changed, 329 insertions(+), 23 deletions(-) create mode 100644 test/docx-paginate.test.ts diff --git a/src/react/docx/paginate.ts b/src/react/docx/paginate.ts index 1755d97..5d9c20b 100644 --- a/src/react/docx/paginate.ts +++ b/src/react/docx/paginate.ts @@ -11,19 +11,54 @@ export function pageHF(meta: DocxMeta | undefined, index: number): { header?: Bl return { header: meta?.header, footer: meta?.footer, hk: 'header', fk: 'footer' } } -/** the blocks [start, end) of a page and the height they take */ +/** + * Where a block can be split, as the measure pass read it: its lines (a paragraph) or rows (a table). A block without + * one is placed whole. + */ +export interface Lines { + /** the top of each line / row and the bottom of the last, from the top of the block (px) */ + ys: number[] + /** paragraph: the offset each line starts at, read once a page ends inside the paragraph (undefined: not read yet) */ + at?: (number | undefined)[] + /** table: how many leading rows repeat at the top of each following page (w:tblHeader) */ + head?: number + /** table: row boundaries it does not break at (a merged cell going on below them would not fit above) */ + keep?: number[] +} + +/** + * The blocks [start, end) of a page and the height they take. The first may have begun on an earlier page (`from`), + * the last may go on on the next one (`to`): lines of a paragraph, rows of a table. + */ export interface PageSlice { start: number end: number used: number + /** the line / row block `start` starts at on this page (0: its start) */ + from: number + /** the line / row block `end - 1` stops before on this page; undefined: it ends here */ + to?: number + /** text columns: where each column after the first starts, as [block, line / row] */ + cols?: [number, number][] +} + +const EPS = 0.01 + +/** the lines / rows a block is cut into: its measured lines, or one unit as tall as the block */ +function unitsOf(h: number, l: Lines | undefined): { ys: number[]; n: number } { + if (l && l.ys.length >= 2) return { ys: l.ys, n: l.ys.length - 1 } + return { ys: [0, h], n: 1 } } /** - * Cuts the blocks into pages. With text columns (`cols` > 1) a page holds `cols` columns of `avail`: a block that does - * not fit what is left of a column starts the next one (blocks are never split, as for pages), and `used` is the - * tallest column. + * Cuts the blocks into pages. A paragraph that does not fit what is left of a page is split between two lines, a table + * between two rows, its header rows repeated at the top of the next page; a block with no line or row that fits + * starts the next page, and one that does not fit an empty page either (one line or one row taller than the page) is + * placed anyway: its page grows (`used` > `avail`). The space after the last paragraph of a page needs no room. + * With text columns (`cols` > 1) a page holds `cols` columns of `avail`, filled the same way one after the other; + * `used` is the tallest. */ -export function paginate(blocks: Block[], heights: WeakMap, count: number, avail: number, cols = 1, lastKind = 'nextPage'): PageSlice[] { +export function paginate(blocks: Block[], heights: WeakMap, count: number, avail: number, cols = 1, lastKind = 'nextPage', lines?: WeakMap): PageSlice[] { // a section's type says how it starts: the break after a section is the next section's ('continuous': no new page); // the last section's is the body's (known once loaded) const breakAfter = new Map() @@ -35,35 +70,130 @@ export function paginate(blocks: Block[], heights: WeakMap, count nextKind = b.kind } const pages: PageSlice[] = [] - let cur: PageSlice = { start: 0, end: 0, used: 0 } + let cur: PageSlice = { start: 0, end: 0, used: 0, from: 0 } let col = 0 - let inCol = 0 - const next = (start: number) => { + /** height used in the column, and the same without the space after its last paragraph */ + let y = 0 + let ink = 0 + const colEnd = () => { + cur.used = Math.max(cur.used, y <= avail + EPS ? y : Math.max(avail, ink)) + y = 0 + ink = 0 + } + const newPage = (start: number, from: number) => { + colEnd() pages.push(cur) - cur = { start, end: start, used: 0 } + cur = { start, end: start, used: 0, from } col = 0 - inCol = 0 + } + /** the rest of the page or column is left empty; what comes next starts at line / row `k` of block `bi` */ + const advance = (bi: number, k: number) => { + if (col + 1 < cols) { + colEnd() + col++ + ;(cur.cols ??= []).push([bi, k]) + } else newPage(bi, k) } for (let i = 0; i < count; i++) { const b = blocks[i] - const h = heights.get(b) ?? 0 if (b.t === 'sect') { cur.end = i + 1 - if (breakAfter.get(i) !== 'continuous') next(i + 1) + cur.to = undefined + if (breakAfter.get(i) !== 'continuous') newPage(i + 1, 0) continue } - const forced = b.t === 'p' && b.pb && cur.end > cur.start - if (forced) next(i) - else if (inCol > 0 && inCol + h > avail) { - if (col + 1 < cols) { - col++ - inCol = 0 - } else next(i) + if (b.t === 'p' && b.pb && cur.end > cur.start) newPage(i, 0) + const h = heights.get(b) ?? 0 + const l = lines?.get(b) + const { ys, n } = unitsOf(h, l) + const table = b.t === 'tbl' + // header rows repeat when they leave room for a row below them + const head = table && l?.head && l.head < n && ys[l.head] - ys[0] < avail ? l.head : 0 + const headH = head ? ys[head] - ys[0] : 0 + const keep = table && l?.keep?.length ? new Set(l.keep) : undefined + // the last line of a paragraph ends before its space after; a table's bottom border is part of it + const inkEnd = table ? h : ys[n] + const canBreak = (j: number) => j > 0 && j < n && j > head && !keep?.has(j) + const pieceH = (k: number, j: number) => (k > 0 ? headH - ys[k] : 0) + (j === n ? h : ys[j]) + const pieceInk = (k: number, j: number) => (k > 0 ? headH - ys[k] : 0) + (j === n ? inkEnd : ys[j]) + const place = (k: number, j: number) => { + cur.end = i + 1 + cur.to = j < n ? j : undefined + y += pieceH(k, j) + ink = y - (j === n ? h - inkEnd : 0) + } + for (let k = 0; ; ) { + const room = avail - y + if (pieceInk(k, n) <= room + EPS) { + place(k, n) + break + } + // the most lines / rows that fit + let j = -1 + for (let x = k + 1; x < n && pieceInk(k, x) <= room + EPS; x++) if (canBreak(x)) j = x + if (j < 0 && y > 0) { + advance(i, k) + continue + } + // nothing fits an empty page or column: the smallest piece there is, its page grows + if (j < 0) { + j = k + 1 + while (j < n && !canBreak(j)) j++ + } + place(k, j) + if (j === n) break + advance(i, j) + k = j } - cur.end = i + 1 - inCol += h - cur.used = Math.max(cur.used, cols > 1 ? Math.min(inCol, avail) : inCol) } - if (cur.end > cur.start || !pages.length) pages.push(cur) + if (cur.end > cur.start || !pages.length) { + colEnd() + pages.push(cur) + } return pages } + +/** the slice of each column of a page (one: the page itself) */ +export function columnsOf(p: PageSlice): PageSlice[] { + if (!p.cols?.length) return [p] + const cuts: [number, number][] = [[p.start, p.from], ...p.cols] + const last: [number, number] = p.to !== undefined ? [p.end - 1, p.to] : [p.end, 0] + return cuts.map(([bi, k], c) => { + const [eb, ek] = c + 1 < cuts.length ? cuts[c + 1] : last + return { start: bi, from: k, end: ek > 0 ? eb + 1 : eb, to: ek > 0 ? ek : undefined, used: p.used } + }) +} + +/** the lines / rows [from, to) of block `bi` that a page (or column) holds; to undefined: to its end */ +export function pieceOf(p: PageSlice, bi: number): { from: number; to?: number } { + return { from: bi === p.start ? p.from : 0, to: bi === p.end - 1 ? p.to : undefined } +} + +/** the first and last page holding a part of block `bi`; [-1, -1] when none does (not laid out yet) */ +export function pagesOf(pages: PageSlice[], bi: number): [number, number] { + // pages are in block order: the first whose end is past the block + let lo = 0 + let hi = pages.length + while (lo < hi) { + const m = (lo + hi) >> 1 + if (pages[m].end <= bi) lo = m + 1 + else hi = m + } + if (lo >= pages.length || pages[lo].start > bi) return [-1, -1] + let last = lo + while (last + 1 < pages.length && pages[last + 1].start <= bi && pages[last + 1].end > bi) last++ + return [lo, last] +} + +/** + * The page showing offset `o` of paragraph `bi` (a paragraph split across pages is on several); the first of its pages + * when where its lines start is not read yet. + */ +export function pageAt(pages: PageSlice[], bi: number, o: number, l: Lines | undefined): number { + const [first, last] = pagesOf(pages, bi) + for (let pi = last; pi > first; pi--) { + const at = l?.at?.[pieceOf(pages[pi], bi).from] + if (at !== undefined && o >= at) return pi + } + return first +} diff --git a/test/docx-paginate.test.ts b/test/docx-paginate.test.ts new file mode 100644 index 0000000..0603e8f --- /dev/null +++ b/test/docx-paginate.test.ts @@ -0,0 +1,176 @@ +import { describe, expect, test } from 'bun:test' +import type { Block, PageSetup, ParaStyle } from '../src/core/docx/types' +import { DEFAULT_PAGE } from '../src/core/docx/types' +import { columnsOf, pageAt, pagesOf, paginate, pieceOf, type Lines, type PageSlice } from '../src/react/docx/paginate' + +const page: PageSetup = { ...DEFAULT_PAGE } + +interface Spec { + /** paragraph: line heights; table: row heights */ + p?: number[] + t?: number[] + /** space before / after a paragraph */ + before?: number + after?: number + head?: number + keep?: number[] + pb?: boolean + ps?: ParaStyle + sect?: string + /** a block measured as a whole only (no lines read) */ + h?: number +} + +/** blocks with their measures: lines / rows of the given heights */ +function doc(specs: Spec[]) { + const blocks: Block[] = [] + const heights = new WeakMap() + const lines = new WeakMap() + for (const s of specs) { + if (s.sect) { + const b: Block = { t: 'sect', page, kind: s.sect } + blocks.push(b) + heights.set(b, 0) + continue + } + const b: Block = s.t ? { t: 'tbl', cols: [100], rows: s.t.map(() => ({ cells: [] })) } : { t: 'p', ps: s.ps ?? {}, runs: [], pb: s.pb } + blocks.push(b) + if (s.h !== undefined) { + heights.set(b, s.h) + continue + } + const units = s.p ?? s.t! + const ys = [s.before ?? 0] + for (const u of units) ys.push(ys[ys.length - 1] + u) + heights.set(b, ys[ys.length - 1] + (s.after ?? 0)) + lines.set(b, { ys, head: s.head, keep: s.keep }) + } + return { blocks, heights, lines } +} + +const run = (specs: Spec[], avail = 100, cols = 1, lastKind?: string) => { + const d = doc(specs) + return paginate(d.blocks, d.heights, d.blocks.length, avail, cols, lastKind, d.lines) +} + +/** each page as its pieces: `b` (whole block b) or `b:from-to` (lines / rows of block b) */ +function pieces(pages: PageSlice[]): string[][] { + return pages.map((p) => + columnsOf(p).flatMap((c) => { + const out: string[] = [] + for (let bi = c.start; bi < c.end; bi++) { + const { from, to } = pieceOf(c, bi) + out.push(from === 0 && to === undefined ? String(bi) : `${bi}:${from}-${to ?? 'end'}`) + } + return out + }), + ) +} + +const lines = (n: number, h = 10) => Array(n).fill(h) + +describe('paragraphs split between lines', () => { + test('the lines that fit stay, the rest goes on on the next page', () => { + // 6 lines of 10 fit under 40: 4 stay + const pages = run([{ p: [60] }, { p: lines(6) }]) + expect(pieces(pages)).toEqual([['0', '1:0-4'], ['1:4-end']]) + expect(pages.map((p) => p.used)).toEqual([100, 20]) + }) + + test('a paragraph longer than a page is cut on every page', () => { + expect(pieces(run([{ p: lines(25) }]))).toEqual([['0:0-10'], ['0:10-20'], ['0:20-end']]) + }) + + test('the space before counts on its first page only; the space after needs no room', () => { + // before 15: 15 + 8 lines = 95, the 9th line does not fit + expect(pieces(run([{ p: lines(12), before: 15 }]))).toEqual([['0:0-8'], ['0:8-end']]) + // the lines fit, the space after does not: the paragraph stays whole, the next one starts the next page + const pages = run([{ p: lines(9), after: 20 }, { p: lines(2) }]) + expect(pieces(pages)).toEqual([['0'], ['1']]) + expect(pages[0].used).toBe(100) + }) + + test('a paragraph measured as a whole (lines not read yet) moves whole', () => { + expect(pieces(run([{ p: [70] }, { h: 50 }]))).toEqual([['0'], ['1']]) + }) + + test('a line taller than the page: its page grows, nothing is lost', () => { + const pages = run([{ p: [30] }, { p: [10, 150, 10] }]) + expect(pieces(pages)).toEqual([['0', '1:0-1'], ['1:1-2'], ['1:2-end']]) + expect(pages.map((p) => p.used)).toEqual([40, 150, 10]) + }) +}) + +describe('tables split between rows', () => { + test('rows that fit stay; the header rows repeat on each following page', () => { + // 25 rows of 10, one header row: 10 rows on page 1, then the header + 9 rows per page + const pages = run([{ t: lines(25), head: 1 }]) + expect(pieces(pages)).toEqual([['0:0-10'], ['0:10-19'], ['0:19-end']]) + expect(pages.map((p) => p.used)).toEqual([100, 100, 70]) + }) + + test('a table after a paragraph starts on its page when its header and a row fit there', () => { + expect(pieces(run([{ p: lines(8) }, { t: lines(5), head: 1 }]))).toEqual([['0', '1:0-2'], ['1:2-end']]) + // only the header would fit: the table starts on the next page + expect(pieces(run([{ p: lines(9) }, { t: lines(5), head: 1 }]))).toEqual([['0'], ['1']]) + }) + + test('a header taller than the page is not repeated', () => { + expect(pieces(run([{ t: [120, 10, 10], head: 1 }]))).toEqual([['0:0-1'], ['0:1-end']]) + }) + + test('a row is never split: one taller than the page makes its page grow', () => { + const pages = run([{ t: [10, 130, 10] }]) + expect(pieces(pages)).toEqual([['0:0-1'], ['0:1-2'], ['0:2-end']]) + expect(pages.map((p) => p.used)).toEqual([10, 130, 10]) + // with a header row: it comes first on the grown page + const h = run([{ t: [10, 20, 130, 10], head: 1 }]) + expect(pieces(h)).toEqual([['0:0-2'], ['0:2-3'], ['0:3-end']]) + expect(h.map((p) => p.used)).toEqual([30, 140, 20]) + }) + + test('boundaries a merged cell spans are kept together', () => { + // rows 3-6 hold a merged cell too tall to be cut at 4, 5 or 6: 5 rows would fit, 3 stay + expect(pieces(run([{ t: lines(12), keep: [4, 5, 6] }], 55))).toEqual([['0:0-3'], ['0:3-8'], ['0:8-end']]) + }) +}) + +describe('breaks, sections, columns', () => { + test('a forced page break and a section break still start a page, after split blocks too', () => { + expect(pieces(run([{ p: lines(15) }, { p: lines(2), pb: true }, { p: lines(2) }]))).toEqual([['0:0-10'], ['0:10-end'], ['1', '2']]) + expect(pieces(run([{ p: lines(15) }, { sect: 'nextPage' }, { p: lines(2) }], 100, 1, 'nextPage'))).toEqual([['0:0-10'], ['0:10-end', '1'], ['2']]) + expect(pieces(run([{ p: lines(15) }, { sect: 'nextPage' }, { p: lines(2) }], 100, 1, 'continuous'))).toEqual([['0:0-10'], ['0:10-end', '1', '2']]) + }) + + test('text columns are filled one after the other, blocks split between them', () => { + const pages = run([{ p: lines(8) }, { p: lines(6) }, { t: lines(30), head: 1 }], 100, 2) + // column 1: block 0 and 2 lines of block 1; column 2: the rest of block 1 and the table up to row 6; then the + // header and 9 rows in each column + expect(pieces(pages)).toEqual([ + ['0', '1:0-2', '1:2-end', '2:0-6'], + ['2:6-15', '2:15-24'], + ['2:24-end'], + ]) + expect(columnsOf(pages[0]).map((c) => [c.start, c.from, c.end, c.to])).toEqual([ + [0, 0, 2, 2], + [1, 2, 3, 6], + ]) + }) + + test('the pages of a block, the page of an offset', () => { + const d = doc([{ p: [50] }, { p: lines(24) }, { p: [10] }]) + const pages = paginate(d.blocks, d.heights, d.blocks.length, 100, 1, undefined, d.lines) + expect(pieces(pages)).toEqual([['0', '1:0-5'], ['1:5-15'], ['1:15-end', '2']]) + expect(pagesOf(pages, 0)).toEqual([0, 0]) + expect(pagesOf(pages, 1)).toEqual([0, 2]) + expect(pagesOf(pages, 2)).toEqual([2, 2]) + expect(pagesOf(pages, 3)).toEqual([-1, -1]) + const l = d.lines.get(d.blocks[1])! + // line starts not read yet: the first page + expect(pageAt(pages, 1, 400, l)).toBe(0) + l.at = [] + l.at[5] = 100 + l.at[15] = 300 + expect([0, 99, 100, 299, 300, 500].map((o) => pageAt(pages, 1, o, l))).toEqual([0, 0, 1, 1, 2, 2]) + }) +}) From 7b82e6aac73e08ca9d517d393e803744b6585775 Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 11:34:22 +0700 Subject: [PATCH 3/9] feat(docx): a table longer than the rest of a page goes on on the next one, its header rows repeated The measure pass reads where the rows of a table are; pages cut it between rows. The pages after the first start with a copy of the header rows (shown, not editable). A merged cell cut by a page end keeps its text on its first page and goes on below as an empty cell; one whose text would not fit above the cut keeps those rows together. Text columns are laid out as columns of their own, filled like pages. Co-Authored-By: Claude Opus 5.5 --- e2e/docx-page.spec.ts | 3 +- e2e/docx-split.spec.ts | 126 +++++++++++++++++++++++++++++++++++ src/react/docx/DocxEditor.ts | 22 ++++-- src/react/docx/DocxView.tsx | 110 ++++++++++++++++++++---------- src/react/docx/measure.ts | 33 +++++++++ src/react/docx/paginate.ts | 9 ++- src/react/docx/render.tsx | 123 ++++++++++++++++++++++++---------- src/react/styles.css | 1 - 8 files changed, 344 insertions(+), 83 deletions(-) create mode 100644 e2e/docx-split.spec.ts create mode 100644 src/react/docx/measure.ts diff --git a/e2e/docx-page.spec.ts b/e2e/docx-page.spec.ts index c93a282..3e90c58 100644 --- a/e2e/docx-page.spec.ts +++ b/e2e/docx-page.spec.ts @@ -41,8 +41,7 @@ describe('docx page setup', () => { const after = await pageBox(v) expect(after.width / after.height).toBeCloseTo(841.9 / 595.3, 1) - const colsCss = await v.page.locator('.de-page-cols').first().evaluate((el) => getComputedStyle(el).columnCount) - expect(colsCss).toBe('2') + expect(await v.page.locator('.de-page').first().locator('.de-page-cols > .de-page-col').count()).toBe(2) if (SHOTS) await v.page.screenshot({ path: `${SHOTS}/page-setup-2cols.png` }) const m = await metaOf((await v.save()).bytes) diff --git a/e2e/docx-split.spec.ts b/e2e/docx-split.spec.ts new file mode 100644 index 0000000..f240fe3 --- /dev/null +++ b/e2e/docx-split.spec.ts @@ -0,0 +1,126 @@ +import { describe, expect, test } from 'bun:test' +import type { Paragraph, Table } from '../src/core/docx/types' +import { bareDocx, para, table } from '../test/docx-builder' +import { docxBlocks, paraText, useBrowser, viewer, type Viewer } from './harness' + +useBrowser() + +/** opens a built document in the fixture, editable, at `zoom`; waits until every page is laid out */ +async function open(doc: Blob | Promise, zoom = 1) { + const v = await viewer({ editable: true, onSave: true }, { wait: false }) + const b64 = Buffer.from(await (await doc).arrayBuffer()).toString('base64') + await v.page.evaluate(([b, z]) => window.__setProps({ src: new Blob([Uint8Array.from(atob(b as string), (c) => c.charCodeAt(0))]), name: 'split.docx', zoom: z as number }), [b64, zoom] as const) + await v.ready('docx') + await v.page.waitForFunction(() => /Page \d+ of \d+ ·/.test(document.querySelector('.de-bar .de-status')?.textContent ?? '')) + await v.page.waitForTimeout(200) + return v +} + +const pageCount = async (v: Viewer) => Number(/Page \d+ of (\d+)/.exec(await v.status())![1]) + +/** scrolls page `n` (1-based) to the top of the view */ +async function showPage(v: Viewer, n: number) { + await v.page.evaluate((k) => { + const sc = document.querySelector('.de-scroll')! + const el = document.querySelector(`.de-page[data-page="${k}"]`) + if (el) sc.scrollTop = el.offsetTop - 16 + else sc.scrollTop = ((k - 1) / Number(/of (\d+)/.exec(document.querySelector('.de-bar .de-status')!.textContent!)![1])) * sc.scrollHeight + }, n) + await v.page.locator(`.de-page[data-page="${n}"]`).waitFor() + await v.page.waitForTimeout(150) +} + +/** what each page shows: the text of its paragraphs (by address), the text of its table rows (copies apart) */ +async function pageContent(v: Viewer, n: number) { + await showPage(v, n) + return v.page.locator(`.de-page[data-page="${n}"]`).evaluate((pg) => { + const rows = Array.from(pg.querySelectorAll('tr')).map((tr) => ({ copy: tr.classList.contains('de-head-copy'), text: Array.from(tr.cells).map((c) => c.innerText.trim()).join('|') })) + const paras = Array.from(pg.querySelectorAll('.de-page-inner > div:not(.de-hf):not(.de-hf-zone) [data-pa]:not([data-pa*="."])')).map((p) => ({ pa: p.dataset.pa!, text: p.textContent ?? '' })) + const inner = pg.querySelector('.de-page-inner')! + const box = inner.getBoundingClientRect() + return { rows, paras, top: pg.getBoundingClientRect().top, height: pg.getBoundingClientRect().height, zoom: box.height / inner.offsetHeight } + }) +} + +describe('a table longer than a page', () => { + test('a merged cell cut by the page end: its text stays on the first page, an empty cell goes on below', async () => { + const body = [['Head A', 'Head B'], ...Array.from({ length: 70 }, (_, i) => [i === 0 ? 'Group' : '', `row ${i + 1} b`])] + const merge = (r: number, c: number) => (c === 0 && r >= 1 ? (r === 1 ? '' : '') : '') + const v = await open(bareDocx(table(body, { header: 1, tcPr: merge }))) + const n = await pageCount(v) + expect(n).toBeGreaterThanOrEqual(2) + const second: string[] = [] + let groups = 0 + for (let k = 1; k <= n; k++) { + await showPage(v, k) + const c = await v.page.locator(`.de-page[data-page="${k}"]`).evaluate((pg) => + Array.from(pg.querySelectorAll('tr:not(.de-head-copy)')).map((tr) => Array.from((tr as HTMLTableRowElement).cells).map((td) => ({ text: td.innerText.trim(), span: td.rowSpan }))), + ) + groups += c.flat().filter((x) => x.text === 'Group').length + // the merged cell spans the rows of its page + const first = k === 1 ? 1 : 0 + expect(c[first][0].span).toBe(c.length - first) + expect(c[first][0].text).toBe(k === 1 ? 'Group' : '') + second.push(...c.map((cells) => cells[cells.length - 1].text)) + } + expect(groups).toBe(1) + expect(second).toEqual(body.map((r) => r[1])) + expect(v.errors).toEqual([]) + }) + + const rows = [['Head A', 'Head B'], ...Array.from({ length: 70 }, (_, i) => [`row ${i + 1} a`, `row ${i + 1} b`])] + const doc = () => bareDocx(para('Before the table') + table(rows, { header: 1 }) + para('After the table')) + + test('goes on on the next pages, its header row repeated, every row shown once', async () => { + const v = await open(doc()) + const n = await pageCount(v) + expect(n).toBeGreaterThanOrEqual(2) + const seen: string[] = [] + for (let k = 1; k <= n; k++) { + const c = await pageContent(v, k) + const copies = c.rows.filter((r) => r.copy) + // page 1 holds the header itself, the following pages a copy of it first + if (k === 1) expect(copies).toEqual([]) + else if (c.rows.length) expect(c.rows[0]).toEqual({ copy: true, text: 'Head A|Head B' }) + seen.push(...c.rows.filter((r) => !r.copy).map((r) => r.text)) + // no page grows past the paper (a row is never taller than the page here) + expect(c.height / c.zoom).toBeCloseTo(792 * (4 / 3), 0) + } + expect(seen).toEqual(rows.map((r) => r.join('|'))) + expect(v.errors).toEqual([]) + }) + + test('the copy is not editable; a cell on the next page is; the header edited on page 1 shows in the copy', async () => { + const v = await open(doc()) + await showPage(v, 2) + const copy = v.page.locator('.de-page[data-page="2"] tr.de-head-copy').first() + expect(await copy.evaluate((tr) => (tr as HTMLElement).isContentEditable)).toBe(false) + expect(await copy.locator('[data-pa]').count()).toBe(0) + // a click on the copy does not put the caret in it, typing changes nothing there + await copy.locator('td').first().click() + await v.page.keyboard.type('Q') + expect(await copy.innerText()).not.toContain('Q') + + // a cell of a row on page 2 + const cell = v.page.locator('.de-page[data-page="2"] tr:not(.de-head-copy) td').nth(2) + const before = (await cell.innerText()).trim() + await v.selectText(before, 'end') + await v.page.keyboard.type(' edited') + expect((await cell.innerText()).trim()).toBe(`${before} edited`) + + // the header itself, on page 1 + await showPage(v, 1) + await v.selectText('Head A', 'end') + await v.page.keyboard.type('Z') + await showPage(v, 2) + expect(await v.page.locator('.de-page[data-page="2"] tr.de-head-copy').first().innerText()).toContain('Head AZ') + + const blocks = await docxBlocks((await v.save()).bytes) + const t = blocks.find((b): b is Table => b.t === 'tbl')! + const cellText = (r: number, c: number) => paraText(t.rows[r].cells[c].blocks[0] as Paragraph) + expect(cellText(0, 0)).toBe('Head AZ') + expect(t.rows.flatMap((_, r) => [cellText(r, 0), cellText(r, 1)]).filter((x) => x.includes('edited'))).toEqual([`${before} edited`]) + expect(t.rows.length).toBe(rows.length) + expect(v.errors).toEqual([]) + }) +}) diff --git a/src/react/docx/DocxEditor.ts b/src/react/docx/DocxEditor.ts index d292804..6b93c61 100644 --- a/src/react/docx/DocxEditor.ts +++ b/src/react/docx/DocxEditor.ts @@ -13,6 +13,7 @@ import { htmlToParas, type PastedCell, type PastedPara } from '../../core/html' import { docxBodyHtml, docxToText } from '../file/text' import { cellsIn, deleteCol, deleteRow, distributeCols, gridOf, insertCol, insertRow, mergeCells, newTable, patchCells, rectOf, setBorders, tableFromRows, unmergeCell, type BorderPreset, type CellRect } from './tables' import { changeSpans, hasChanges, resolveRuns, trackEdit } from './track' +import type { Lines } from './paginate' import { collapsed, formatRange, linkSpan, markRange, normalize, plen, rlen, runAt, runsText, shiftPa, splitRuns, type Pos, type RRun, type Sel } from '../edit/rich' /** a place in a paragraph that survives edits elsewhere: paragraph id, page-break part, offset */ @@ -52,6 +53,8 @@ const marksOf = (ps: Paragraph[]) => { export interface DocState { blocks: Block[] heights: WeakMap + /** where the lines of a measured paragraph / the rows of a measured table are (where pages can cut them) */ + lines?: WeakMap dirty: Set /** leading blocks measured at least once */ frontier: number @@ -373,6 +376,17 @@ export class DocxEditor implements RichHost { // ---------------------------------------------------------------- mutation core + /** + * `next` replaces `was` on the page: measured again soon, laid out meanwhile as `was` was (its height; its rows when + * a table keeps the same rows) + */ + private estimate(was: Block | undefined, next: Block) { + this.st.heights.set(next, (was && this.st.heights.get(was)) ?? 0) + const l = was && this.st.lines?.get(was) + if (l && next.t === 'tbl' && was.t === 'tbl' && next.rows.length === was.rows.length) this.st.lines!.set(next, l) + this.st.dirty.add(next) + } + private splice(pa: string, count: number, next: Block[]): Block[] { const c = this.container(pa)! if (!c.cell) { @@ -384,8 +398,7 @@ export class DocxEditor implements RichHost { const blocks = [...c.list] blocks.splice(c.at, count, ...next) const nt: Table = { ...t, rows: t.rows.map((r, i) => (i !== ri ? r : { ...r, cells: r.cells.map((cell, j) => (j !== ci ? cell : { ...cell, blocks })) })) } - this.st.heights.set(nt, this.st.heights.get(t) ?? 0) - this.st.dirty.add(nt) + this.estimate(t, nt) this.st.blocks[bi] = nt return blocks } @@ -1036,10 +1049,7 @@ export class DocxEditor implements RichHost { replaceBlocks(bi: number, count: number, next: Block[], sel: Sel | null, history = true) { const before = this.st.blocks.slice(bi, bi + count) this.st.blocks.splice(bi, count, ...next) - next.forEach((b, i) => { - this.st.heights.set(b, this.st.heights.get(before[i] ?? before[0]) ?? 0) - this.st.dirty.add(b) - }) + next.forEach((b, i) => this.estimate(before[i] ?? before[0], b)) if (bi < this.st.frontier) this.st.frontier = Math.max(0, this.st.frontier + next.length - count) const key = (b: Block) => (b.t === 'tbl' ? `t${b.tid ?? 'i' + b.item}` : b.t === 'p' ? `p${b.pid}` : '') const nextKeys = new Set(next.map(key)) diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index 358f61b..512285e 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -24,7 +24,8 @@ import { PageSetupDialog } from './PageSetupDialog' import { mergeSource } from '../../core/plainmerge' import { docxBodyHtml, docxToHtml, docxToMarkdown, docxToText, pictureData } from '../file/text' import { BlockView, contextual, type RenderCtx } from './render' -import { pageHF, paginate, type PageSlice } from './paginate' +import { columnsOf, headOf, pageAt, pageHF, pagesOf, paginate, pieceOf, type Lines, type PageSlice } from './paginate' +import { tableLines } from './measure' const PX = 4 / 3 const GAP = 16 @@ -76,7 +77,7 @@ export interface DocxViewProps { export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProps) { const viewer = useViewer() - const st = useRef({ blocks: [], heights: new WeakMap(), dirty: new Set(), frontier: 0 }).current + const st = useRef }>({ blocks: [], heights: new WeakMap(), lines: new WeakMap(), dirty: new Set(), frontier: 0 }).current const [version, bump] = useForceUpdate() const [meta, setMeta] = useState(null) const [pageDlg, setPageDlg] = useState(false) @@ -156,6 +157,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp if (lastKey.current !== widthKey) { lastKey.current = widthKey st.heights = new WeakMap() + st.lines = new WeakMap() st.dirty.clear() st.frontier = 0 } @@ -175,11 +177,16 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp useIsoLayoutEffect(() => { const el = measureRef.current if (!el || !queue.length || !meta) return - const hs = Array.from(el.children).map((c) => (c as HTMLElement).getBoundingClientRect().height) + const res = queue.map((q, k) => { + const c = el.children[k] as HTMLElement | undefined + return { h: c?.getBoundingClientRect().height ?? 0, l: c && q.b.t === 'tbl' ? tableLines(c, q.b) : undefined } + }) const dt = performance.now() - renderStart const id = setTimeout(() => { queue.forEach((q, k) => { - st.heights.set(q.b, hs[k] ?? 0) + st.heights.set(q.b, res[k].h) + if (res[k].l) st.lines.set(q.b, res[k].l!) + else st.lines.delete(q.b) st.dirty.delete(q.b) }) if (tailEnd > st.frontier) st.frontier = tailEnd @@ -190,7 +197,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp }) const pages = useMemo( - () => paginate(st.blocks, st.heights, Math.min(st.frontier, total), availPx, cols, (meta?.final && meta.sectKind) || 'nextPage'), + () => paginate(st.blocks, st.heights, Math.min(st.frontier, total), availPx, cols, (meta?.final && meta.sectKind) || 'nextPage', st.lines), // eslint-disable-next-line react-hooks/exhaustive-deps [version, availPx, total, cols, meta?.final, meta?.sectKind], ) @@ -221,7 +228,16 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const pinned = new Set(domSel) const lastSel = isEditing ? editor.input.lastSel : null const caretBi = lastSel ? Number(lastSel.f.pa.split('.')[0]) : -1 - for (const bi of lastSel ? [Number(lastSel.a.pa.split('.')[0]), caretBi] : []) pinned.add(pages.findIndex((p) => bi >= p.start && bi < p.end)) + /** the page showing a place: of a block split across pages, the one holding that line / row */ + const pageOfPos = (pa: string, o = 0) => { + const [bi, ri] = pa.split('.').map(Number) + const [a, b] = pagesOf(pages, bi) + if (a === b) return a + if (ri === undefined) return pageAt(pages, bi, o, st.lines.get(st.blocks[bi])) + for (let pi = b; pi > a; pi--) if (ri >= pieceOf(pages[pi], bi).from) return pi + return a + } + for (const p of lastSel ? [lastSel.a, lastSel.f] : []) pinned.add(pageOfPos(p.pa, p.o)) editor.contentW = contentW editor.defaultFont = meta?.font @@ -339,8 +355,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp } if (!editor.input.restore(sel)) { // 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) + const pi = pageOfPos(sel.f.pa, sel.f.o) if (pi >= 0 && scrollRef.current) scrollRef.current.scrollTop = Math.max(0, tops[pi] - 16) if (pi < 0 || (pi >= first && pi <= last)) editor.pendingSel = null return @@ -379,7 +394,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const m = matches[idx] const sc = scrollRef.current if (!m || !sc) return - const pi = pages.findIndex((p) => m.bi >= p.start && m.bi < p.end) + const pi = pageOfPos(m.pa, m.a) if (pi >= 0) sc.scrollTop = Math.max(0, tops[pi] - 16) setFind((f) => ({ ...f, idx })) requestAnimationFrame(() => @@ -447,7 +462,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const tall = h > pageH return (
- +
) }), @@ -695,8 +710,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const place = editor.commentPlaces().get(id) const sc = scrollRef.current if (!place || !sc) return - const bi = Number(place.pa.split('.')[0]) - const pi = pages.findIndex((p) => bi >= p.start && bi < p.end) + const pi = pageOfPos(place.pa, place.o) if (pi < 0) return const show = () => { const el = pagesRef.current?.querySelector(`[data-cm~="${CSS.escape(id)}"]`) @@ -765,7 +779,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const activeHeading = headings.reduce((acc, h, i) => (h.bi <= Math.max(topBlock, caretBi) ? i : acc), -1) const gotoBlock = (bi: number) => { const sc = scrollRef.current - const pi = pages.findIndex((p) => bi >= p.start && bi < p.end) + const pi = pagesOf(pages, bi)[0] if (!sc || pi < 0) return sc.scrollTop = Math.max(0, tops[pi] - 16) requestAnimationFrame(() => @@ -806,8 +820,10 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp spellCheck={false} onMouseDown={(e) => { if (!isEditing) return - // clicking a picture selects it (resize handles, image tools) const t = e.target as HTMLElement + // a copy of a table's header rows on a following page shows them, the rows themselves are edited on the first + if (t.closest('.de-head-copy')) return void e.preventDefault() + // clicking a picture selects it (resize handles, image tools) const obj = t.tagName === 'IMG' ? t.closest('[data-obj]') : null const pos = obj && pagesRef.current ? posFromDom(pagesRef.current, obj, 0) : null if (pos) { @@ -851,6 +867,8 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp editing={isEditing} colResize={colResize} onHF={isEditing && done ? openHF : undefined} + lines={st.lines} + avail={availPx} /> ), )} @@ -955,9 +973,12 @@ interface PageViewProps { colResize?: RenderCtx['colResize'] /** editing: a double click on the header / footer area edits it */ onHF?: (k: HFKind) => void + /** where the blocks' lines / rows are, and the height of a page's text (px) */ + lines: WeakMap + avail: number } -function PageView({ index, count, slice, blocks, meta, page, top, left, height, zoom, client, docStyle, editing, colResize, onHF }: PageViewProps) { +function PageView({ index, count, slice, blocks, meta, page, top, left, height, zoom, client, docStyle, editing, colResize, onHF, lines, avail }: PageViewProps) { const ctx = useMemo( () => ({ client, page: index, pages: count, measuring: false, editable: editing, colResize: editing ? colResize : undefined }), [client, index, count, editing, colResize], @@ -965,19 +986,34 @@ function PageView({ index, count, slice, blocks, meta, page, top, left, height, const hfCtx = useMemo(() => ({ ...ctx, editable: false }), [ctx]) // the first page's, the even pages' (when the file has different odd and even ones) or the default const { header, footer, hk, fk } = pageHF(meta ?? undefined, index) - const items = [] - for (let i = slice.start; i < slice.end; i++) { - const b = blocks[i] - items.push( - , - ) - } + // each column's blocks; a block split across pages (or columns) shows the lines / rows it has here + const columns = columnsOf(slice).map((c) => { + const items = [] + for (let i = c.start; i < c.end; i++) { + const b = blocks[i] + let { from, to }: { from?: number; to?: number } = pieceOf(c, i) + let head: number | undefined + if (b.t === 'tbl' && (from || to !== undefined)) head = from ? headOf(lines.get(b), avail) : undefined + else from = to = undefined + items.push( + , + ) + } + return items + }) + const nCols = page.cols && page.cols > 1 ? page.cols : 1 + const gap = nCols > 1 ? (page.colGap ?? 36) : 0 + const colW = (page.w - page.ml - page.mr - gap * (nCols - 1)) / nCols return (
@@ -995,16 +1031,16 @@ function PageView({ index, count, slice, blocks, meta, page, top, left, height,
)}
1 ? 'de-page-cols' : undefined} - style={{ - position: 'absolute', - top: `${page.mt}pt`, - left: `${page.ml}pt`, - width: `${page.w - page.ml - page.mr}pt`, - ...(page.cols && page.cols > 1 ? { columnCount: page.cols, columnGap: `${page.colGap ?? 36}pt`, columnFill: 'auto', height: `${page.h - page.mt - page.mb}pt` } : {}), - }} + className={nCols > 1 ? 'de-page-cols' : undefined} + style={{ position: 'absolute', top: `${page.mt}pt`, left: `${page.ml}pt`, width: `${page.w - page.ml - page.mr}pt`, ...(nCols > 1 ? { display: 'flex', columnGap: `${gap}pt` } : {}) }} > - {items} + {nCols > 1 + ? columns.map((items, c) => ( +
+ {items} +
+ )) + : columns[0]}
{footer && (
onHF(fk))}> diff --git a/src/react/docx/measure.ts b/src/react/docx/measure.ts new file mode 100644 index 0000000..7fe3d74 --- /dev/null +++ b/src/react/docx/measure.ts @@ -0,0 +1,33 @@ +/** + * What the measure pass reads of a rendered block beyond its height: where its rows (a table) or lines (a paragraph) + * are, so that pagination can cut it between two of them. + */ +import type { Table } from '../../core/docx/types' +import type { Lines } from './paginate' + +/** + * The rows of a top-level table (`el`: its rendered block): their tops and the bottom of the last, the leading header + * rows, and the row boundaries a merged cell spans when what it holds would not fit above them. + */ +export function tableLines(el: HTMLElement, t: Table): Lines | undefined { + const trs = Array.from(el.querySelector('table')?.tBodies[0]?.rows ?? []) + if (!trs.length || trs.length !== t.rows.length) return undefined + const top = el.getBoundingClientRect().top + const ys = trs.map((tr) => tr.getBoundingClientRect().top - top) + ys.push(trs[trs.length - 1].getBoundingClientRect().bottom - top) + let head = 0 + while (head < t.rows.length && t.rows[head].header) head++ + const keep = new Set() + trs.forEach((tr, r) => { + for (const td of Array.from(tr.cells)) { + if (td.rowSpan <= 1) continue + // a merged cell going on on the next page keeps what it holds above the break + const kids = td.children + const cs = getComputedStyle(td) + let need = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom) + if (kids.length) need += kids[kids.length - 1].getBoundingClientRect().bottom - kids[0].getBoundingClientRect().top + for (let b = r + 1; b < Math.min(r + td.rowSpan, trs.length); b++) if (ys[b] - ys[r] < need - 0.5) keep.add(b) + } + }) + return { ys, head: head < t.rows.length ? head : 0, keep: keep.size ? [...keep] : undefined } +} diff --git a/src/react/docx/paginate.ts b/src/react/docx/paginate.ts index 5d9c20b..36505b2 100644 --- a/src/react/docx/paginate.ts +++ b/src/react/docx/paginate.ts @@ -44,6 +44,12 @@ export interface PageSlice { const EPS = 0.01 +/** the header rows a table repeats at the top of the pages it goes on on: none when they leave no room for a row */ +export function headOf(l: Lines | undefined, avail: number): number { + const n = l ? l.ys.length - 1 : 0 + return l?.head && l.head < n && l.ys[l.head] - l.ys[0] < avail ? l.head : 0 +} + /** the lines / rows a block is cut into: its measured lines, or one unit as tall as the block */ function unitsOf(h: number, l: Lines | undefined): { ys: number[]; n: number } { if (l && l.ys.length >= 2) return { ys: l.ys, n: l.ys.length - 1 } @@ -107,8 +113,7 @@ export function paginate(blocks: Block[], heights: WeakMap, count const l = lines?.get(b) const { ys, n } = unitsOf(h, l) const table = b.t === 'tbl' - // header rows repeat when they leave room for a row below them - const head = table && l?.head && l.head < n && ys[l.head] - ys[0] < avail ? l.head : 0 + const head = table ? headOf(l, avail) : 0 const headH = head ? ys[head] - ys[0] : 0 const keep = table && l?.keep?.length ? new Set(l.keep) : undefined // the last line of a paragraph ends before its space after; a table's bottom border is part of it diff --git a/src/react/docx/render.tsx b/src/react/docx/render.tsx index 932b232..c2a0a16 100644 --- a/src/react/docx/render.tsx +++ b/src/react/docx/render.tsx @@ -1,10 +1,11 @@ import { memo, type CSSProperties, type PointerEvent as RPointerEvent, type ReactNode } from 'react' import { cssColor } from '../../core/color' -import type { Block, Inline, Paragraph, ParaStyle, RunStyle, Table, TrackMark } from '../../core/docx/types' +import type { Block, Inline, Paragraph, ParaStyle, RunStyle, Table, TableCell, TrackMark } from '../../core/docx/types' import { safeHref } from '../../core/url' import type { DocumentClient } from '../../core/worker/client' import { useMediaUrl } from '../common/hooks' import { dict } from '../../core/dict' +import { gridOf, type GridCell } from './tables' export interface RenderCtx { client: DocumentClient @@ -239,12 +240,85 @@ function ParaView({ p, ctx, pa, sp }: { p: Paragraph; ctx: RenderCtx; pa?: strin ) } -function TableView({ t, ctx, pa }: { t: Table; ctx: RenderCtx; pa?: string }) { +const grids = new WeakMap>() +const gridCached = (t: Table) => { + let g = grids.get(t) + if (!g) grids.set(t, (g = gridOf(t))) + return g +} +const gridRows = new WeakMap() +/** the cells of each row with their grid column */ +const gridRowsOf = (t: Table) => { + let r = gridRows.get(t) + if (!r) { + const rows: GridCell[][] = t.rows.map(() => []) + for (const c of gridCached(t).cells) rows[c.ri].push(c) + gridRows.set(t, (r = rows)) + } + return r +} + +/** + * A table, or the rows [from, to) of one split across pages. A part after the first starts with copies of the header + * rows (`head`): display only, not editable, not addressed. A merged cell cut by the page end is cut too: its content + * stays on the page it starts on, an empty cell of the same look goes on below. + */ +function TableView({ t, ctx, pa, from = 0, to, head = 0 }: { t: Table; ctx: RenderCtx; pa?: string; from?: number; to?: number; head?: number }) { const total = t.cols.reduce((a, b) => a + b, 0) const style: CSSProperties = { width: total ? `${total}pt` : '100%' } if (t.align === 'center') style.margin = '0 auto' else if (t.align === 'right') style.marginLeft = 'auto' else if (t.indL) style.marginLeft = `${t.indL}pt` + const end = Math.min(to ?? t.rows.length, t.rows.length) + const cut = from > 0 || end < t.rows.length + const cellView = (c: TableCell, ri: number, ci: number, rowSpan: number, copy: boolean, rest = false) => ( + 1 ? c.colSpan : undefined} + rowSpan={rowSpan > 1 ? rowSpan : undefined} + contentEditable={rest && ctx.editable ? false : undefined} + style={{ + borderTop: c.borders.t, + borderRight: c.borders.r, + borderBottom: c.borders.b, + borderLeft: c.borders.l, + background: cssColor(c.shd), + verticalAlign: c.vAlign, + padding: `${c.pad[0]}pt ${c.pad[1]}pt ${c.pad[2]}pt ${c.pad[3]}pt`, + }} + > + {!rest && + c.blocks.map((b, i) => ( + + ))} + + ) + /** row `ri`, its merged cells cut at row `limit` */ + const rowView = (ri: number, limit: number, copy: boolean) => { + const row = t.rows[ri] + let cells: ReactNode[] + if (!cut) cells = row.cells.map((c, ci) => cellView(c, ri, ci, c.rowSpan, false)) + else { + const at: { g: number; node: ReactNode }[] = [] + for (const gc of gridRowsOf(t)[ri]) at.push({ g: gc.g, node: cellView(gc.cell, ri, gc.ci, Math.min(gc.cell.rowSpan, limit - ri), copy) }) + // merged cells from the page before go on here, empty + if (!copy && ri === from) + for (const gc of gridCached(t).cells) if (gc.ri < from && gc.ri + gc.cell.rowSpan > from) at.push({ g: gc.g, node: cellView(gc.cell, ri, gc.ci, Math.min(gc.ri + gc.cell.rowSpan, limit) - ri, false, true) }) + cells = at.sort((a, b) => a.g - b.g).map((x) => x.node) + } + return ( + + {cells} + + ) + } const resize = ctx.colResize && pa !== undefined && !pa.includes('.') && total > 0 ? ctx.colResize : undefined const drag = (i: number) => (e: RPointerEvent) => { const tbl = (e.currentTarget.parentElement as HTMLElement).querySelector('table') @@ -295,37 +369,8 @@ function TableView({ t, ctx, pa }: { t: Table; ctx: RenderCtx; pa?: string }) { )} - {t.rows.map((row, ri) => ( - - {row.cells.map((c, ci) => ( - 1 ? c.colSpan : undefined} - rowSpan={c.rowSpan > 1 ? c.rowSpan : undefined} - style={{ - borderTop: c.borders.t, - borderRight: c.borders.r, - borderBottom: c.borders.b, - borderLeft: c.borders.l, - background: cssColor(c.shd), - verticalAlign: c.vAlign, - padding: `${c.pad[0]}pt ${c.pad[1]}pt ${c.pad[2]}pt ${c.pad[3]}pt`, - }} - > - {c.blocks.map((b, i) => ( - - ))} - - ))} - - ))} + {from > 0 && Array.from({ length: Math.min(head, from) }, (_, ri) => rowView(ri, head, true))} + {Array.from({ length: end - from }, (_, k) => rowView(from + k, end, false))} ) @@ -346,16 +391,24 @@ export interface BlockViewProps { pa?: string sp?: Spacing nested?: boolean + /** + * A part of a block split across pages: the characters [from, to) of a paragraph, the rows [from, to) of a table; + * to undefined: to its end + */ + from?: number + to?: number + /** a table part after the first: its header rows shown again above it */ + head?: number } -export const BlockView = memo(function BlockView({ block, ctx, pa, sp = '', nested }: BlockViewProps) { +export const BlockView = memo(function BlockView({ block, ctx, pa, sp = '', nested, from, to, head }: BlockViewProps) { switch (block.t) { case 'p': return case 'tbl': return (
- +
) default: diff --git a/src/react/styles.css b/src/react/styles.css index 151703f..e5c9d47 100644 --- a/src/react/styles.css +++ b/src/react/styles.css @@ -1228,7 +1228,6 @@ .de-ps-radio input { width: auto; padding: 0; margin: 0; } .de-ps-preset { font-weight: 400; font-size: 12px; } .de-ps select, .de-hfd select { padding: 6px 8px; border: 1px solid var(--de-input-border); border-radius: var(--de-radius); background: var(--de-input-bg); color: var(--de-text); font: inherit; } -.de-page-cols > * { break-inside: avoid; } .de-ps-bad { color: var(--de-danger); } .de-dialog-btns .de-btn:disabled { opacity: 0.5; cursor: default; } .de-dialog-btns { display: flex; justify-content: flex-end; gap: 8px; margin-top: 4px; } From 918efe8bb64edf758867ca1a9689147c48f7e415 Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 12:06:38 +0700 Subject: [PATCH 4/9] feat(docx): a paragraph longer than the rest of a page goes on on the next one, split between two lines The measure pass reads where each line of a paragraph is, and for the paragraphs a page in view cuts, the offset each line starts at; the page shows the lines that fit, the next page the rest, with the same line breaks (no first-line indent or space before on the second part, the first part's last line justified when the paragraph is). Keep rules choose the cut: widow / orphan control, keep lines together, keep with next. A split paragraph is edited as one: its parts carry the offsets they hold, and the DOM <-> offset mapping goes across them (caret, selection, find highlights, comment drafts, collaborators' cursors). Arrow keys step over the page end one character; typing that moves the page end keeps the caret on the side it was typed on; edited paragraphs are measured again before the page is painted; the pages stay as they are while an input method composes. Printing waits until every cut paragraph is read. Co-Authored-By: Claude Opus 5.5 --- e2e/docx-split.spec.ts | 457 +++++++++++++++++++++++++++++++++++ src/collab/docx.ts | 9 +- src/react/docx/DocxEditor.ts | 27 ++- src/react/docx/DocxView.tsx | 213 +++++++++++----- src/react/docx/measure.ts | 109 +++++++++ src/react/docx/paginate.ts | 91 +++++-- src/react/docx/render.tsx | 43 +++- src/react/edit/input.ts | 132 +++++++++- src/react/styles.css | 3 + test/docx-paginate.test.ts | 55 ++++- 10 files changed, 1033 insertions(+), 106 deletions(-) diff --git a/e2e/docx-split.spec.ts b/e2e/docx-split.spec.ts index f240fe3..12a4bef 100644 --- a/e2e/docx-split.spec.ts +++ b/e2e/docx-split.spec.ts @@ -42,6 +42,463 @@ async function pageContent(v: Viewer, n: number) { }) } +const LOREM = 'lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'.split(' ') +const words = (n: number, seed = 0) => Array.from({ length: n }, (_, i) => LOREM[(i * 7 + seed) % LOREM.length]).join(' ') +/** `n` one-line paragraphs */ +const filler = (n: number) => Array.from({ length: n }, (_, i) => para(`Filler line ${i + 1}`)).join('') + +interface Frag { + page: number + text: string + /** px from the top / bottom of the page's text area, at zoom 1 */ + top: number + bottom: number + /** offsets in the element's text where its lines start (after the first) */ + lines: number[] + /** last line: right edge of its last non-blank character, from the text area's right edge */ + right: number +} + +/** the parts of top-level paragraph `pa` on every page, in order */ +async function fragments(v: Viewer, pa: number): Promise { + const out: Frag[] = [] + for (let k = 1; k <= (await pageCount(v)); k++) { + await showPage(v, k) + const got = await v.page.locator(`.de-page[data-page="${k}"]`).evaluate((pg, a) => { + const inner = pg.querySelector('.de-page-inner')! + const z = inner.getBoundingClientRect().height / inner.offsetHeight + const area = inner.querySelector(':scope > div[style*="position: absolute"]:not(.de-hf):not(.de-hf-zone)')!.getBoundingClientRect() + const pageBottom = pg.getBoundingClientRect().top + (792 - 72) * (4 / 3) * z + return Array.from(pg.querySelectorAll(`[data-pa="${a}"]`)).map((el) => { + const r = el.getBoundingClientRect() + const lines: number[] = [] + const range = document.createRange() + let o = 0 + let lastTop = -1 + let right = 0 + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT) + for (let t = walker.nextNode() as Text | null; t; t = walker.nextNode() as Text | null) { + for (let i = 0; i < t.length; i++, o++) { + range.setStart(t, i) + range.setEnd(t, i + 1) + const cr = range.getBoundingClientRect() + if (lastTop >= 0 && cr.top > lastTop + 2) lines.push(o) + if (lastTop < 0 || cr.top > lastTop + 2) lastTop = cr.top + if (cr.top >= lastTop - 2 && /\S/.test(t.data[i])) right = cr.right + } + } + return { text: el.textContent ?? '', top: (r.top - area.top) / z, bottom: (pageBottom - r.bottom) / z, lines, right: (area.right - right) / z } + }) + }, pa) + out.push(...got.map((g) => ({ ...g, page: k }))) + } + return out +} + +/** where the lines of `text` start when laid out whole like the paragraph's first part (its look and width) */ +async function wholeLines(v: Viewer, pa: number, text: string) { + await showPage(v, (await fragments(v, pa))[0].page) + return v.page.evaluate( + ([a, t]) => { + const f = document.querySelector(`[data-pa="${a}"]`)! + const el = f.cloneNode(false) as HTMLElement + el.removeAttribute('data-pa') + el.classList.remove('de-just') + el.style.height = '' + el.style.paddingBottom = getComputedStyle(f).paddingTop + const sp = document.createElement('span') + sp.textContent = t as string + el.append(sp) + f.parentElement!.append(el) + const lines: number[] = [] + const range = document.createRange() + const node = sp.firstChild as Text + let lastTop = -1 + for (let i = 0; i < node.length; i++) { + range.setStart(node, i) + range.setEnd(node, i + 1) + const top = range.getBoundingClientRect().top + if (lastTop >= 0 && top > lastTop + 2) lines.push(i) + if (lastTop < 0 || top > lastTop + 2) lastTop = top + } + el.remove() + return lines + }, + [pa, text] as const, + ) +} + +describe('a paragraph longer than the rest of a page', () => { + test('goes on at the top of the next page: no gap, no text lost or shown twice, its lines as when whole', async () => { + const long = words(420) + // justified, a first-line indent, space before and after + const pPr = '' + const blob = await bareDocx(filler(30) + para(long, pPr) + para('After')) + const model = (await docxBlocks(blob)).filter((b): b is Paragraph => b.t === 'p').map(paraText) + expect(model[30]).toBe(long) + const v = await open(blob) + const fr = await fragments(v, 30) + expect(fr.map((f) => f.page)).toEqual([1, 2]) + expect(fr.map((f) => f.text).join('')).toBe(long) + // the first part ends less than a line above the bottom of the text area, the second starts at its top + expect(fr[0].bottom).toBeGreaterThanOrEqual(-1) + expect(fr[0].bottom).toBeLessThan(18) + expect(Math.abs(fr[1].top)).toBeLessThan(1) + // cut at the start of a line: the space it broke at ends the first part + expect(fr[0].text.endsWith(' ')).toBe(true) + expect(fr[1].text.startsWith(' ')).toBe(false) + // justified: the last line of the first part reaches the right edge, the paragraph's last line does not + expect(Math.abs(fr[0].right)).toBeLessThan(1.5) + expect(fr[1].right).toBeGreaterThan(20) + // the same lines as the paragraph laid out whole + const whole = await wholeLines(v, 30, long) + const n0 = fr[0].text.length + expect([...fr[0].lines, n0, ...fr[1].lines.map((x) => x + n0)]).toEqual(whole) + expect(v.errors).toEqual([]) + }) + + test('line breaks inside it and a hanging indent: the same lines on both pages', async () => { + const lines = Array.from({ length: 30 }, (_, i) => `${i + 1}. ${words(14 + (i % 3) * 9, i)}`) + const text = lines.join('\n') + const blob = await bareDocx(filler(28) + para(text, '')) + const v = await open(blob) + const fr = await fragments(v, 28) + expect(fr.length).toBe(2) + expect(fr.map((f) => f.text).join('')).toBe(text) + // not cut inside a line: the first part ends with a line break or a space, the second starts with neither + expect(/[\n ]$/.test(fr[0].text)).toBe(true) + expect(/^[\n ]/.test(fr[1].text)).toBe(false) + const whole = await wholeLines(v, 28, text) + const n0 = fr[0].text.length + expect([...fr[0].lines, n0, ...fr[1].lines.map((x) => x + n0)]).toEqual(whole) + expect(v.errors).toEqual([]) + }) +}) + +/** words that occur once each: `n1q n2q …` */ +const uniq = (n: number) => Array.from({ length: n }, (_, i) => `n${i + 1}q`).join(' ') + +/** the parts of paragraph `pa` rendered now (the pages around the view), in order */ +const parts = (v: Viewer, pa: number) => + v.page.evaluate( + (a) => + Array.from(document.querySelectorAll(`.de-pages [data-pa="${a}"]`)).map((el) => ({ + text: el.textContent ?? '', + page: Number(el.closest('.de-page')!.dataset.page), + from: Number(el.dataset.from ?? 0), + })), + pa, + ) + +/** sets the DOM selection in parts of paragraph `pa`: [part, offset in its text ('end': its end)] for anchor and focus */ +async function setSel(v: Viewer, pa: number, a: [number, number | 'end'], f = a) { + await v.page.evaluate( + ([p, x, y]) => { + const els = Array.from(document.querySelectorAll(`.de-pages [data-pa="${p}"]`)) + const at = ([k, o]: readonly [number, number | 'end']): [Node, number] => { + const texts: Text[] = [] + const w = document.createTreeWalker(els[k], NodeFilter.SHOW_TEXT) + for (let t = w.nextNode(); t; t = w.nextNode()) texts.push(t as Text) + let rem = o === 'end' ? texts.reduce((n, t) => n + t.length, 0) : o + for (const t of texts) { + if (rem <= t.length) return [t, rem] + rem -= t.length + } + return [texts[texts.length - 1], texts[texts.length - 1].length] + } + document.querySelector('.de-pages')!.focus() + const [an, ao] = at(x) + const [fn, fo] = at(y) + getSelection()!.setBaseAndExtent(an, ao, fn, fo) + }, + [pa, a, f] as const, + ) + await v.page.waitForTimeout(150) +} + +/** where the caret is: its page, and its offset in paragraph `pa` (-1: not in it) */ +const caretAt = (v: Viewer, pa: number) => + v.page.evaluate((a) => { + const s = getSelection()! + const n = s.focusNode! + const el = (n.nodeType === 1 ? (n as Element) : n.parentElement)!.closest('[data-pa]') + const page = Number(el?.closest('.de-page')?.dataset.page ?? -1) + if (!el || el.dataset.pa !== String(a)) return { page, o: -1 } + const r = document.createRange() + r.setStart(el, 0) + r.setEnd(n, s.focusOffset) + return { page, o: Number(el.dataset.from ?? 0) + r.toString().length } + }, pa) + +const joined = async (v: Viewer, pa: number) => (await parts(v, pa)).map((p) => p.text).join('') +const savedText = async (v: Viewer, k: number) => paraText((await docxBlocks((await v.save()).bytes)).filter((b): b is Paragraph => b.t === 'p')[k]) + +describe('editing a paragraph split across pages', () => { + const long = uniq(420) + const doc = () => bareDocx(filler(30) + para(long) + para('After')) + + test('typing in its second part, and at the end of its first until the page cut moves: the caret stays with the typing', async () => { + const v = await open(doc(), 0.5) + let ps = await parts(v, 30) + expect(ps.map((p) => p.page)).toEqual([1, 2]) + const cut = ps[1].from + // after the first word of the second part + const w = ps[1].text.split(' ')[0] + await setSel(v, 30, [1, w.length]) + await v.page.keyboard.type('X') + let text = long.slice(0, cut + w.length) + 'X' + long.slice(cut + w.length) + expect(await joined(v, 30)).toBe(text) + expect(await caretAt(v, 30)).toEqual({ page: 2, o: cut + w.length + 1 }) + + // a click right of the last line of the first part: the caret at its end, on page 1 + const end = await v.page.evaluate(() => { + const el = document.querySelector('.de-pages [data-pa="30"]')! + const r = document.createRange() + r.selectNodeContents(el) + const rects = r.getClientRects() + const last = rects[rects.length - 1] + return { x: el.getBoundingClientRect().right - 2, y: last.top + last.height / 2 } + }) + await v.page.mouse.click(end.x, end.y) + await v.page.waitForTimeout(150) + expect(await caretAt(v, 30)).toEqual({ page: 1, o: cut }) + // typing there: text that does not fit the last line of the page starts the next page, the caret with it + await v.page.keyboard.type('abc ') + text = text.slice(0, cut) + 'abc ' + text.slice(cut) + ps = await parts(v, 30) + expect(ps.map((p) => p.text).join('')).toBe(text) + expect(await caretAt(v, 30)).toEqual({ page: ps[1].from <= cut ? 2 : 1, o: cut + 4 }) + + // typing inside the last line of the page: the words after the caret go on to the next page, then the word typed + // does not fit either and goes there too, with the caret; the page cut moves back as the line fills up + ps = await parts(v, 30) + const lastSpace = ps[0].text.trimEnd().lastIndexOf(' ') + let o = lastSpace + await setSel(v, 30, [0, o]) + const cuts = new Set() + for (let k = 0; k < 40; k++) { + await v.page.keyboard.type('x') + text = text.slice(0, o) + 'x' + text.slice(o) + o++ + ps = await parts(v, 30) + expect(ps.map((p) => p.text).join('')).toBe(text) + const c = await caretAt(v, 30) + expect(c.o).toBe(o) + // the caret is on the page of the part that holds it + expect(c.page).toBe(o > ps[1].from ? 2 : 1) + cuts.add(ps[1].from) + } + expect(cuts.size).toBeGreaterThan(1) + expect((await caretAt(v, 30)).page).toBe(2) + // the caret stayed where the typing is + await v.page.keyboard.type('Y') + text = text.slice(0, o) + 'Y' + text.slice(o) + expect(await joined(v, 30)).toBe(text) + expect(await savedText(v, 30)).toBe(text) + expect(v.errors).toEqual([]) + }) + + test('Backspace at the end of the first part joins two words: the joined word goes to the next page, the caret too', async () => { + const v = await open(doc(), 0.5) + const ps = await parts(v, 30) + const cut = ps[1].from + await setSel(v, 30, [0, 'end']) + expect(await caretAt(v, 30)).toEqual({ page: 1, o: cut }) + await v.page.keyboard.press('Backspace') + await v.page.waitForTimeout(150) + const after = await parts(v, 30) + expect(after.map((p) => p.text).join('')).toBe(long.slice(0, cut - 1) + long.slice(cut)) + // the word before the cut and the one after it are one word now, too long for the end of the line + expect(after[1].from).toBeLessThan(cut - 1) + expect(await caretAt(v, 30)).toEqual({ page: 2, o: cut - 1 }) + expect(v.errors).toEqual([]) + }) + + test('a selection over the page cut is deleted, and undone', async () => { + const v = await open(doc(), 0.5) + const ps = await parts(v, 30) + const cut = ps[1].from + const back = ps[0].text.trimEnd().split(' ').slice(-3).join(' ').length + 1 + await setSel(v, 30, [0, ps[0].text.length - back], [1, 7]) + await v.page.keyboard.press('Backspace') + await v.page.waitForTimeout(200) + const gone = long.slice(0, cut - back) + long.slice(cut + 7) + expect(await joined(v, 30)).toBe(gone) + expect((await caretAt(v, 30)).o).toBe(cut - back) + await v.page.keyboard.press('Control+z') + await v.page.waitForTimeout(200) + expect(await joined(v, 30)).toBe(long) + expect(await savedText(v, 30)).toBe(long) + expect(v.errors).toEqual([]) + }) + + test('arrow keys over the page cut move one character, the caret on the page of its text', async () => { + const v = await open(doc(), 0.5) + let ps = await parts(v, 30) + const cut = ps[1].from + // ← at the start of the second part: before the last character of the first (the space the line broke at) + await setSel(v, 30, [1, 0]) + expect(await caretAt(v, 30)).toEqual({ page: 2, o: cut }) + await v.page.keyboard.press('ArrowLeft') + expect(await caretAt(v, 30)).toEqual({ page: 1, o: cut - 1 }) + await v.page.keyboard.press('ArrowRight') + expect(await caretAt(v, 30)).toEqual({ page: 1, o: cut }) + // → at the end of the first part: after the first character of the second + await v.page.keyboard.press('ArrowRight') + expect(await caretAt(v, 30)).toEqual({ page: 2, o: cut + 1 }) + await v.page.keyboard.type('R') + let text = long.slice(0, cut + 1) + 'R' + long.slice(cut + 1) + expect(await joined(v, 30)).toBe(text) + // Shift+← from there: the selection grows back over the cut, one character a key; typing replaces it + for (let k = 0; k < 3; k++) await v.page.keyboard.press('Shift+ArrowLeft') + await v.page.keyboard.type('K') + text = text.slice(0, cut - 1) + 'K' + text.slice(cut + 2) + expect(await joined(v, 30)).toBe(text) + // ↓ from the last line of the first part: the first line of the second; ↑ back + ps = await parts(v, 30) + await setSel(v, 30, [0, ps[0].text.length - 3]) + await v.page.keyboard.press('ArrowDown') + const down = await caretAt(v, 30) + expect(down.page).toBe(2) + expect(down.o).toBeGreaterThanOrEqual(ps[1].from) + await v.page.keyboard.press('ArrowUp') + expect((await caretAt(v, 30)).page).toBe(1) + text = await joined(v, 30) + expect(await savedText(v, 30)).toBe(text) + expect(v.errors).toEqual([]) + }) + + test('find: a phrase over the page cut is found once, highlighted on both pages; an input method composes at the cut', async () => { + const v = await open(doc(), 0.5) + const ps = await parts(v, 30) + const cut = ps[1].from + const phrase = `${ps[0].text.trim().split(' ').pop()} ${ps[1].text.split(' ')[0]}` + await setSel(v, 30, [0, 0]) + await v.page.keyboard.press('Control+f') + await v.page.locator('.de-find input').first().fill(phrase) + await v.page.waitForTimeout(300) + expect(await v.page.locator('.de-find-count').innerText()).toBe('1 / 1') + const hl = await v.page.evaluate(() => { + const reg = (CSS as unknown as { highlights: Map> }).highlights + const h = reg.get('de-find-cur') ?? reg.get('de-find') + return h ? [...h].map((r) => ({ text: r.toString(), page: (r.startContainer.parentElement!.closest('.de-page') as HTMLElement).dataset.page })) : [] + }) + expect(hl.map((r) => r.page)).toEqual(['1', '2']) + expect(hl.map((r) => r.text).join('')).toBe(phrase) + await v.page.keyboard.press('Escape') + + // an input method composing at the end of the first part + await setSel(v, 30, [0, 'end']) + const cdp = await v.ctx.newCDPSession(v.page) + await cdp.send('Input.imeSetComposition', { text: 'd', selectionStart: 1, selectionEnd: 1 }) + await cdp.send('Input.imeSetComposition', { text: 'đ', selectionStart: 1, selectionEnd: 1 }) + await cdp.send('Input.insertText', { text: 'đ' }) + await v.page.waitForTimeout(200) + await v.page.keyboard.type('x') + await v.page.waitForTimeout(200) + const text = long.slice(0, cut) + 'đx' + long.slice(cut) + expect(await joined(v, 30)).toBe(text) + expect(await savedText(v, 30)).toBe(text) + expect(v.errors).toEqual([]) + }) +}) + +describe('print', () => { + test('the printed pages are the pages shown: a paragraph and a table split the same way, nothing taller than the paper', async () => { + const long = words(420) + const rows = [['Head A', 'Head B'], ...Array.from({ length: 70 }, (_, i) => [`row ${i + 1} a`, `row ${i + 1} b`])] + const v = await open(bareDocx(filler(30) + para(long) + table(rows, { header: 1 }) + para('The end'))) + const shown = await pageCount(v) + await v.page.evaluate(() => { + ;(window as any).__printed = null + new MutationObserver((ms) => { + for (const m of ms) + for (const n of m.addedNodes) { + if ((n as HTMLElement).tagName !== 'IFRAME') continue + const w = (n as HTMLIFrameElement).contentWindow! + w.print = () => { + const d = w.document + ;(window as any).__printed = { + pages: d.querySelectorAll('.de-print-page').length, + tall: d.querySelectorAll('.de-print-tall').length, + parts: [...d.querySelectorAll('[data-pa="30"]')].map((el) => el.textContent), + copies: d.querySelectorAll('tr.de-head-copy').length, + tablePages: [...d.querySelectorAll('.de-print-page')].filter((pg) => pg.querySelector('tr')).length, + rows: [...d.querySelectorAll('tr:not(.de-head-copy)')].map((tr) => (tr as HTMLElement).innerText.replace(/\s+/g, ' ').trim()), + } + } + w.document.execCommand = () => false + } + }).observe(document.body, { childList: true }) + }) + await v.page.keyboard.press('Control+p') + await v.page.waitForFunction(() => (window as any).__printed, null, { timeout: 30_000 }) + const p = await v.page.evaluate(() => (window as any).__printed) + expect(p.pages).toBe(shown) + expect(p.tall).toBe(0) + expect(p.parts.length).toBe(2) + expect(p.parts.join('')).toBe(long) + expect(p.tablePages).toBeGreaterThan(1) + expect(p.copies).toBe(p.tablePages - 1) + expect(p.rows).toEqual(rows.map((r) => r.join(' '))) + expect(v.errors).toEqual([]) + }) +}) + +describe('keep rules', () => { + // every line 12 pt (16 px): the text area of a letter page holds 54 of them + const EXACT = '' + const nLines = (n: number, pPr = '') => para(Array.from({ length: n }, (_, i) => `line ${i + 1}`).join('\n'), pPr) + /** page and line count of each part of paragraph `pa` */ + const layout = async (body: string, pa: number, pPrDefault = EXACT) => { + const v = await open(bareDocx(body, { pPrDefault }), 0.5) + const ps = await parts(v, pa) + expect(v.errors).toEqual([]) + return ps.map((p) => [p.page, p.text.replace(/\n$/, '').split('\n').length]) + } + + test('widow / orphan control: no first or last line alone on a page; off when the document says so', async () => { + // room for 1 line: the paragraph starts the next page + expect(await layout(filler(53) + nLines(6), 53)).toEqual([[2, 6]]) + // room for 5 of 6: 4 stay, 2 go on + expect(await layout(filler(49) + nLines(6), 49)).toEqual([ + [1, 4], + [2, 2], + ]) + const off = EXACT + '' + expect(await layout(filler(53) + nLines(6), 53, off)).toEqual([ + [1, 1], + [2, 5], + ]) + expect(await layout(filler(49) + nLines(6), 49, off)).toEqual([ + [1, 5], + [2, 1], + ]) + }) + + test('keep lines together: the paragraph starts the next page', async () => { + expect(await layout(filler(50) + nLines(6, ''), 50)).toEqual([[2, 6]]) + expect(await layout(filler(50) + nLines(6), 50)).toEqual([ + [1, 4], + [2, 2], + ]) + }) + + test('keep with next: a heading stays with the first lines of its paragraph, a caption with its table', async () => { + const heading = (t: string) => para(t, '') + // room for the heading and 2 lines: they stay + expect(await layout(filler(51) + heading('Heading') + nLines(6), 51)).toEqual([[1, 1]]) + // room for the heading and 1 line: the heading goes with the paragraph to the next page + expect(await layout(filler(52) + heading('Heading') + nLines(6), 52)).toEqual([[2, 1]]) + // two headings in a row: both go + expect(await layout(filler(51) + heading('Part') + heading('Heading') + nLines(6), 51)).toEqual([[2, 1]]) + // a caption kept with the table below it + const rows = Array.from({ length: 8 }, (_, i) => [`r${i + 1}`, 'x']) + expect(await layout(filler(52) + heading('Caption') + table(rows, { header: 1 }), 52)).toEqual([[2, 1]]) + expect(await layout(filler(52) + para('Caption') + table(rows, { header: 1 }), 52)).toEqual([[1, 1]]) + }) +}) + describe('a table longer than a page', () => { test('a merged cell cut by the page end: its text stays on the first page, an empty cell goes on below', async () => { const body = [['Head A', 'Head B'], ...Array.from({ length: 70 }, (_, i) => [i === 0 ? 'Group' : '', `row ${i + 1} b`])] diff --git a/src/collab/docx.ts b/src/collab/docx.ts index 1fce1a2..51f05e6 100644 --- a/src/collab/docx.ts +++ b/src/collab/docx.ts @@ -14,7 +14,7 @@ import type { Block, HFSetResult, Inline, PageSetResult, Paragraph, StyleInfo } import type { DocumentClient } from '../core/worker/client' import type { Methods } from '../core/worker/protocol' import type { DocState, DocxCommit, DocxEditor } from '../react/docx/DocxEditor' -import { domFromPos } from '../react/edit/input' +import { domFromPos, paraRanges } from '../react/edit/input' import { normalize, plen, runsText, splitRuns, type Pos, type RRun, type Sel } from '../react/edit/rich' import { watchHost } from './hosts' import type { Adapter, ApplyResult } from './session' @@ -753,10 +753,13 @@ export class DocxCollab implements Adapter { } const sel: DOMRect[] = [] const ad = domFromPos(pages, a) - if (ad && fd && (a.pa !== f.pa || a.o !== f.o)) { + if (a.pa === f.pa && a.o !== f.o) { + // one paragraph, maybe over the end of a page: only its parts, not what is between them + for (const r of paraRanges(pages, a.pa, Math.min(a.o, f.o), Math.max(a.o, f.o))) for (const x of Array.from(r.getClientRects())) if (x.width > 0.5) sel.push(x) + } else if (ad && fd && a.pa !== f.pa) { const r = document.createRange() try { - const forward = this.ed.cmp(a.pa, f.pa) < 0 || (a.pa === f.pa && a.o < f.o) + const forward = this.ed.cmp(a.pa, f.pa) < 0 if (forward) { r.setStart(ad[0], ad[1]) r.setEnd(fd[0], fd[1]) diff --git a/src/react/docx/DocxEditor.ts b/src/react/docx/DocxEditor.ts index 6b93c61..e51b30a 100644 --- a/src/react/docx/DocxEditor.ts +++ b/src/react/docx/DocxEditor.ts @@ -192,6 +192,18 @@ function moveSel(sel: Sel, from: string, to: string): Sel { return { a: mv(sel.a), f: mv(sel.f) } } +/** lines of a paragraph whose text went from `a` to `b`: the lines starting after the change move with the text */ +function shifted(l: Lines, a: string, b: string): Lines { + if (!l.at) return { ys: l.ys } + let pre = 0 + while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++ + let suf = 0 + while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++ + const at = l.at.map((x) => (x === undefined || x <= pre ? x : x >= a.length - suf ? x + b.length - a.length : pre)) + for (let k = 1; k < at.length; k++) if (at[k] === undefined || at[k]! <= at[k - 1]! || at[k]! >= b.length) return { ys: l.ys } + return { ys: l.ys, at } +} + /** a model change: contiguous paragraphs replaced, or top-level blocks replaced */ export type DocxCommit = { kind: 'paras'; before: Paragraph[]; next: Paragraph[] } | { kind: 'blocks'; bi: number; before: Block[]; next: Block[] } @@ -378,12 +390,13 @@ export class DocxEditor implements RichHost { /** * `next` replaces `was` on the page: measured again soon, laid out meanwhile as `was` was (its height; its rows when - * a table keeps the same rows) + * a table keeps the same rows; its lines when it is the same paragraph edited, `same`) */ - private estimate(was: Block | undefined, next: Block) { + private estimate(was: Block | undefined, next: Block, same = false) { this.st.heights.set(next, (was && this.st.heights.get(was)) ?? 0) const l = was && this.st.lines?.get(was) if (l && next.t === 'tbl' && was.t === 'tbl' && next.rows.length === was.rows.length) this.st.lines!.set(next, l) + else if (l && same && next.t === 'p' && was.t === 'p') this.st.lines!.set(next, shifted(l, runsText(was.runs as RRun[]), runsText(next.runs as RRun[]))) this.st.dirty.add(next) } @@ -429,10 +442,7 @@ export class DocxEditor implements RichHost { } // heights: estimate from what was there, remeasure soon if (!c.cell) { - next.forEach((p, i) => { - this.st.heights.set(p, this.st.heights.get(before[i] ?? before[0]) ?? 0) - this.st.dirty.add(p) - }) + next.forEach((p, i) => this.estimate(before[i] ?? before[0], p, before.length === next.length)) for (const k of [at - 1, at + next.length]) if (list[k]) this.st.dirty.add(list[k]) if (at < this.st.frontier) this.st.frontier = Math.max(0, this.st.frontier + next.length - pas.length) } @@ -692,10 +702,7 @@ export class DocxEditor implements RichHost { if (!c) return const old = c.list[c.at] this.splice(pa, 1, [p]) - if (!c.cell) { - this.st.heights.set(p, this.st.heights.get(old) ?? 0) - this.st.dirty.add(p) - } + if (!c.cell) this.estimate(old, p, true) } private applyResult(res: EditResult, sent: Set): boolean { diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index 512285e..c95694f 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -10,7 +10,7 @@ import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' 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 { domFromPos, getSel, opInsert, paraRanges, posFromDom, selPoints } from '../edit/input' import { download, Icon, pickFiles } from '../edit/Toolbar' import { runsText, type RRun } from '../edit/rich' import { DocxEditor, type CommentRange, type DocState, type FormatState } from './DocxEditor' @@ -25,7 +25,7 @@ import { mergeSource } from '../../core/plainmerge' import { docxBodyHtml, docxToHtml, docxToMarkdown, docxToText, pictureData } from '../file/text' import { BlockView, contextual, type RenderCtx } from './render' import { columnsOf, headOf, pageAt, pageHF, pagesOf, paginate, pieceOf, type Lines, type PageSlice } from './paginate' -import { tableLines } from './measure' +import { lineStarts, paraLines, tableLines } from './measure' const PX = 4 / 3 const GAP = 16 @@ -149,8 +149,12 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const contentW = (page.w - page.ml - page.mr - colGap * (cols - 1)) / cols const availPx = (page.h - page.mt - page.mb) * PX - // ---- measurement: edited blocks first, then the not-yet-measured tail (time-sliced) ---- + // ---- measurement (see below, once the pages shown are known) ---- const [batch, setBatch] = useState(40) + /** printing waits until the line starts of every paragraph a page cuts are read */ + const printWait = useRef<(() => void) | null>(null) + /** the pages are laid out again before this render is painted: what depends on where things are waits for that */ + const relayout = useRef(false) const measureRef = useRef(null) const widthKey = `${contentW}|${meta?.font}|${meta?.sz}` const lastKey = useRef(widthKey) @@ -162,45 +166,16 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp st.frontier = 0 } const total = st.blocks.length - const queue: { b: Block; i: number }[] = [] - for (const b of st.dirty) { - if (queue.length >= 50) break - const i = st.blocks.indexOf(b) - if (i < 0) st.dirty.delete(b) - else queue.push({ b, i }) - } - const tailEnd = Math.min(total, st.frontier + batch) - for (let i = st.frontier; i < tailEnd; i++) queue.push({ b: st.blocks[i], i }) - const renderStart = performance.now() - const measureCtx = useMemo(() => ({ client, page: -1, pages: 0, measuring: true, editable: false }), [client]) - - useIsoLayoutEffect(() => { - const el = measureRef.current - if (!el || !queue.length || !meta) return - const res = queue.map((q, k) => { - const c = el.children[k] as HTMLElement | undefined - return { h: c?.getBoundingClientRect().height ?? 0, l: c && q.b.t === 'tbl' ? tableLines(c, q.b) : undefined } - }) - const dt = performance.now() - renderStart - const id = setTimeout(() => { - queue.forEach((q, k) => { - st.heights.set(q.b, res[k].h) - if (res[k].l) st.lines.set(q.b, res[k].l!) - else st.lines.delete(q.b) - st.dirty.delete(q.b) - }) - if (tailEnd > st.frontier) st.frontier = tailEnd - setBatch((b) => (dt < 10 ? Math.min(b * 2, 1500) : dt > 30 ? Math.max(10, b >> 1) : b)) - bump() - }, 0) - return () => clearTimeout(id) - }) - - const pages = useMemo( + const laid = useMemo( () => paginate(st.blocks, st.heights, Math.min(st.frontier, total), availPx, cols, (meta?.final && meta.sectKind) || 'nextPage', st.lines), // eslint-disable-next-line react-hooks/exhaustive-deps [version, availPx, total, cols, meta?.final, meta?.sectKind], ) + // while an input method composes, the pages stay as they are: a paragraph cut elsewhere would be rebuilt under it + const frozen = useRef<{ pages: PageSlice[]; total: number } | null>(null) + const composing = isEditing && editor.input.isComposing + const pages = composing && frozen.current?.total === total ? frozen.current.pages : laid + if (!composing) frozen.current = { pages, total } // ---- layout ---- const pageW = page.w * PX @@ -237,7 +212,108 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp for (let pi = b; pi > a; pi--) if (ri >= pieceOf(pages[pi], bi).from) return pi return a } - for (const p of lastSel ? [lastSel.a, lastSel.f] : []) pinned.add(pageOfPos(p.pa, p.o)) + // (an offset where a page cuts a paragraph is shown at the end of one page and the start of the next) + for (const p of lastSel ? [lastSel.a, lastSel.f] : []) pinned.add(pageOfPos(p.pa, p.o)).add(pageOfPos(p.pa, Math.max(0, p.o - 1))) + /** where the pages cut the paragraphs holding the selection: the caret is put back when that changes */ + const selCuts = lastSel + ? [lastSel.a.pa, lastSel.f.pa] + .map((pa) => { + const bi = Number(pa.split('.')[0]) + const [a, b] = pagesOf(pages, bi) + const at = st.lines.get(st.blocks[bi])?.at + let sig = `${bi}` + for (let pi = a; pi >= 0 && pi < b; pi++) sig += `:${pages[pi].to === undefined ? '' : at?.[pages[pi].to!]}` + return sig + }) + .join('|') + : '' + const lastCuts = useRef(selCuts) + + // measured first: edited blocks, then the paragraphs a page shown ends in (where their lines start is read), then the + // not-yet-measured tail (time-sliced) + const queue: { b: Block; i: number; starts?: boolean }[] = [] + const queued = new Set() + const enqueue = (b: Block, i: number, starts?: boolean) => { + if (queued.has(b)) return + queued.add(b) + queue.push({ b, i, starts }) + } + for (const b of st.dirty) { + if (queue.length >= 50) break + const i = st.blocks.indexOf(b) + if (i < 0) st.dirty.delete(b) + else enqueue(b, i, true) + } + const edited = queue.length + /** the paragraphs page `pi` cuts whose line starts are not read yet */ + const unread = (pi: number, out: Map) => { + for (const c of pages[pi] ? columnsOf(pages[pi]) : []) { + for (const bi of c.end - 1 > c.start ? [c.start, c.end - 1] : [c.start]) { + const b = st.blocks[bi] + if (b?.t !== 'p') continue + const { from, to } = pieceOf(c, bi) + const at = st.lines.get(b)?.at + if ((from && at?.[from] === undefined) || (to !== undefined && at?.[to] === undefined)) out.set(b, bi) + } + } + } + const shownUnread = new Map() + for (let pi = first; pi <= last; pi++) unread(pi, shownUnread) + for (const pi of pinned) unread(pi, shownUnread) + for (const [b, i] of shownUnread) enqueue(b, i, true) + // printing: every page + const allUnread = new Map() + if (printWait.current) for (let pi = 0; pi < pages.length && allUnread.size < 200; pi++) unread(pi, allUnread) + for (const [b, i] of allUnread) enqueue(b, i, true) + const tailEnd = Math.min(total, st.frontier + batch) + for (let i = st.frontier; i < tailEnd; i++) enqueue(st.blocks[i], i) + const renderStart = performance.now() + const measureCtx = useMemo(() => ({ client, page: -1, pages: 0, measuring: true, editable: false }), [client]) + + useIsoLayoutEffect(() => { + const el = measureRef.current + if (!el || !queue.length || !meta) return + const res = queue.map((q, k) => { + const c = el.children[k] as HTMLElement | undefined + let l: Lines | undefined + if (c && q.b.t === 'tbl') l = tableLines(c, q.b) + else if (c && q.b.t === 'p') { + l = paraLines(c) + if (q.starts && l.ys.length > 2) { + const at = lineStarts(c, l.ys) + // lines that cannot be told apart: the paragraph is not cut + l = at ? { ys: l.ys, at } : { ys: [l.ys[0], l.ys[l.ys.length - 1]] } + } + } + return { h: c?.getBoundingClientRect().height ?? 0, l } + }) + const dt = performance.now() - renderStart + const save = () => { + queue.forEach((q, k) => { + st.heights.set(q.b, res[k].h) + if (res[k].l) st.lines.set(q.b, res[k].l!) + else st.lines.delete(q.b) + st.dirty.delete(q.b) + }) + if (tailEnd > st.frontier) st.frontier = tailEnd + setBatch((b) => (dt < 10 ? Math.min(b * 2, 1500) : dt > 30 ? Math.max(10, b >> 1) : b)) + bump() + } + // a page shown waits for these, and a few edited blocks (typing) are laid out again before anything is painted: no + // page shows them where they were (the caret is put back once, after that) + if (shownUnread.size || (edited > 0 && edited <= 10)) { + relayout.current = true + return void save() + } + const id = setTimeout(save, 0) + return () => clearTimeout(id) + }) + useEffect(() => { + if (!printWait.current || allUnread.size) return + const done = printWait.current + printWait.current = null + done() + }) editor.contentW = contentW editor.defaultFont = meta?.font @@ -347,10 +423,17 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp }, [editor, viewer]) // eslint-disable-line react-hooks/exhaustive-deps useIsoLayoutEffect(() => { + if (relayout.current) { + relayout.current = false + return + } + const cutsMoved = lastCuts.current !== selCuts + lastCuts.current = selCuts const sel = editor.pendingSel if (!sel || !pagesRef.current) { - // a paragraph that moved to another page took the caret with it: it goes back to where it was - if (isEditing) editor.input.repair() + // a paragraph that moved to another page took the caret with it: it goes back to where it was; so does a caret + // in a paragraph now cut elsewhere by the end of a page (its text moved from one part to the other) + if (isEditing && !editor.input.repair() && cutsMoved) editor.input.reflow() return } if (!editor.input.restore(sel)) { @@ -400,13 +483,8 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp requestAnimationFrame(() => requestAnimationFrame(() => { const root = pagesRef.current - if (!root) return - const a = domFromPos(root, { pa: m.pa, o: m.a }) - const b = domFromPos(root, { pa: m.pa, o: m.b }) - if (!a || !b) return - const r = document.createRange() - r.setStart(a[0], a[1]) - r.setEnd(b[0], b[1]) + const r = root && paraRanges(root, m.pa, m.a, m.b)[0] + if (!r) return const rect = r.getBoundingClientRect() const box = sc.getBoundingClientRect() sc.scrollTop += rect.top - box.top - box.height / 3 @@ -427,20 +505,16 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp return } const all: Range[] = [] - let curR: Range | undefined + let curR: Range[] | undefined matches.forEach((m, i) => { if (m.bi < (pages[first]?.start ?? 0) || m.bi >= (pages[last]?.end ?? 0)) return - const a = domFromPos(root, { pa: m.pa, o: m.a }) - const b = domFromPos(root, { pa: m.pa, o: m.b }) - if (!a || !b) return - const r = document.createRange() - r.setStart(a[0], a[1]) - r.setEnd(b[0], b[1]) - if (i === find.idx) curR = r - else all.push(r) + // a match over the end of a page: one range on each page + const rs = paraRanges(root, m.pa, m.a, m.b) + if (i === find.idx) curR = rs + else all.push(...rs) }) reg.set('de-find', new H(...all)) - if (curR) reg.set('de-find-cur', new H(curR)) + if (curR?.length) reg.set('de-find-cur', new H(...curR)) else reg.delete('de-find-cur') }) @@ -452,6 +526,10 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp useFileOps({ printable: async () => { if (!complete) throw new Error('The document is still loading — try again in a moment') + await new Promise((resolve) => { + printWait.current = resolve + bump() + }) return { size: `${page.w}pt ${page.h}pt`, margin: '0', @@ -761,6 +839,8 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const da = root && a && domFromPos(root, a) const df = root && f && domFromPos(root, f) if (!da || !df) return void reg.delete('de-cm-draft') + // within one paragraph, a range on each page it is on + if (a!.pa === f!.pa) return void reg.set('de-cm-draft', new H(...paraRanges(root!, a!.pa, Math.min(a!.o, f!.o), Math.max(a!.o, f!.o)))) const r = document.createRange() r.setStart(da[0], da[1]) r.setEnd(df[0], df[1]) @@ -993,8 +1073,22 @@ function PageView({ index, count, slice, blocks, meta, page, top, left, height, const b = blocks[i] let { from, to }: { from?: number; to?: number } = pieceOf(c, i) let head: number | undefined + let height: number | undefined if (b.t === 'tbl' && (from || to !== undefined)) head = from ? headOf(lines.get(b), avail) : undefined - else from = to = undefined + else if (b.t === 'p' && (from || to !== undefined)) { + // lines [from, to): the characters they hold, the height they take + const l = lines.get(b) + const a = from ? l?.at?.[from] : 0 + const z = to !== undefined ? l?.at?.[to] : undefined + if (!l || a === undefined || (to !== undefined && z === undefined)) { + // where its lines start is being read (before this is painted): the place is kept + items.push(
) + continue + } + if (to !== undefined) height = l.ys[to] - (from ? l.ys[from] : 0) + from = a + to = z + } else from = to = undefined items.push( , ) } diff --git a/src/react/docx/measure.ts b/src/react/docx/measure.ts index 7fe3d74..2a925fb 100644 --- a/src/react/docx/measure.ts +++ b/src/react/docx/measure.ts @@ -31,3 +31,112 @@ export function tableLines(el: HTMLElement, t: Table): Lines | undefined { }) return { ys, head: head < t.rows.length ? head : 0, keep: keep.size ? [...keep] : undefined } } + +/** inline boxes measured as a whole (pictures, text boxes, list markers), not by the text inside them */ +const ATOMIC = 'img, .de-tbox, .de-ph, .de-img-missing, .de-marker' + +/** + * The lines of a rendered paragraph (`el`: its box): the top of the first, the boundary between each two, the bottom + * of the last, from the top of the box (px). The text boxes are read in order: one whose middle is below the bottom of + * the line so far starts the next line; two lines meet halfway between the bottom of the one and the top of the other. + */ +export function paraLines(el: HTMLElement): Lines { + const box = el.getBoundingClientRect() + const cs = getComputedStyle(el) + const top = parseFloat(cs.paddingTop) + parseFloat(cs.borderTopWidth) + const bottom = box.height - parseFloat(cs.paddingBottom) - parseFloat(cs.borderBottomWidth) + const lines: { t: number; b: number }[] = [] + const add = (r: DOMRect) => { + if (!r.height) return + const t = r.top - box.top + const b = r.bottom - box.top + const cur = lines[lines.length - 1] + if (cur && (t + b) / 2 <= cur.b) { + cur.t = Math.min(cur.t, t) + cur.b = Math.max(cur.b, b) + } else lines.push({ t, b }) + } + const range = document.createRange() + const walk = (n: Node) => { + for (let c = n.firstChild; c; c = c.nextSibling) { + if (c.nodeType === 3) { + range.selectNodeContents(c) + for (const r of range.getClientRects()) add(r) + } else if (c.nodeType === 1) { + if ((c as Element).matches(ATOMIC)) add((c as Element).getBoundingClientRect()) + else walk(c) + } + } + } + walk(el) + const ys = [top] + for (let i = 1; i < lines.length; i++) { + const y = (lines[i - 1].b + lines[i].t) / 2 + // lines that overlap that much are taken as one + if (y > ys[ys.length - 1] + 0.5 && y < bottom - 0.5) ys.push(y) + } + ys.push(Math.max(bottom, top)) + return { ys } +} + +/** + * Where each line of a rendered paragraph starts (offsets in the paragraph; `ys` from `paraLines`): for each boundary, + * the first character whose middle is below it (a binary search). Undefined when the characters cannot be told apart + * that way. + */ +export function lineStarts(el: HTMLElement, ys: number[]): number[] | undefined { + const top = el.getBoundingClientRect().top + // the paragraph's runs, each one element: an object, or a text node + const runs: { o: number; n: number; el: HTMLElement; text?: Text }[] = [] + for (const sp of el.querySelectorAll(':scope > [data-o], :scope > a > [data-o]')) { + if (sp.hasAttribute('data-empty')) continue + const o = Number(sp.dataset.o) + if (sp.hasAttribute('data-obj')) runs.push({ o, n: 1, el: sp }) + else if (sp.childNodes.length === 1 && sp.firstChild!.nodeType === 3) runs.push({ o, n: (sp.firstChild as Text).length, el: sp, text: sp.firstChild as Text }) + else return undefined + } + if (!runs.length) return undefined + const len = runs[runs.length - 1].o + runs[runs.length - 1].n + const range = document.createRange() + const runAt = (o: number) => { + let lo = 0 + let hi = runs.length - 1 + while (lo < hi) { + const m = (lo + hi + 1) >> 1 + if (runs[m].o <= o) lo = m + else hi = m - 1 + } + return runs[lo] + } + /** the middle of the character at `o`, from the top of the paragraph */ + const mid = (o: number) => { + const r = runAt(o) + let rect: DOMRect + if (!r.text) rect = r.el.getBoundingClientRect() + else { + let i = Math.min(o - r.o, r.n - 1) + // the second half of a surrogate pair is where the first is + if (i > 0 && (r.text.data.charCodeAt(i) & 0xfc00) === 0xdc00) i-- + range.setStart(r.text, i) + range.setEnd(r.text, i + 1) + rect = range.getBoundingClientRect() + } + return (rect.top + rect.bottom) / 2 - top + } + const at = [0] + for (let k = 1; k < ys.length - 1; k++) { + let lo = at[k - 1] + 1 + let hi = len + while (lo < hi) { + const m = (lo + hi) >> 1 + if (mid(m) > ys[k]) hi = m + else lo = m + 1 + } + // a line break belongs to the line it ends + const r = lo < len ? runAt(lo) : undefined + if (r?.text && r.text.data[lo - r.o] === '\n') lo++ + if (lo >= len) return undefined + at.push(lo) + } + return at +} diff --git a/src/react/docx/paginate.ts b/src/react/docx/paginate.ts index 36505b2..78878eb 100644 --- a/src/react/docx/paginate.ts +++ b/src/react/docx/paginate.ts @@ -1,4 +1,4 @@ -import type { Block, DocxMeta, HFKind } from '../../core/docx/types' +import type { Block, DocxMeta, HFKind, Paragraph } from '../../core/docx/types' /** * The header and footer a page shows (`index`: 0-based) and the editable kind each is: the first page's when "different @@ -61,6 +61,7 @@ function unitsOf(h: number, l: Lines | undefined): { ys: number[]; n: number } { * between two rows, its header rows repeated at the top of the next page; a block with no line or row that fits * starts the next page, and one that does not fit an empty page either (one line or one row taller than the page) is * placed anyway: its page grows (`used` > `avail`). The space after the last paragraph of a page needs no room. + * Keep rules choose the cut: widow / orphan control, keep lines together, keep with next (see `kept`, `chain`). * With text columns (`cols` > 1) a page holds `cols` columns of `avail`, filled the same way one after the other; * `used` is the tallest. */ @@ -100,6 +101,58 @@ export function paginate(blocks: Block[], heights: WeakMap, count ;(cur.cols ??= []).push([bi, k]) } else newPage(bi, k) } + /** what pagination needs to know of a block: where it can be cut, and the paragraph's keep rules */ + const shape = (b: Block) => { + const h = heights.get(b) ?? 0 + const l = lines?.get(b) + const { ys, n } = unitsOf(h, l) + const table = b.t === 'tbl' + const head = table ? headOf(l, avail) : 0 + // the last line of a paragraph ends before its space after; a table's bottom border is part of it + return { h, ys, n, head, headH: head ? ys[head] - ys[0] : 0, keep: table && l?.keep?.length ? new Set(l.keep) : undefined, inkEnd: table ? h : ys[n], ps: b.t === 'p' ? b.ps : undefined } + } + type Shape = ReturnType + /** a cut before line / row `j` the block allows: a table below its header rows, not inside a merged cell kept whole */ + const cuts = (s: Shape, j: number) => j > 0 && j < s.n && j > s.head && !s.keep?.has(j) + /** + * the keep rules of a paragraph allow a part [k, j): it is not split when it keeps its lines together (and fits a + * page); widow / orphan control (on unless turned off) leaves neither its first nor its last line alone on a page + */ + const kept = (s: Shape, k: number, j: number) => + !s.ps || !((s.ps.keepLines && s.inkEnd <= avail + EPS) || (s.ps.widowControl !== false && ((k === 0 && j < 2) || s.n - j < 2))) + /** the height of the smallest first part of a block (whole when it cannot be cut) */ + const firstPart = (s: Shape) => { + for (let j = 1; j < s.n; j++) if (cuts(s, j) && kept(s, 0, j)) return s.ys[j] + return s.inkEnd + } + /** + * Keep with next: what block `i` needs on its page, with the paragraphs after it that keep with the next one too and + * the first part of the block after them; `end`: that block. Infinity when that would not fit a page either: such a + * chain is let go, its paragraphs are cut like the others (no page is pushed on forever). + */ + const chain = (i: number): { need: number; end: number } => { + let need = 0 + for (let m = i; m < count; m++) { + const b = blocks[m] + // a page break comes before the next block anyway + if (b.t === 'sect' || (m > i && b.t === 'p' && b.pb)) return { need: 0, end: m } + const s = shape(b) + if (m > i && !s.ps?.keepNext) { + need += firstPart(s) + return { need: need > avail + EPS ? Infinity : need, end: m } + } + need += s.h + if (need > avail + EPS) { + let end = m + 1 + while (end < count && blocks[end].t === 'p' && (blocks[end] as Paragraph).ps.keepNext) end++ + return { need: Infinity, end } + } + } + // what comes next is not measured yet + return { need: 0, end: count } + } + /** blocks before this one belong to a chain let go */ + let loose = 0 for (let i = 0; i < count; i++) { const b = blocks[i] if (b.t === 'sect') { @@ -109,16 +162,8 @@ export function paginate(blocks: Block[], heights: WeakMap, count continue } if (b.t === 'p' && b.pb && cur.end > cur.start) newPage(i, 0) - const h = heights.get(b) ?? 0 - const l = lines?.get(b) - const { ys, n } = unitsOf(h, l) - const table = b.t === 'tbl' - const head = table ? headOf(l, avail) : 0 - const headH = head ? ys[head] - ys[0] : 0 - const keep = table && l?.keep?.length ? new Set(l.keep) : undefined - // the last line of a paragraph ends before its space after; a table's bottom border is part of it - const inkEnd = table ? h : ys[n] - const canBreak = (j: number) => j > 0 && j < n && j > head && !keep?.has(j) + const s = shape(b) + const { h, ys, n, headH, inkEnd } = s const pieceH = (k: number, j: number) => (k > 0 ? headH - ys[k] : 0) + (j === n ? h : ys[j]) const pieceInk = (k: number, j: number) => (k > 0 ? headH - ys[k] : 0) + (j === n ? inkEnd : ys[j]) const place = (k: number, j: number) => { @@ -127,23 +172,39 @@ export function paginate(blocks: Block[], heights: WeakMap, count y += pieceH(k, j) ink = y - (j === n ? h - inkEnd : 0) } + /** the last cut where the part from `k` fits `room` and `ok` allows */ + const best = (k: number, room: number, ok: (j: number) => boolean) => { + let j = -1 + for (let x = k + 1; x < n && pieceInk(k, x) <= room + EPS; x++) if (ok(x)) j = x + return j + } for (let k = 0; ; ) { const room = avail - y + // a paragraph kept with the next one starts the next page (or column) when they do not fit together here + if (k === 0 && i >= loose && s.ps?.keepNext) { + const c = chain(i) + if (c.need === Infinity) loose = c.end + else if (y > 0 && c.need > room + EPS) { + advance(i, 0) + continue + } + } if (pieceInk(k, n) <= room + EPS) { place(k, n) break } // the most lines / rows that fit - let j = -1 - for (let x = k + 1; x < n && pieceInk(k, x) <= room + EPS; x++) if (canBreak(x)) j = x + let j = best(k, room, (x) => cuts(s, x) && kept(s, k, x)) if (j < 0 && y > 0) { advance(i, k) continue } - // nothing fits an empty page or column: the smallest piece there is, its page grows + // at the top of a page or column the keep rules give way; when not even one line / row fits there, the smallest + // part there is goes on it and its page grows + if (j < 0) j = best(k, room, (x) => cuts(s, x)) if (j < 0) { j = k + 1 - while (j < n && !canBreak(j)) j++ + while (j < n && !cuts(s, j)) j++ } place(k, j) if (j === n) break diff --git a/src/react/docx/render.tsx b/src/react/docx/render.tsx index c2a0a16..78a17ca 100644 --- a/src/react/docx/render.tsx +++ b/src/react/docx/render.tsx @@ -204,7 +204,12 @@ function InlineView({ x, ctx, o }: { x: Inline; ctx: RenderCtx; o: number }): Re } } -function ParaView({ p, ctx, pa, sp }: { p: Paragraph; ctx: RenderCtx; pa?: string; sp: Spacing }) { +/** + * A paragraph, or the characters [from, to) of one split across pages: lines as the whole paragraph has them there. + * A part after the first has no first-line indent, no space or border above; one before the last no space or border + * below, its height the measured one (`height`, px), and its last line justified when the paragraph is. + */ +function ParaView({ p, ctx, pa, sp, from = 0, to, height }: { p: Paragraph; ctx: RenderCtx; pa?: string; sp: Spacing; from?: number; to?: number; height?: number }) { const hang = p.ps.indFirst && p.ps.indFirst < 0 ? -p.ps.indFirst : 0 const visible = p.runs.length > 0 const style = paraCss(p.ps, sp) @@ -212,16 +217,34 @@ function ParaView({ p, ctx, pa, sp }: { p: Paragraph; ctx: RenderCtx; pa?: strin style.fontSize = pt(p.markSz) if (p.markFont) style.fontFamily = p.markFont } + const first = from === 0 + const last = to === undefined + if (!first) style.paddingTop = style.textIndent = style.borderTop = undefined + if (!last) { + style.paddingBottom = style.borderBottom = undefined + style.boxSizing = 'border-box' + style.height = height + } const editable = ctx.editable && pa !== undefined let o = 0 - const runs = p.runs.map((x, i) => { - const node = - o += x.t === 'text' ? x.text.length : 1 - return node + const runs: ReactNode[] = [] + p.runs.forEach((x, i) => { + const n = x.t === 'text' ? x.text.length : 1 + const a = Math.max(from, o) + const b = Math.min(to ?? Infinity, o + n) + if (b > a || (n === 0 && first && last)) runs.push( o || b < o + n) ? { ...x, text: x.text.slice(a - o, b - o) } : x} ctx={ctx} o={a} />) + o += n }) return ( -
- {p.marker && ( +
+ {first && p.marker && ( {p.marker.text} {p.marker.tab && !hang ? '\t' : ''} @@ -399,12 +422,14 @@ export interface BlockViewProps { to?: number /** a table part after the first: its header rows shown again above it */ head?: number + /** a paragraph part before the last: its height (px) */ + height?: number } -export const BlockView = memo(function BlockView({ block, ctx, pa, sp = '', nested, from, to, head }: BlockViewProps) { +export const BlockView = memo(function BlockView({ block, ctx, pa, sp = '', nested, from, to, head, height }: BlockViewProps) { switch (block.t) { case 'p': - return + return case 'tbl': return (
diff --git a/src/react/edit/input.ts b/src/react/edit/input.ts index e96e69a..7590679 100644 --- a/src/react/edit/input.ts +++ b/src/react/edit/input.ts @@ -239,17 +239,62 @@ function spanEnd(s: HTMLElement): number { return o + (s.textContent?.length ?? 0) } +/** the offsets [from, to] a paragraph element shows: all of them, or those of its part when the paragraph is split */ +const partOf = (el: HTMLElement): [number, number] => [Number(el.dataset.from ?? 0), el.dataset.to === undefined ? Infinity : Number(el.dataset.to)] + +/** + * The element of paragraph `pa` that shows offset `o`. A paragraph split across pages has one element per part, each + * with the offsets it holds (`data-from`, `data-to`: absent for the first and the last). Where two parts meet the + * offset is in both: the later one (the start of its first line), or with `upstream` the earlier one (the end of its + * last line). Null when no element of the paragraph shows `o` (its page is not rendered). + */ +export function paraEl(root: ParentNode, pa: string, o: number, upstream = false): HTMLElement | null { + let pick: HTMLElement | null = null + for (const el of root.querySelectorAll(`[data-pa="${pa}"]`)) { + const [from, to] = partOf(el) + if (o >= from && o <= to && !(upstream && pick)) pick = el + } + return pick +} + +/** the caret at a place is at the end of a part of its paragraph (the next part starts there) */ +function atPartEnd(root: HTMLElement, node: Node | null, pos: Pos | null): boolean { + const el = node && (node.nodeType === 1 ? (node as Element) : node.parentElement)?.closest('[data-pa]') + return !!el && !!pos && root.contains(el) && el.dataset.to !== undefined && pos.o === Number(el.dataset.to) +} + +/** + * DOM ranges over the offsets [a, b) of paragraph `pa`: one for each part of it shown, so that a range over the end of + * a page does not take in what is between the parts (footer, header). + */ +export function paraRanges(root: HTMLElement, pa: string, a: number, b: number): Range[] { + const out: Range[] = [] + for (const el of root.querySelectorAll(`[data-pa="${pa}"]`)) { + const [from, to] = partOf(el) + const x = Math.max(a, from) + const y = Math.min(b, to) + if (y < x || (y === x && b > a)) continue + const s = domIn(el, x) + const e = domIn(el, y) + const r = document.createRange() + r.setStart(s[0], s[1]) + r.setEnd(e[0], e[1]) + out.push(r) + } + return out +} + export function posFromDom(root: HTMLElement, node: Node, offset: number): Pos | null { const start = node.nodeType === 1 ? (node as Element) : node.parentElement const pel = start?.closest('[data-pa]') as HTMLElement | null if (!pel || !root.contains(pel)) return null const pa = pel.dataset.pa! if (!runSpan(node, pel)) { - // boundary between runs: end of the last run span before the point + // boundary between runs: end of the last run span before the point (the start of the part when none is) const r = document.createRange() r.setStart(node, offset) r.collapse(true) - let o = 0 + let o = Number(pel.dataset.from ?? 0) for (const sp of Array.from(pel.querySelectorAll('[data-o]'))) { if (r.comparePoint(sp, sp.childNodes.length) < 0) o = spanEnd(sp) else break @@ -275,9 +320,14 @@ export function posFromDom(root: HTMLElement, node: Node, offset: number): Pos | return { pa, o: base + o } } -export function domFromPos(root: HTMLElement, pos: Pos): [Node, number] | null { - const pel = root.querySelector(`[data-pa="${pos.pa}"]`) - if (!pel) return null +export function domFromPos(root: HTMLElement, pos: Pos, upstream = false): [Node, number] | null { + const pel = paraEl(root, pos.pa, pos.o, upstream) + return pel && domIn(pel, pos.o) +} + +/** the DOM place of offset `o` in a paragraph element (or the part of one that holds it) */ +function domIn(pel: HTMLElement, at: number): [Node, number] { + const pos = { o: at } const spans = Array.from(pel.querySelectorAll('[data-o]')) if (!spans.length) return [pel, pel.childNodes.length] let pick: HTMLElement | undefined @@ -366,6 +416,11 @@ export class RichInput { private expected: Sel | null = null /** where the DOM selection last was in a paragraph: a view update that removes this node leaves the caret on the page element */ private seen: Node | null = null + /** + * The caret was last seen at the end of a part of a paragraph split across pages (the end of a page), not at the + * start of the next part, which is the same offset: a caret put back there (after typing) stays on that side. + */ + private upstream = false constructor(private host: RichHost) {} @@ -413,7 +468,10 @@ export class RichInput { if (!root.contains(s.anchorNode) || !root.contains(s.focusNode)) return null const a = posFromDom(root, s.anchorNode, s.anchorOffset) const f = posFromDom(root, s.focusNode, s.focusOffset) - if (a && f) this.seen = s.anchorNode + if (a && f) { + this.seen = s.anchorNode + this.upstream = atPartEnd(root, s.focusNode, f) + } return a && f ? { a, f } : null } @@ -466,20 +524,34 @@ export class RichInput { }) const first = paras[0] const last = paras[paras.length - 1] - const dom: Sel = first && last ? { a: { pa: first.dataset.pa!, o: 0 }, f: { pa: last.dataset.pa!, o: plen(this.host.para(last.dataset.pa!)!.runs) } } : all + // (the first and last elements may be parts of paragraphs split across pages: what they show) + const dom: Sel = first && last ? { a: { pa: first.dataset.pa!, o: partOf(first)[0] }, f: { pa: last.dataset.pa!, o: Math.min(partOf(last)[1], plen(this.host.para(last.dataset.pa!)!.runs)) } } : all this.restore(dom) this.override = { model: all, dom: this.readSel() ?? dom } this.host.onSelection?.(all) return true } + /** + * The paragraphs holding the selection were laid out again (a page now ends elsewhere in them): when the DOM + * selection no longer shows the model's, it is put back. + */ + reflow(): boolean { + const want = this.expected ?? this.last + if (!this.root || this.composing || this.override || !want) return false + const now = this.readSel() + if (now && sameSel(now, want)) return false + return this.restore(want, false) + } + /** Applies a model selection to the DOM; false when its paragraph isn't rendered. */ restore(sel: Sel | null, focus = true): boolean { const root = this.root if (!root || !sel) return false this.override = null - const a = domFromPos(root, sel.a) - const f = domFromPos(root, sel.f) + const up = this.upstream && collapsed(sel) + const a = domFromPos(root, sel.a, up) + const f = domFromPos(root, sel.f, up) if (!a || !f) { // not in the DOM (its page is not shown): the DOM caret is somewhere else, and key presses go by this one this.last = sel @@ -631,6 +703,10 @@ export class RichInput { } } if (NAV.has(e.key)) this.expected = null + if ((e.key === 'ArrowRight' || e.key === 'ArrowLeft') && !mod && !e.altKey && this.crossPart(e.key === 'ArrowRight' ? 1 : -1, e.shiftKey)) { + e.preventDefault() + return + } if ((e.key === 'ArrowRight' || e.key === 'ArrowLeft') && !mod && !e.shiftKey && !e.altKey) { const sel = this.live() if (sel && collapsed(sel) && this.host.arrow?.(sel, e.key === 'ArrowRight' ? 1 : -1)) e.preventDefault() @@ -644,6 +720,44 @@ export class RichInput { } } + /** + * ArrowRight at the end of a part of a paragraph split across pages, ArrowLeft at the start of one: the browser would + * move to the other part at the same offset (the caret seems stuck). The caret moves one character into it instead, + * as over the end of a line. `extend`: Shift, the selection grows. + */ + private crossPart(dir: 1 | -1, extend: boolean): boolean { + const root = this.root + const s = root && selPoints(root) + const el = s?.focusNode && (s.focusNode.nodeType === 1 ? (s.focusNode as Element) : s.focusNode.parentElement)?.closest('[data-pa]') + if (!root || !el || !root.contains(el) || (el.dataset.from === undefined && el.dataset.to === undefined)) return false + const sel = this.readSel() + const p = sel && this.host.para(sel.f.pa) + if (!sel || !p || (!extend && !collapsed(sel))) return false + const [from, to] = partOf(el) + const text = runsText(p.runs) + let o: number + if (dir === 1 && to !== Infinity && sel.f.o >= to) o = nextBoundary(text, to) + else if (dir === -1 && from > 0 && sel.f.o <= from) o = prevBoundary(text, from) + else return false + const f = { pa: sel.f.pa, o } + if (!this.restore(extend ? { a: sel.a, f } : caret(f))) return false + // shown: the view scrolls to it (the browser does that for the caret it moves itself) + const n = getSel(root)?.focusNode + const r = n && document.createRange() + if (r && n) { + r.setStart(n, getSel(root)!.focusOffset) + const box = r.getBoundingClientRect() + let sc = root.parentElement + while (sc && !/(auto|scroll)/.test(getComputedStyle(sc).overflowY)) sc = sc.parentElement + const view = sc?.getBoundingClientRect() + if (sc && view && box.height) { + if (box.bottom > view.bottom - 8) sc.scrollTop += box.bottom - view.bottom + 48 + else if (box.top < view.top + 8) sc.scrollTop -= view.top - box.top + 48 + } + } + return true + } + /** a click moves the caret: what an edit asked for no longer holds */ private onMouseDown = () => { this.expected = null diff --git a/src/react/styles.css b/src/react/styles.css index e5c9d47..cc02b6f 100644 --- a/src/react/styles.css +++ b/src/react/styles.css @@ -386,6 +386,9 @@ -moz-tab-size: 36pt; } .de-p > span { white-space: inherit; } +/* a justified paragraph going on on the next page: its last line here is not its last, it is justified (an empty + line after it takes the place of the last; the part's height is set, that line is outside it) */ +.de-p.de-just::after { content: ''; display: inline-block; width: 100%; } .de-marker { display: inline-block; text-indent: 0; white-space: pre; } .de-tbl { border-collapse: collapse; diff --git a/test/docx-paginate.test.ts b/test/docx-paginate.test.ts index 0603e8f..5b66667 100644 --- a/test/docx-paginate.test.ts +++ b/test/docx-paginate.test.ts @@ -33,7 +33,8 @@ function doc(specs: Spec[]) { heights.set(b, 0) continue } - const b: Block = s.t ? { t: 'tbl', cols: [100], rows: s.t.map(() => ({ cells: [] })) } : { t: 'p', ps: s.ps ?? {}, runs: [], pb: s.pb } + // (widow / orphan control off unless a test turns it on: the cuts are then where the lines end) + const b: Block = s.t ? { t: 'tbl', cols: [100], rows: s.t.map(() => ({ cells: [] })) } : { t: 'p', ps: s.ps ?? { widowControl: false }, runs: [], pb: s.pb } blocks.push(b) if (s.h !== undefined) { heights.set(b, s.h) @@ -174,3 +175,55 @@ describe('breaks, sections, columns', () => { expect([0, 99, 100, 299, 300, 500].map((o) => pageAt(pages, 1, o, l))).toEqual([0, 0, 1, 1, 2, 2]) }) }) + +describe('keep rules', () => { + const wc: ParaStyle = {} + const off: ParaStyle = { widowControl: false } + + test('orphan control: the first line of a paragraph is not left alone at the bottom of a page', () => { + expect(pieces(run([{ p: lines(9) }, { p: lines(5), ps: wc }]))).toEqual([['0'], ['1']]) + expect(pieces(run([{ p: lines(9) }, { p: lines(5), ps: off }]))).toEqual([['0', '1:0-1'], ['1:1-end']]) + }) + + test('widow control: nor its last line alone at the top of the next', () => { + expect(pieces(run([{ p: lines(6) }, { p: lines(5), ps: wc }]))).toEqual([['0', '1:0-3'], ['1:3-end']]) + expect(pieces(run([{ p: lines(6) }, { p: lines(5), ps: off }]))).toEqual([['0', '1:0-4'], ['1:4-end']]) + // three lines with room for two: neither cut is allowed, the paragraph moves whole + expect(pieces(run([{ p: lines(8) }, { p: lines(3), ps: wc }]))).toEqual([['0'], ['1']]) + // a paragraph longer than a page: its last page keeps two lines + expect(pieces(run([{ p: lines(21), ps: wc }]))).toEqual([['0:0-10'], ['0:10-19'], ['0:19-end']]) + }) + + test('at the top of a page the rules give way: a line too tall for two to fit', () => { + expect(pieces(run([{ p: [60, 60, 60], ps: wc }]))).toEqual([['0:0-1'], ['0:1-2'], ['0:2-end']]) + }) + + test('keep lines together: the paragraph moves whole; one longer than a page is cut all the same', () => { + expect(pieces(run([{ p: lines(6) }, { p: lines(5), ps: { keepLines: true } }]))).toEqual([['0'], ['1']]) + expect(pieces(run([{ p: lines(2) }, { p: lines(15), ps: { keepLines: true } }]))).toEqual([['0', '1:0-8'], ['1:8-end']]) + }) + + test('keep with next: a heading goes with the first lines of what follows it', () => { + const heading: ParaStyle = { keepNext: true, widowControl: false } + // room for 2 lines after the heading: the paragraph's first part is 2 lines (orphan control), they fit + expect(pieces(run([{ p: lines(7) }, { p: [10], ps: heading }, { p: lines(5), ps: wc }]))).toEqual([['0', '1', '2:0-2'], ['2:2-end']]) + // room for one: the heading starts the next page with the paragraph + expect(pieces(run([{ p: lines(8) }, { p: [10], ps: heading }, { p: lines(5), ps: wc }]))).toEqual([['0'], ['1', '2']]) + // a chain of two headings: both move + expect(pieces(run([{ p: lines(7) }, { p: [10], ps: heading }, { p: [10], ps: heading }, { p: lines(5), ps: wc }]))).toEqual([['0'], ['1', '2', '3']]) + // before a table: with its header row and first row + expect(pieces(run([{ p: lines(8) }, { p: [10], ps: heading }, { t: lines(5), head: 1 }]))).toEqual([['0'], ['1', '2']]) + expect(pieces(run([{ p: lines(7) }, { p: [10], ps: heading }, { t: lines(5), head: 1 }]))).toEqual([['0', '1', '2:0-2'], ['2:2-end']]) + // a page break after the chain: nothing to keep it with on this page + expect(pieces(run([{ p: lines(8) }, { p: [10], ps: heading }, { p: lines(5), pb: true }]))).toEqual([['0', '1'], ['2']]) + }) + + test('a chain of paragraphs kept with the next taller than a page is cut like any: no page pushed on forever', () => { + const heading: ParaStyle = { keepNext: true, widowControl: false } + const specs: Spec[] = [{ p: lines(5) }, ...Array.from({ length: 15 }, () => ({ p: [10], ps: heading })), { p: lines(3) }] + expect(pieces(run(specs))).toEqual([['0', '1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10', '11', '12', '13', '14', '15'], ['16']]) + // every paragraph kept with the next: the document is cut into full pages + const all = run(Array.from({ length: 40 }, () => ({ p: [10], ps: heading }))) + expect(all.map((p) => p.end - p.start)).toEqual([10, 10, 10, 10]) + }) +}) From d49352c3bf977d8779eff729d5a1dc499f59c03c Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 12:26:05 +0700 Subject: [PATCH 5/9] perf(docx): measuring lines keeps one range, blocks that fit are placed without looking at their lines, typing cuts the pages once Co-Authored-By: Claude Opus 5.5 --- src/react/docx/DocxView.tsx | 52 +++++++++++++++++++++---------------- src/react/docx/measure.ts | 11 ++++++-- src/react/docx/paginate.ts | 13 ++++++++++ 3 files changed, 52 insertions(+), 24 deletions(-) diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index c95694f..5b39027 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -166,11 +166,33 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp st.frontier = 0 } const total = st.blocks.length - const laid = useMemo( - () => paginate(st.blocks, st.heights, Math.min(st.frontier, total), availPx, cols, (meta?.final && meta.sectKind) || 'nextPage', st.lines), - // eslint-disable-next-line react-hooks/exhaustive-deps - [version, availPx, total, cols, meta?.final, meta?.sectKind], - ) + // measured first: edited blocks + const queue: { b: Block; i: number; starts?: boolean }[] = [] + const queued = new Set() + const enqueue = (b: Block, i: number, starts?: boolean) => { + if (queued.has(b)) return + queued.add(b) + queue.push({ b, i, starts }) + } + for (const b of st.dirty) { + if (queue.length >= 50) break + const i = st.blocks.indexOf(b) + if (i < 0) st.dirty.delete(b) + else enqueue(b, i, true) + } + const edited = queue.length + // A few edited blocks (typing) are measured again before this render is painted, and the pages cut again then (see + // the measure effect): until that, the pages stay as they were cut. Else they are cut again on every update. + const soon = edited > 0 && edited <= 10 + const cut = useRef<{ version: number; key: string; total: number; pages: PageSlice[] } | null>(null) + const cutKey = `${availPx}|${cols}|${meta?.final}|${meta?.sectKind}` + const c0 = cut.current + let laid: PageSlice[] + if (c0 && c0.key === cutKey && c0.total === total && (c0.version === version || soon)) laid = c0.pages + else { + laid = paginate(st.blocks, st.heights, Math.min(st.frontier, total), availPx, cols, (meta?.final && meta.sectKind) || 'nextPage', st.lines) + cut.current = { version, key: cutKey, total, pages: laid } + } // while an input method composes, the pages stay as they are: a paragraph cut elsewhere would be rebuilt under it const frozen = useRef<{ pages: PageSlice[]; total: number } | null>(null) const composing = isEditing && editor.input.isComposing @@ -229,22 +251,8 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp : '' const lastCuts = useRef(selCuts) - // measured first: edited blocks, then the paragraphs a page shown ends in (where their lines start is read), then the - // not-yet-measured tail (time-sliced) - const queue: { b: Block; i: number; starts?: boolean }[] = [] - const queued = new Set() - const enqueue = (b: Block, i: number, starts?: boolean) => { - if (queued.has(b)) return - queued.add(b) - queue.push({ b, i, starts }) - } - for (const b of st.dirty) { - if (queue.length >= 50) break - const i = st.blocks.indexOf(b) - if (i < 0) st.dirty.delete(b) - else enqueue(b, i, true) - } - const edited = queue.length + // then the paragraphs a page shown ends in (where their lines start is read), then the not-yet-measured tail + // (time-sliced) /** the paragraphs page `pi` cuts whose line starts are not read yet */ const unread = (pi: number, out: Map) => { for (const c of pages[pi] ? columnsOf(pages[pi]) : []) { @@ -301,7 +309,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp } // a page shown waits for these, and a few edited blocks (typing) are laid out again before anything is painted: no // page shows them where they were (the caret is put back once, after that) - if (shownUnread.size || (edited > 0 && edited <= 10)) { + if (shownUnread.size || soon) { relayout.current = true return void save() } diff --git a/src/react/docx/measure.ts b/src/react/docx/measure.ts index 2a925fb..bba39b1 100644 --- a/src/react/docx/measure.ts +++ b/src/react/docx/measure.ts @@ -32,6 +32,13 @@ export function tableLines(el: HTMLElement, t: Table): Lines | undefined { return { ys, head: head < t.rows.length ? head : 0, keep: keep.size ? [...keep] : undefined } } +/** + * The one range measuring uses. Every live Range is updated by the browser on each DOM removal: one per paragraph + * measured, waiting for the garbage collector, would make removing the measured blocks slower and slower. + */ +let shared: Range | null = null +const theRange = () => (shared ??= document.createRange()) + /** inline boxes measured as a whole (pictures, text boxes, list markers), not by the text inside them */ const ATOMIC = 'img, .de-tbox, .de-ph, .de-img-missing, .de-marker' @@ -56,7 +63,7 @@ export function paraLines(el: HTMLElement): Lines { cur.b = Math.max(cur.b, b) } else lines.push({ t, b }) } - const range = document.createRange() + const range = theRange() const walk = (n: Node) => { for (let c = n.firstChild; c; c = c.nextSibling) { if (c.nodeType === 3) { @@ -97,7 +104,7 @@ export function lineStarts(el: HTMLElement, ys: number[]): number[] | undefined } if (!runs.length) return undefined const len = runs[runs.length - 1].o + runs[runs.length - 1].n - const range = document.createRange() + const range = theRange() const runAt = (o: number) => { let lo = 0 let hi = runs.length - 1 diff --git a/src/react/docx/paginate.ts b/src/react/docx/paginate.ts index 78878eb..3d77c8f 100644 --- a/src/react/docx/paginate.ts +++ b/src/react/docx/paginate.ts @@ -162,6 +162,19 @@ export function paginate(blocks: Block[], heights: WeakMap, count continue } if (b.t === 'p' && b.pb && cur.end > cur.start) newPage(i, 0) + // most blocks fit whole: placed without working out where they could be cut (thousands of pages, every update) + const bh = heights.get(b) ?? 0 + const free = !(b.t === 'p' && b.ps.keepNext && i >= loose) + // (its lines are looked at only when the space after it may not fit) + const bys = free && bh > avail - y + EPS && b.t === 'p' ? lines?.get(b)?.ys : undefined + const bInk = !bys || bys.length < 2 ? bh : bys[bys.length - 1] + if (free && bInk <= avail - y + EPS) { + cur.end = i + 1 + cur.to = undefined + y += bh + ink = y - (bh - bInk) + continue + } const s = shape(b) const { h, ys, n, headH, inkEnd } = s const pieceH = (k: number, j: number) => (k > 0 ? headH - ys[k] : 0) + (j === n ? h : ys[j]) From fa6a6aa69d39af419e8704eefd6eebf6c7eb7de7 Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 12:27:21 +0700 Subject: [PATCH 6/9] test(docx): split blocks in text columns, a justified paragraph, a comment over the page end, a Word 97 file Co-Authored-By: Claude Opus 5.5 --- e2e/docx-split.spec.ts | 92 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 2 deletions(-) diff --git a/e2e/docx-split.spec.ts b/e2e/docx-split.spec.ts index 12a4bef..96289b3 100644 --- a/e2e/docx-split.spec.ts +++ b/e2e/docx-split.spec.ts @@ -1,15 +1,16 @@ import { describe, expect, test } from 'bun:test' import type { Paragraph, Table } from '../src/core/docx/types' +import { DocBuilder } from '../test/doc-builder' import { bareDocx, para, table } from '../test/docx-builder' import { docxBlocks, paraText, useBrowser, viewer, type Viewer } from './harness' useBrowser() /** opens a built document in the fixture, editable, at `zoom`; waits until every page is laid out */ -async function open(doc: Blob | Promise, zoom = 1) { +async function open(doc: Blob | Promise, zoom = 1, name = 'split.docx') { const v = await viewer({ editable: true, onSave: true }, { wait: false }) const b64 = Buffer.from(await (await doc).arrayBuffer()).toString('base64') - await v.page.evaluate(([b, z]) => window.__setProps({ src: new Blob([Uint8Array.from(atob(b as string), (c) => c.charCodeAt(0))]), name: 'split.docx', zoom: z as number }), [b64, zoom] as const) + await v.page.evaluate(([b, z, n]) => window.__setProps({ src: new Blob([Uint8Array.from(atob(b as string), (c) => c.charCodeAt(0))]), name: n as string, zoom: z as number }), [b64, zoom, name] as const) await v.ready('docx') await v.page.waitForFunction(() => /Page \d+ of \d+ ·/.test(document.querySelector('.de-bar .de-status')?.textContent ?? '')) await v.page.waitForTimeout(200) @@ -403,6 +404,93 @@ describe('editing a paragraph split across pages', () => { }) }) +describe('more layouts', () => { + test('text columns: a paragraph goes on from one column to the next, then to the next page', async () => { + const long = uniq(900) + const sectPr = '' + const v = await open(bareDocx(filler(20) + para(long) + para('After'), { sectPr }), 0.5) + const ps = await parts(v, 20) + expect(ps.length).toBeGreaterThanOrEqual(3) + expect(ps.map((p) => p.text).join('')).toBe(long) + // the first two parts on page 1, in its two columns side by side + const cols = await v.page.evaluate(() => + Array.from(document.querySelectorAll('.de-pages [data-pa="20"]')).map((el) => ({ page: el.closest('.de-page')!.dataset.page, col: Array.from(el.closest('.de-page-cols')!.children).indexOf(el.closest('.de-page-col')!) })), + ) + expect(cols.slice(0, 3)).toEqual([ + { page: '1', col: 0 }, + { page: '1', col: 1 }, + { page: '2', col: 0 }, + ]) + expect(v.errors).toEqual([]) + }) + + test('a justified paragraph: ↓ from the last line of the first part goes to the next page', async () => { + const long = uniq(420) + const v = await open(bareDocx(filler(30) + para(long, '') + para('After')), 0.5) + const ps = await parts(v, 30) + expect(ps.map((p) => p.page)).toEqual([1, 2]) + await setSel(v, 30, [0, ps[0].text.length - 3]) + await v.page.keyboard.press('ArrowDown') + const c = await caretAt(v, 30) + expect(c.page).toBe(2) + expect(c.o).toBeGreaterThanOrEqual(ps[1].from) + // End on the last line of the first part: the caret at its end, still on page 1 + await setSel(v, 30, [0, ps[0].text.length - 3]) + await v.page.keyboard.press('End') + expect(await caretAt(v, 30)).toEqual({ page: 1, o: ps[1].from }) + expect(v.errors).toEqual([]) + }) +}) + +describe('a Word 97 file', () => { + test('converted, it is cut the same way: a long paragraph, a long table with its header row repeated', async () => { + const d = new DocBuilder() + for (let i = 0; i < 30; i++) d.p(`Filler line ${i + 1}`) + const long = uniq(420) + d.p(long) + d.table({ widths: [4000, 4000], header: true, borders: true, rows: [[{ paras: ['Head A'] }, { paras: ['Head B'] }], ...Array.from({ length: 70 }, (_, i) => [{ paras: [`row ${i + 1} a`] }, { paras: [`row ${i + 1} b`] }])] }) + d.p('The end') + const v = await open(new Blob([d.build()]), 0.5, 'split.doc') + const ps = await parts(v, 30) + expect(ps.length).toBe(2) + expect(ps.map((p) => p.text).join('')).toBe(long) + const n = await pageCount(v) + let copies = 0 + for (let k = 2; k <= n; k++) { + await showPage(v, k) + copies += await v.page.locator(`.de-page[data-page="${k}"] tr.de-head-copy`).count() + } + expect(copies).toBeGreaterThan(0) + expect(v.errors).toEqual([]) + }) +}) + +describe('comments', () => { + test('a comment on text over the page cut marks it on both pages', async () => { + const long = uniq(420) + const v = await open(bareDocx(filler(30) + para(long) + para('After')), 0.5) + const ps = await parts(v, 30) + const cut = ps[1].from + const back = ps[0].text.trimEnd().split(' ').slice(-2).join(' ').length + 1 + await setSel(v, 30, [0, ps[0].text.length - back], [1, 11]) + await v.page.keyboard.press('Control+Alt+KeyM') + await v.page.locator('.de-cm-panel').waitFor() + const quote = long.slice(cut - back, cut + 11) + expect(await v.page.locator('.de-cm-draft .de-cm-quote').innerText()).toBe(quote.trim()) + await v.page.keyboard.type('over the page end') + await v.page.keyboard.press('Enter') + const add = await v.waitEvent('comment') + await v.page.waitForTimeout(200) + const marked = await v.page.evaluate( + (id) => Array.from(document.querySelectorAll(`.de-pages [data-cm~="${id}"]`)).map((el) => ({ page: el.closest('.de-page')!.dataset.page, text: el.textContent })), + add.id as string, + ) + expect(marked.map((m) => m.page)).toEqual(['1', '2']) + expect(marked.map((m) => m.text).join('')).toBe(quote) + expect(v.errors).toEqual([]) + }) +}) + describe('print', () => { test('the printed pages are the pages shown: a paragraph and a table split the same way, nothing taller than the paper', async () => { const long = words(420) From f63371ba6f0069e3c02e851c74d8e9b6ec48c672 Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 12:29:22 +0700 Subject: [PATCH 7/9] docs: DOCX pages cut between lines and rows, keep rules, editing across the page end Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + docs/development.md | 4 ++++ docs/features.md | 14 ++++++++------ 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b057e26..733d105 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ Also online at [p10node.github.io/office-engine](https://p10node.github.io/offic - **Progressive loading**: lazy ZIP, HTTP Range requests, streaming XML parser in a Web Worker → UI never blocks - **Virtualized views**: only visible pages, cells and slides render +- **DOCX pages cut like Word's**: a paragraph goes on at the top of the next page between two lines, a table between two rows with its header rows repeated; widow / orphan control, keep with next, keep lines together; editing goes on across the page end - **Editing** with a Google Docs-style toolbar: DOCX text, styles, lists, images, tables; XLSX cells, formulas (540+ functions of Excel and Google Sheets, dynamic arrays, `LET` / `LAMBDA`), formats, borders, rows/columns, sheets; PPTX text, shapes, images, slides, slideshow - **Fast save**: only edited parts are regenerated, everything else keeps its original bytes - **Word, Excel and PowerPoint 97-2003, RTF, OpenDocument**: `.doc` / `.xls` / `.ppt`, `.rtf` and `.odt` / `.ods` / `.odp` (also templates and flat XML) are converted in the worker to DOCX / XLSX / PPTX and open **editable**: styles, lists, tables, pictures, headers and footers, notes and comments; formulas with their values, number formats, merged cells, frozen panes; masters, shapes, text and pictures of slides. Saved as `.docx` / `.xlsx` / `.pptx` diff --git a/docs/development.md b/docs/development.md index b20388e..289f237 100644 --- a/docs/development.md +++ b/docs/development.md @@ -39,6 +39,10 @@ src/embed.ts mount() + src/collab real-time collaboration (hub, session, per-format adapters) ``` +### DOCX pages + +`DocxView` measures the blocks off screen in time slices (`src/react/docx/measure.ts`: a block's height, where a paragraph's lines and a table's rows are), `paginate()` cuts them into pages (`paginate.ts`: pure, lines and rows given, keep rules; unit tests in `test/docx-paginate.test.ts`) and only the pages in view render. The browser breaks the lines; the offset each line starts at is read (`lineStarts`) only for the paragraphs a page in view or an edit cuts. A paragraph split across pages renders as one element per part, each with the paragraph's `data-pa` address and the offsets it holds (`data-from`, `data-to`): `paraEl()` / `posFromDom()` / `domFromPos()` in `src/react/edit/input.ts` map DOM places to paragraph offsets over the parts, so the caret, selections, find and comments need nothing else. Header rows repeated on the following pages of a table are copies without an address (`.de-head-copy`). + ## Browser tests `e2e/*.spec.ts` drive a fixture app (`e2e/app`, served by Vite with `vite.e2e.config.ts`) in headless Chromium through `playwright-core`, one browser and server per file (`e2e/harness.ts`). diff --git a/docs/features.md b/docs/features.md index c7ca46b..59cd884 100644 --- a/docs/features.md +++ b/docs/features.md @@ -6,17 +6,18 @@ - **HTTP Range**: open a URL → fetch only the bytes needed (256 KB block cache); server without Range support → automatic full-download fallback - **Streaming XML parser** runs in a **Web Worker** → UI never blocks - **Progressive render**: - - DOCX: blocks (paragraph/table) stream in → offscreen height measurement in time slices → pagination → only visible pages render + - DOCX: blocks (paragraph/table) stream in → offscreen measurement in time slices (heights, where lines and table rows are) → pagination → only visible pages render - XLSX: rows stream in, 2D virtualized grid (only cells in viewport render), freeze panes, merge, number format, sheet tabs - PPTX: slides parsed on demand when scrolled into view, virtualized thumbnails +- **DOCX pages** are cut the way Word cuts them, with the lines the browser lays out: a paragraph that does not fit the rest of a page goes on at the top of the next one (split between two lines, the same lines as when whole; a justified paragraph's last line on the first page stays justified), a table between two rows, its header rows (`w:tblHeader`) repeated at the top of each following page; a merged cell cut by the page end goes on as an empty cell. Keep rules choose the cut: widow / orphan control (on unless the paragraph, its style or the document defaults turn it off), keep lines together, keep with next (a chain of headings goes with the first lines after it; a chain taller than a page is cut like any text). Only one line or one row taller than a page makes its page taller. Text columns are filled the same way, column after column ## Format support -| Format | Supported | Not yet | -|--------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------| -| DOCX | inherited styles, run formatting, lists/numbering, tables (merge, border, shading, table style), images, hyperlinks, header/footer, PAGE field, text boxes, page/section breaks, text columns, tracked changes | footnote body, charts, exact float wrapping, paragraphs split across pages | -| XLSX | shared strings, number/date formats, font/fill/border/align, merge, freeze, hidden columns/rows, wrap, formula calculation (540+ functions, recalculated on edit), multiple sheets, images (over the cells) | charts (placeholder), shapes, conditional formatting | -| PPTX | master/layout/theme, placeholder inheritance, ~50 preset shapes, custGeom, images (crop), tables + table style, groups, bullet/autonum, autofit | charts (placeholder), SmartArt, animations, video playback | +| Format | Supported | Not yet | +|--------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------| +| DOCX | inherited styles, run formatting, lists/numbering, tables (merge, border, shading, table style), images, hyperlinks, header/footer, PAGE field, text boxes, page/section breaks, text columns, tracked changes, paragraphs and tables split across pages | footnote body, charts, exact float wrapping | +| XLSX | shared strings, number/date formats, font/fill/border/align, merge, freeze, hidden columns/rows, wrap, formula calculation (540+ functions, recalculated on edit), multiple sheets, images (over the cells) | charts (placeholder), shapes, conditional formatting | +| PPTX | master/layout/theme, placeholder inheritance, ~50 preset shapes, custGeom, images (crop), tables + table style, groups, bullet/autonum, autofit | charts (placeholder), SmartArt, animations, video playback | Password-protected (encrypted) files are not supported. @@ -177,6 +178,7 @@ Diagram sources open as a document holding the drawing (an SVG picture, editable - **Images**: insert (file picker/paste/drag & drop), click to select with 8 resize handles, original size, fit width, replace, alt text, download - **Tables**: insert, add/delete rows & columns, delete table, Tab between cells; select cells by dragging across them, merge / unmerge (across and down), cell color, cell borders (all / outer / inner / none / one side, color, line style), vertical alignment, distribute columns, drag a column edge to resize - **Page setup**: paper size (A4, Letter, Legal, A3, A5, B5), portrait / landscape, margins (cm, presets), 1–3 text columns with spacing; applies to the whole document +- **Across pages**: a paragraph cut by the end of a page is edited as one: click, type, select, delete, find and arrow keys go over the page end; typing that moves the page end keeps the caret where the typing is (also with an input method). In a table that goes on over pages every row is edited where it is; the header rows repeated on the following pages are copies, edited on the first page - **Headers & footers**: header, footer and first-page parts (double-click the page's header / footer area, or the toolbar), alignment, bold, size, page number / page count fields with presets ("Page 1 of 5", "Trang 1/5"), different first page - **Tracked changes**: insertions and deletions from Word shown in their author's color and kept on save; next / previous change, accept / reject (the change at the caret, the selection, or all); *Track changes* records your own edits as suggestions (typing, deleting, pasting, replacing) - **Other**: select all (Ctrl/⌘+A), link (dialog), special characters, right-click context menu (clipboard, link, table, image, insert, styles), find & replace, word count, undo/redo From 3364b7a73c6f59b4e3ee63a219009fba2416e80a Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 12:29:22 +0700 Subject: [PATCH 8/9] test(docx): the Word 97 file's bytes typed as a Blob part (typecheck) Co-Authored-By: Claude Opus 5.5 --- e2e/docx-split.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/docx-split.spec.ts b/e2e/docx-split.spec.ts index 96289b3..1b49294 100644 --- a/e2e/docx-split.spec.ts +++ b/e2e/docx-split.spec.ts @@ -450,7 +450,7 @@ describe('a Word 97 file', () => { d.p(long) d.table({ widths: [4000, 4000], header: true, borders: true, rows: [[{ paras: ['Head A'] }, { paras: ['Head B'] }], ...Array.from({ length: 70 }, (_, i) => [{ paras: [`row ${i + 1} a`] }, { paras: [`row ${i + 1} b`] }])] }) d.p('The end') - const v = await open(new Blob([d.build()]), 0.5, 'split.doc') + const v = await open(new Blob([d.build() as BlobPart]), 0.5, 'split.doc') const ps = await parts(v, 30) expect(ps.length).toBe(2) expect(ps.map((p) => p.text).join('')).toBe(long) From 343fc9e5ff3c1752963527d3e96e926f2392a66a Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 12:44:02 +0700 Subject: [PATCH 9/9] fix(docx): Word 97 and RTF paragraphs without widow control keep it off Widow control absent from a DOCX now means on, as Word reads it. The Word 97 and RTF converters write it only where a paragraph or style has it, so the paragraphs of those files without it came out with it on. Their document defaults now say it is off. Co-Authored-By: Claude Opus 5.5 --- src/core/legacy/doc/index.ts | 4 +++- src/core/legacy/rtf/docx.ts | 3 ++- test/docx-keep.test.ts | 14 ++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/core/legacy/doc/index.ts b/src/core/legacy/doc/index.ts index 3820f61..423e64c 100644 --- a/src/core/legacy/doc/index.ts +++ b/src/core/legacy/doc/index.ts @@ -155,7 +155,9 @@ class Packager { let out = `` + `` + - '' + // (styles and paragraphs say widow control only where it differs from a Word 97 paragraph's default: off. + // OOXML without it means on, as Word reads it) + '' for (const s of st.styles) { if (!s || (s.stk !== 1 && s.stk !== 2)) continue const base = st.baseOf(s.istd) diff --git a/src/core/legacy/rtf/docx.ts b/src/core/legacy/rtf/docx.ts index 015c7c7..835ff64 100644 --- a/src/core/legacy/rtf/docx.ts +++ b/src/core/legacy/rtf/docx.ts @@ -31,10 +31,11 @@ export function packDocx(r: RtfReader): Promise { // styles: the document defaults, then the stylesheet's styles const st = r.styles const dRPr = rPrSet(r.tables, st.defChp) + // (an RTF paragraph has widow control only with \widctlpar; OOXML without it means on, as Word reads it) add( 'word/styles.xml', 'styles', - `${XML_HEAD}${dRPr}${st.xml()}`, + `${XML_HEAD}${dRPr}${st.xml()}`, ) doc.rel('styles', 'styles.xml') diff --git a/test/docx-keep.test.ts b/test/docx-keep.test.ts index 5d13413..d3a2e2b 100644 --- a/test/docx-keep.test.ts +++ b/test/docx-keep.test.ts @@ -5,6 +5,7 @@ import type { Block, Paragraph } from '../src/core/docx/types' import { BlobSource } from '../src/core/source' import { ZipArchive } from '../src/core/zip' import { bareDocx, para } from './docx-builder' +import { DocBuilder, sprm } from './doc-builder' async function open(src: Blob) { const events: { event: string; data: any }[] = [] @@ -73,4 +74,17 @@ describe('keepLines / widowControl', () => { { keepLines: undefined, widowControl: undefined }, ]) }) + + test('RTF and Word 97 files: widow control only where the file has it (their paragraphs have none unless said)', async () => { + const rtf = String.raw`{\rtf1\ansi\deff0{\fonttbl{\f0 Times New Roman;}}` + '\n' + String.raw`\pard plain\par\pard\widctlpar kept\par\pard\nowidctlpar off\par}` + const r = await open(new Blob([rtf], { type: 'application/rtf' })) + expect(r.paras.map(text)).toEqual(['plain', 'kept', 'off']) + expect(r.paras.map((p) => p.ps.widowControl)).toEqual([false, true, false]) + const d = new DocBuilder() + d.p('plain') + d.p('kept', 0, sprm(0x2431, 1)) + const w = await open(new Blob([d.build() as Uint8Array])) + expect(w.paras.map(text)).toEqual(['plain', 'kept']) + expect(w.paras.map((p) => p.ps.widowControl)).toEqual([false, true]) + }) })