Sync snapshot (2026-08-12) (#87)
- Add text insertion and improved text editing in PDF files - Expand PDF form filling, annotations, highlighting, and visual signature workflows - Add PDF image crop, flip, transparency, replacement, and background removal - Improve Sheets validation rendering, undo behavior, and workbook stability - Add system font discovery and improve shared Office interface consistency - Improve AI network resilience and response validation Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
2c1f0e821a
commit
dc4d7e5927
@@ -7,7 +7,7 @@ import type {
|
||||
TableCell,
|
||||
TableModel,
|
||||
} from './types'
|
||||
import { escapeXmlAttr, escapeXmlText } from './xml-utils'
|
||||
import { escapeXmlAttr, escapeXmlText, textHasComplexScript } from './xml-utils'
|
||||
|
||||
export interface GenerateContext {
|
||||
/** heading level -> styleId existing in the original styles.xml */
|
||||
@@ -1011,6 +1011,10 @@ function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
|
||||
xml: `<w:framePr w:dropCap="${type}" w:lines="${lines}" w:wrap="around" w:vAnchor="text" w:hAnchor="text"/>`,
|
||||
})
|
||||
}
|
||||
if (format.emptyRunSizeHalfPoints) {
|
||||
const sz = Math.round(format.emptyRunSizeHalfPoints)
|
||||
out.push({ name: 'w:rPr', xml: `<w:rPr><w:sz w:val="${sz}"/><w:szCs w:val="${sz}"/></w:rPr>` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -1182,6 +1186,10 @@ function pprGroupUnchanged(tag: string, raw: string | undefined, f: ParaFormat):
|
||||
return rawTabsUnchanged(raw, f.tabStops ?? [])
|
||||
case 'w:framePr':
|
||||
return rawFramePrUnchanged(raw, f)
|
||||
case 'w:rPr': {
|
||||
const m = raw ? /<w:sz\b[^>]*w:val="(\d+)"/.exec(raw) : null
|
||||
return (m ? parseInt(m[1], 10) : undefined) === f.emptyRunSizeHalfPoints
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
@@ -1216,6 +1224,8 @@ export function mergePPrFormat(rawPPr: string, format: ParaFormat | undefined):
|
||||
const managedTags = new Set(FORMAT_MANAGED_TAGS)
|
||||
if (format?.tabStops !== undefined) managedTags.add('w:tabs')
|
||||
if (format?.dropCap !== undefined) managedTags.add('w:framePr')
|
||||
// only when the model carries a size: otherwise the paragraph-mark rPr stays unmanaged
|
||||
if (format?.emptyRunSizeHalfPoints !== undefined) managedTags.add('w:rPr')
|
||||
const rawChildren = splitXmlChildren(inner)
|
||||
const rawOf = (tag: string) => rawChildren.find((c) => c.name === tag)?.xml
|
||||
const rebuilt = new Set(
|
||||
@@ -1493,22 +1503,16 @@ function tableCellXml(
|
||||
runs: text === '' ? [] : [{ text, bold: cell.bold, color: cell.color }],
|
||||
}))
|
||||
const paraXmls = paragraphs.map((paragraph) => {
|
||||
// cell.align is a raw w:jc, so it is Word's logical value, while paragraph.align has already
|
||||
// been converted to a visual one and the format model converts it back on the way out. Only
|
||||
// left and right differ between the two, so an RTL paragraph still takes the cell fallback
|
||||
// for centre and justify and skips it for the sided values, which cannot be placed in either
|
||||
// coordinate system with confidence.
|
||||
const bidi = 'bidi' in paragraph && paragraph.bidi === true
|
||||
const sided = cell.align === 'left' || cell.align === 'right'
|
||||
const align = paragraph.align ?? (bidi && sided ? undefined : cell.align)
|
||||
const list = 'list' in paragraph ? paragraph.list : undefined
|
||||
const numPr = list
|
||||
? `<w:numPr><w:ilvl w:val="${list.ilvl}"/><w:numId w:val="${escapeXmlAttr(list.numId)}"/></w:numPr>`
|
||||
: ''
|
||||
// the parsed format, not just w:jc: hand-building it here dropped w:bidi and wrote the visual
|
||||
// align back as the logical one, flipping RTL cells to LTR, and discarded every other
|
||||
// paragraph property the model carries
|
||||
const pPr = mergePPrFormat(`<w:pPr>${numPr}</w:pPr>`, { ...paragraph, align })
|
||||
// no cell.align fallback here: it is a display aggregate of the paragraphs' own
|
||||
// jc values, and writing it back would stamp w:jc into paragraphs that never had one
|
||||
// (rich paragraphs carry their own align; the plain-paras fallback above sets it).
|
||||
// The parsed format, not just w:jc: hand-building the pPr here dropped w:bidi and
|
||||
// discarded every other paragraph property the model carries.
|
||||
const pPr = mergePPrFormat(`<w:pPr>${numPr}</w:pPr>`, paragraph)
|
||||
return `<w:p>${pPr}${runsXml(paragraph.runs, null)}</w:p>`
|
||||
})
|
||||
// nested tables are regenerated from the model at their paragraph anchors (reverse
|
||||
@@ -1969,6 +1973,7 @@ const RUN_MANAGED_GROUPS: Array<{ key: string; tags: string[] }> = [
|
||||
{ key: 'size', tags: ['w:sz', 'w:szCs'] },
|
||||
{ key: 'highlight', tags: ['w:highlight'] },
|
||||
{ key: 'underline', tags: ['w:u'] },
|
||||
{ key: 'shading', tags: ['w:shd'] },
|
||||
{ key: 'vertAlign', tags: ['w:vertAlign'] },
|
||||
{ key: 'rPrChange', tags: ['w:rPrChange'] },
|
||||
]
|
||||
@@ -2077,6 +2082,12 @@ function modelRPrChildren(run: Run, insideLink: boolean): PPrChild[] {
|
||||
if (run.highlight)
|
||||
out.push({ name: 'w:highlight', xml: `<w:highlight w:val="${escapeXmlAttr(run.highlight)}"/>` })
|
||||
if (run.underline) out.push({ name: 'w:u', xml: '<w:u w:val="single"/>' })
|
||||
if (run.shading) {
|
||||
out.push({
|
||||
name: 'w:shd',
|
||||
xml: `<w:shd w:val="clear" w:color="auto" w:fill="${escapeXmlAttr(run.shading)}"/>`,
|
||||
})
|
||||
}
|
||||
if (run.vertAlign)
|
||||
out.push({ name: 'w:vertAlign', xml: `<w:vertAlign w:val="${run.vertAlign}"/>` })
|
||||
const rPrChange = revisionRPrChangeXml(run)
|
||||
@@ -2100,6 +2111,9 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
|
||||
const inner = rawRPr.slice(open.length, rawRPr.length - '</w:rPr>'.length)
|
||||
const rawChildren = splitXmlChildren(inner)
|
||||
const rawOf = (tag: string) => rawChildren.find((c) => c.name === tag)?.xml
|
||||
// complex-script runs decode bold/italic/size from the Cs twins on the parse side;
|
||||
// compare against the same elements or every untouched cs run would get "rebuilt"
|
||||
const cs = run.cs ?? textHasComplexScript(run.text)
|
||||
|
||||
// Compare model vs raw-encoded values group by group; equal → keep the original bytes
|
||||
// (drop the group from fresh)
|
||||
@@ -2126,9 +2140,9 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
|
||||
return (rawAttr(attrs, 'w:eastAsia') ?? ascii) === run.font && ascii === run.fontAscii
|
||||
}
|
||||
case 'bold':
|
||||
return rawBool(rawOf('w:b')) === !!run.bold
|
||||
return rawBool(rawOf(cs ? 'w:bCs' : 'w:b')) === !!run.bold
|
||||
case 'italic':
|
||||
return rawBool(rawOf('w:i')) === !!run.italic
|
||||
return rawBool(rawOf(cs ? 'w:iCs' : 'w:i')) === !!run.italic
|
||||
case 'strike':
|
||||
return rawBool(rawOf('w:strike')) === !!run.strike
|
||||
case 'color': {
|
||||
@@ -2136,13 +2150,17 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
|
||||
return (raw === 'auto' ? undefined : raw) === run.color
|
||||
}
|
||||
case 'size': {
|
||||
const raw = rawAttr(rawOf('w:sz'), 'w:val')
|
||||
const raw = rawAttr(rawOf(cs ? 'w:szCs' : 'w:sz'), 'w:val')
|
||||
return (raw ? parseInt(raw, 10) || undefined : undefined) === run.sizeHalfPoints
|
||||
}
|
||||
case 'highlight': {
|
||||
const raw = rawAttr(rawOf('w:highlight'), 'w:val')
|
||||
return (raw === 'none' ? undefined : raw) === run.highlight
|
||||
}
|
||||
case 'shading': {
|
||||
const raw = rawAttr(rawOf('w:shd'), 'w:fill')
|
||||
return (raw && raw !== 'auto' ? raw : undefined) === run.shading
|
||||
}
|
||||
case 'underline': {
|
||||
// w:u is not a boolean prop: no w:val (or val="none") means no
|
||||
// underline, regardless of other attributes like w:color. Must match
|
||||
|
||||
@@ -58,6 +58,7 @@ import {
|
||||
findChildren,
|
||||
nameOf,
|
||||
serializeXNode,
|
||||
textHasComplexScript,
|
||||
textOf,
|
||||
underlineProp,
|
||||
xmlParser,
|
||||
@@ -1033,6 +1034,10 @@ function buildTextParagraph(
|
||||
rubyFragmentsOf(mathXml),
|
||||
withImages,
|
||||
)
|
||||
if (runs.length === 0) {
|
||||
const emptySz = emptyParaSizeHalfPoints(pNode, pPr)
|
||||
if (emptySz) format = { ...(format ?? {}), emptyRunSizeHalfPoints: emptySz }
|
||||
}
|
||||
const { bookmarks, hiddenBookmarks } = bookmarkNamesOf(stripTextboxes(xml))
|
||||
const { commentStarts, commentEnds } = crossParaCommentMarkers(stripTextboxes(xml))
|
||||
|
||||
@@ -2071,6 +2076,25 @@ function onlyXeFields(xml: string): boolean {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* w:sz governing a run-less paragraph's line height: the paragraph-mark rPr
|
||||
* (pPr/w:rPr), else the last run's rPr — those runs are all empty and get
|
||||
* dropped, but Word still sizes the empty line by them (1pt spacer lines).
|
||||
*/
|
||||
function emptyParaSizeHalfPoints(pNode: XNode, pPr: XNode | undefined): number | undefined {
|
||||
let sz = pPr
|
||||
? attrsOf(findChild(findChild(pPr, 'w:rPr') ?? {}, 'w:sz') ?? {})['w:val']
|
||||
: undefined
|
||||
if (!sz) {
|
||||
for (const r of findChildren(pNode, 'w:r')) {
|
||||
const v = attrsOf(findChild(findChild(r, 'w:rPr') ?? {}, 'w:sz') ?? {})['w:val']
|
||||
if (v) sz = v
|
||||
}
|
||||
}
|
||||
const n = sz ? parseInt(sz, 10) : NaN
|
||||
return Number.isFinite(n) && n > 0 ? n : undefined
|
||||
}
|
||||
|
||||
function extractRuns(
|
||||
pNode: XNode,
|
||||
ctx: BuildContext,
|
||||
@@ -2402,9 +2426,13 @@ function buildRun(
|
||||
run.rawRPr = serializeXNode(rPr)
|
||||
const rStyle = attrsOf(findChild(rPr, 'w:rStyle') ?? {})['w:val']
|
||||
if (rStyle && rStyle !== 'Hyperlink') run.styleId = rStyle
|
||||
const bold = onOffOf(rPr, 'w:b')
|
||||
// complex-script runs take bold/italic/size from the Cs twins only: w:b/w:i/w:sz
|
||||
// do not apply to them, and a missing twin means regular (no fallback), per OOXML
|
||||
const cs = onOffOf(rPr, 'w:rtl') ?? textHasComplexScript(text)
|
||||
if (cs) run.cs = true
|
||||
const bold = onOffOf(rPr, cs ? 'w:bCs' : 'w:b')
|
||||
if (bold !== undefined) run.bold = bold
|
||||
const italic = onOffOf(rPr, 'w:i')
|
||||
const italic = onOffOf(rPr, cs ? 'w:iCs' : 'w:i')
|
||||
if (italic !== undefined) run.italic = italic
|
||||
if (underlineProp(rPr)) run.underline = true
|
||||
else if (attrsOf(findChild(rPr, 'w:u') ?? {})['w:val'] === 'none') run.underline = false
|
||||
@@ -2412,7 +2440,7 @@ function buildRun(
|
||||
if (strike !== undefined) run.strike = strike
|
||||
const color = colorFrom(rPr, theme)
|
||||
if (color) run.color = color
|
||||
const sz = attrsOf(findChild(rPr, 'w:sz') ?? {})['w:val']
|
||||
const sz = attrsOf(findChild(rPr, cs ? 'w:szCs' : 'w:sz') ?? {})['w:val']
|
||||
if (sz) run.sizeHalfPoints = parseInt(sz, 10) || undefined
|
||||
const rf = themedRFonts(attrsOf(findChild(rPr, 'w:rFonts') ?? {}), themeFonts)
|
||||
const font = rf.eastAsia ?? rf.ascii ?? rf.hAnsi
|
||||
@@ -2427,6 +2455,8 @@ function buildRun(
|
||||
if (wScale > 0 && wScale !== 100) run.charScalePct = wScale
|
||||
const highlight = attrsOf(findChild(rPr, 'w:highlight') ?? {})['w:val']
|
||||
if (highlight && highlight !== 'none') run.highlight = highlight
|
||||
const shdFill = attrsOf(findChild(rPr, 'w:shd') ?? {})['w:fill']
|
||||
if (shdFill && shdFill !== 'auto') run.shading = shdFill
|
||||
const vertAlign = attrsOf(findChild(rPr, 'w:vertAlign') ?? {})['w:val']
|
||||
if (vertAlign === 'superscript' || vertAlign === 'subscript') run.vertAlign = vertAlign
|
||||
const em = attrsOf(findChild(rPr, 'w:em') ?? {})['w:val']
|
||||
@@ -2504,6 +2534,8 @@ function sameStyle(a: Run, b: Run): boolean {
|
||||
return (
|
||||
(a.rawRPr ?? '') === (b.rawRPr ?? '') &&
|
||||
a.styleId === b.styleId &&
|
||||
// same rPr can decode differently for cs vs non-cs text; merging would misapply the twins
|
||||
!!a.cs === !!b.cs &&
|
||||
!!a.bold === !!b.bold &&
|
||||
!!a.italic === !!b.italic &&
|
||||
!!a.underline === !!b.underline &&
|
||||
@@ -2888,6 +2920,7 @@ function extractCell(tc: XNode, ctx: BuildContext): TableCell {
|
||||
let sawBold = false
|
||||
let sawNonBold = false
|
||||
const runColors = new Set<string>()
|
||||
const textParaJcs = new Set<string>()
|
||||
for (const block of childrenThroughSdt(tc, ['w:p', 'w:tbl'])) {
|
||||
if (nameOf(block) === 'w:tbl') {
|
||||
const model = extractTableModel(block, ctx)
|
||||
@@ -2898,7 +2931,8 @@ function extractCell(tc: XNode, ctx: BuildContext): TableCell {
|
||||
continue
|
||||
}
|
||||
const p = block
|
||||
cell.paras.push(textOf(p))
|
||||
const paraText = textOf(p)
|
||||
cell.paras.push(paraText)
|
||||
const pPr = findChild(p, 'w:pPr')
|
||||
const format = extractParaFormat(pPr ?? {})
|
||||
const cellStyleId = pPr ? attrsOf(findChild(pPr, 'w:pStyle') ?? {})['w:val'] : undefined
|
||||
@@ -2910,17 +2944,15 @@ function extractCell(tc: XNode, ctx: BuildContext): TableCell {
|
||||
ilvl: cellRef.ilvl,
|
||||
}
|
||||
: undefined
|
||||
const runs = extractRuns(p, ctx, [], [], true)
|
||||
const emptySz = runs.length === 0 ? emptyParaSizeHalfPoints(p, pPr) : undefined
|
||||
richParas.push({
|
||||
...format,
|
||||
...(emptySz ? { emptyRunSizeHalfPoints: emptySz } : {}),
|
||||
...(list ? { list } : {}),
|
||||
runs: extractRuns(p, ctx, [], [], true),
|
||||
runs,
|
||||
})
|
||||
if (!cell.align) {
|
||||
const jc = attrsOf(findChild(findChild(p, 'w:pPr') ?? {}, 'w:jc') ?? {})['w:val']
|
||||
if (jc === 'center' || jc === 'right' || jc === 'left' || jc === 'justify') {
|
||||
cell.align = jc
|
||||
}
|
||||
}
|
||||
if (paraText !== '') textParaJcs.add(attrsOf(findChild(pPr ?? {}, 'w:jc') ?? {})['w:val'] ?? '')
|
||||
for (const r of findChildren(p, 'w:r')) {
|
||||
const rPr = findChild(r, 'w:rPr')
|
||||
if (rPr && boolProp(rPr, 'w:b')) sawBold = true
|
||||
@@ -2928,15 +2960,15 @@ function extractCell(tc: XNode, ctx: BuildContext): TableCell {
|
||||
if (textOf(r) !== '') runColors.add((rPr && colorFrom(rPr, ctx.themeColors)) ?? 'none')
|
||||
}
|
||||
}
|
||||
// drop trailing empty paragraphs so cells don't get artificially tall
|
||||
while (cell.paras.length > 1 && cell.paras[cell.paras.length - 1] === '') {
|
||||
cell.paras.pop()
|
||||
richParas.pop()
|
||||
// cell.align only when every text paragraph declares the same jc; a first-wins
|
||||
// td-level text-align would leak onto the cell's jc-less paragraphs
|
||||
if (textParaJcs.size === 1) {
|
||||
const jc = textParaJcs.values().next().value
|
||||
if (jc === 'center' || jc === 'right' || jc === 'left' || jc === 'justify') cell.align = jc
|
||||
}
|
||||
cell.richParas = richParas
|
||||
if (nested.length > 0) {
|
||||
cell.nestedTables = nested
|
||||
// clamp anchors that pointed past the trimmed tail
|
||||
cell.nestedTableAnchors = nestedAnchors.map((a) => Math.min(a, cell.paras.length))
|
||||
}
|
||||
if (sawBold && !sawNonBold) cell.bold = true
|
||||
|
||||
@@ -1580,6 +1580,9 @@ function retargetImageBlip(xml: string, rId: string): string {
|
||||
return (
|
||||
(xml.slice(0, blip.index) + tag + xml.slice(blip.index + blip[0].length))
|
||||
.replace(/<a:srcRect\b[^>]*\/>/, '')
|
||||
// A non-default fill window would clip the swapped bytes the same way a
|
||||
// crop would — reset it (the editor clears its imageFillRect in step)
|
||||
.replace(/<a:fillRect\b[^>]+\/>/, '<a:fillRect/>')
|
||||
// The replacement is always raster and Word prefers a leftover Office-2016
|
||||
// <asvg:svgBlip> extension over the retargeted r:embed — drop the extension
|
||||
.replace(/<a:ext\b[^>]*>\s*<\w+:svgBlip\b[\s\S]*?<\/a:ext>/, '')
|
||||
|
||||
@@ -43,6 +43,10 @@ export interface Run {
|
||||
charScalePct?: number
|
||||
/** OOXML named highlight color (w:highlight), e.g. "yellow" */
|
||||
highlight?: string
|
||||
/** character shading fill, hex without '#' (w:shd w:fill, non-auto); highlight wins when both are set */
|
||||
shading?: string
|
||||
/** bold/italic/size were read from the Cs twins (w:bCs/w:iCs/w:szCs): w:rtl run or complex-script text */
|
||||
cs?: boolean
|
||||
/** superscript / subscript (w:vertAlign) */
|
||||
vertAlign?: 'superscript' | 'subscript'
|
||||
/** East Asian emphasis mark (w:em). Display only; saving is kept faithful by rawRPr */
|
||||
@@ -239,6 +243,12 @@ export interface ParaFormat {
|
||||
* visual direction and writing back converts again.
|
||||
*/
|
||||
bidi?: boolean
|
||||
/**
|
||||
* w:sz (half-points) governing a run-less paragraph's line height: the
|
||||
* paragraph-mark rPr, else the last (dropped) empty run's rPr. Set only when
|
||||
* the paragraph has no runs, so empty lines keep their Word height.
|
||||
*/
|
||||
emptyRunSizeHalfPoints?: number
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -120,3 +120,10 @@ export function escapeXmlText(text: string): string {
|
||||
export function escapeXmlAttr(text: string): string {
|
||||
return escapeXmlText(text).replace(/"/g, '"')
|
||||
}
|
||||
|
||||
/** Text contains complex-script characters (Arabic/Hebrew/Syriac/Thaana/NKo), i.e. the w:*Cs run properties apply */
|
||||
export function textHasComplexScript(text: string): boolean {
|
||||
return /[\u0590-\u05FF\u0600-\u077F\u0780-\u07FF\u08A0-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/.test(
|
||||
text,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ describe('nested table editing (surgical text patch + regeneration)', () => {
|
||||
expect(xml).toContain('InnerA')
|
||||
expect(xml).toContain('InnerB')
|
||||
// nested table is followed by an empty paragraph (OOXML: tc must end with w:p)
|
||||
expect(/<\/w:tbl><w:p\/><\/w:tc>/.test(xml)).toBe(true)
|
||||
expect(/<\/w:tbl><w:p(?:\/>|><\/w:p>)<\/w:tc>/.test(xml)).toBe(true)
|
||||
// reparsing still yields the nested structure
|
||||
const saved = await saveDocx(doc, [{ kind: 'xml', xml }])
|
||||
const reparsed = await parseDocx(saved)
|
||||
@@ -60,7 +60,8 @@ describe('nested table editing (surgical text patch + regeneration)', () => {
|
||||
it('parses paragraph anchors for interleaved nested tables and regenerates in reading order', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: INTERLEAVED_TABLE_XML }))
|
||||
const cell = doc.blocks[0].table!.rows[0][0]
|
||||
expect(cell.paras).toEqual(['Title1', 'Title2'])
|
||||
// the trailing empty paragraph is kept: Word renders it as a visible line
|
||||
expect(cell.paras).toEqual(['Title1', 'Title2', ''])
|
||||
expect(cell.nestedTableAnchors).toEqual([1, 2])
|
||||
|
||||
const xml = generateTableModelXml(doc.blocks[0].table!)
|
||||
@@ -68,7 +69,7 @@ describe('nested table editing (surgical text patch + regeneration)', () => {
|
||||
expect(order.every((idx) => idx >= 0)).toBe(true)
|
||||
expect([...order].sort((a, b) => a - b)).toEqual(order)
|
||||
// trailing nested table is still followed by an empty paragraph
|
||||
expect(/<\/w:tbl><w:p\/><\/w:tc>/.test(xml)).toBe(true)
|
||||
expect(/<\/w:tbl><w:p(?:\/>|><\/w:p>)<\/w:tc>/.test(xml)).toBe(true)
|
||||
|
||||
// reparse of the regenerated table keeps the anchors
|
||||
const reparsed = await parseDocx(await saveDocx(doc, [{ kind: 'xml', xml }]))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { buildKitchenSinkDocx } from './helpers/build-docx'
|
||||
import { buildDocx, buildKitchenSinkDocx } from './helpers/build-docx'
|
||||
|
||||
describe('parseDocx', () => {
|
||||
it('parses the kitchen-sink document into anchored blocks', async () => {
|
||||
@@ -147,3 +147,19 @@ describe('parseDocx', () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty paragraph line size', () => {
|
||||
it('records the w:sz that governs a run-less paragraph', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:t>before</w:t></w:r></w:p>' +
|
||||
// paragraph-mark rPr wins
|
||||
'<w:p><w:pPr><w:rPr><w:sz w:val="2"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="4"/></w:rPr><w:t></w:t></w:r></w:p>' +
|
||||
// no pPr rPr: falls back to the (dropped) empty run
|
||||
'<w:p><w:r><w:rPr><w:sz w:val="16"/></w:rPr><w:t></w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
expect(doc.blocks[0].format?.emptyRunSizeHalfPoints).toBeUndefined()
|
||||
expect(doc.blocks[1].runs).toEqual([])
|
||||
expect(doc.blocks[1].format?.emptyRunSizeHalfPoints).toBe(2)
|
||||
expect(doc.blocks[2].format?.emptyRunSizeHalfPoints).toBe(16)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -93,3 +93,23 @@ describe('explicit w:after="0"', () => {
|
||||
expect(out).toBe('<w:pPr><w:spacing w:after="0"/></w:pPr>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty-paragraph size write-back (pPr w:rPr)', () => {
|
||||
it('inserts a fresh paragraph-mark rPr when the model carries a size', () => {
|
||||
expect(mergePPrFormat('<w:pPr></w:pPr>', { emptyRunSizeHalfPoints: 2 })).toBe(
|
||||
'<w:pPr><w:rPr><w:sz w:val="2"/><w:szCs w:val="2"/></w:rPr></w:pPr>',
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps the original paragraph-mark rPr bytes when the size is unchanged', () => {
|
||||
const raw = '<w:pPr><w:rPr><w:rFonts w:ascii="Georgia"/><w:sz w:val="2"/></w:rPr></w:pPr>'
|
||||
expect(mergePPrFormat(raw, { emptyRunSizeHalfPoints: 2 })).toBe(raw)
|
||||
})
|
||||
|
||||
it('leaves the paragraph-mark rPr unmanaged when the model has no size', () => {
|
||||
const raw = '<w:pPr><w:rPr><w:b/><w:sz w:val="28"/></w:rPr></w:pPr>'
|
||||
expect(mergePPrFormat(raw, { align: 'center' })).toBe(
|
||||
'<w:pPr><w:jc w:val="center"/><w:rPr><w:b/><w:sz w:val="28"/></w:rPr></w:pPr>',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,7 +4,13 @@
|
||||
* rebuilds; editing a modeled field rebuilds only its group.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateParagraphXml, parseDocx, saveDocx, type GenerateContext, type SaveBlock } from '../src/index'
|
||||
import {
|
||||
generateParagraphXml,
|
||||
parseDocx,
|
||||
saveDocx,
|
||||
type GenerateContext,
|
||||
type SaveBlock,
|
||||
} from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join, dirname } from 'node:path'
|
||||
@@ -33,9 +39,14 @@ const RICH_RPR =
|
||||
const RICH_PARA = `<w:p><w:r>${RICH_RPR}<w:t>富格式文本</w:t></w:r></w:p>`
|
||||
|
||||
const UNMODELED_TAGS = [
|
||||
'<w:caps/>', '<w:dstrike/>', '<w:vanish/>',
|
||||
'<w:caps/>',
|
||||
'<w:dstrike/>',
|
||||
'<w:vanish/>',
|
||||
'w:themeColor="accent1"',
|
||||
'<w:spacing w:val="20"/>', '<w:w w:val="90"/>', '<w:kern w:val="24"/>', '<w:position w:val="6"/>',
|
||||
'<w:spacing w:val="20"/>',
|
||||
'<w:w w:val="90"/>',
|
||||
'<w:kern w:val="24"/>',
|
||||
'<w:position w:val="6"/>',
|
||||
'<w:szCs w:val="32"/>',
|
||||
'<w:u w:val="double"/>',
|
||||
'<w:bdr w:val="single" w:sz="4" w:space="1" w:color="auto"/>',
|
||||
@@ -63,10 +74,7 @@ describe('rawRPr passthrough', () => {
|
||||
const run = doc.blocks[0].runs![0]
|
||||
// Add bold (not there originally): w:b is inserted at its schema position, the other
|
||||
// groups keep their original bytes
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, bold: true }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
const xml = generateParagraphXml({ type: 'paragraph', runs: [{ ...run, bold: true }] }, GEN_CTX)
|
||||
expect(xml).toContain('<w:b/>')
|
||||
// schema order: rFonts < b < caps
|
||||
expect(xml.indexOf('<w:rFonts')).toBeLessThan(xml.indexOf('<w:b/>'))
|
||||
@@ -107,15 +115,22 @@ describe('rawRPr passthrough', () => {
|
||||
|
||||
it('adjacent runs with different unmodeled props are not merged at parse', async () => {
|
||||
const body =
|
||||
'<w:p><w:r><w:rPr><w:caps/></w:rPr><w:t>大写</w:t></w:r>' +
|
||||
'<w:r><w:t>普通</w:t></w:r></w:p>'
|
||||
'<w:p><w:r><w:rPr><w:caps/></w:rPr><w:t>大写</w:t></w:r>' + '<w:r><w:t>普通</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
|
||||
expect(doc.blocks[0].runs).toHaveLength(2) // modeled fields all equal, but rawRPr differs → no merge
|
||||
})
|
||||
})
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const REAL = join(here, '..', '..', '..', 'example', 'docx', 'OpenClaw开源项目调研分析报告文档.docx')
|
||||
const REAL = join(
|
||||
here,
|
||||
'..',
|
||||
'..',
|
||||
'..',
|
||||
'example',
|
||||
'docx',
|
||||
'OpenClaw开源项目调研分析报告文档.docx',
|
||||
)
|
||||
|
||||
// Runs only when the local (gitignored) sample document is present.
|
||||
describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', () => {
|
||||
@@ -154,7 +169,9 @@ describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', ()
|
||||
const JSZip = (await import('jszip')).default
|
||||
const [zBefore, zAfter] = await Promise.all([JSZip.loadAsync(bytes), JSZip.loadAsync(saved)])
|
||||
const fileNames = (z: InstanceType<typeof JSZip>) =>
|
||||
Object.keys(z.files).filter((n) => !z.files[n].dir).sort()
|
||||
Object.keys(z.files)
|
||||
.filter((n) => !z.files[n].dir)
|
||||
.sort()
|
||||
expect(fileNames(zAfter)).toEqual(fileNames(zBefore))
|
||||
for (const name of fileNames(zBefore)) {
|
||||
// core.xml is the exception: a real save updates dcterms:modified / cp:revision
|
||||
@@ -167,7 +184,9 @@ describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', ()
|
||||
}
|
||||
|
||||
// Untouched paragraphs' original slices remain; the edited one keeps its character spacing
|
||||
const newXml = new TextDecoder().decode(await zAfter.files['word/document.xml'].async('uint8array'))
|
||||
const newXml = new TextDecoder().decode(
|
||||
await zAfter.files['word/document.xml'].async('uint8array'),
|
||||
)
|
||||
let checked = 0
|
||||
for (const b of visible) {
|
||||
if (b === target || !b.originalXml || b.originalXml.length < 40) continue
|
||||
@@ -188,3 +207,73 @@ describe.skipIf(!existsSync(REAL))('real document invariant (example/docx)', ()
|
||||
expect(reparsed.blocks.length).toBe(doc.blocks.length)
|
||||
})
|
||||
})
|
||||
|
||||
describe('complex-script runs read the Cs twins (w:bCs/w:iCs/w:szCs)', () => {
|
||||
it('w:b / w:sz do not apply to Arabic text; the Cs twins do', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:rPr><w:b/><w:sz w:val="28"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:rPr><w:bCs/><w:iCs/><w:szCs w:val="36"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:rPr><w:b/><w:sz w:val="28"/></w:rPr><w:t>latin</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const [bOnly, csTwins, latin] = doc.blocks.filter((b) => b.runs?.length).map((b) => b.runs![0])
|
||||
expect(bOnly.cs).toBe(true)
|
||||
expect(bOnly.bold).toBeUndefined()
|
||||
expect(bOnly.sizeHalfPoints).toBeUndefined()
|
||||
expect(csTwins.bold).toBe(true)
|
||||
expect(csTwins.italic).toBe(true)
|
||||
expect(csTwins.sizeHalfPoints).toBe(36)
|
||||
expect(latin.cs).toBeUndefined()
|
||||
expect(latin.bold).toBe(true)
|
||||
expect(latin.sizeHalfPoints).toBe(28)
|
||||
})
|
||||
|
||||
it('w:rtl marks a run complex-script regardless of its characters', async () => {
|
||||
const bodyXml = '<w:p><w:r><w:rPr><w:rtl/><w:b/></w:rPr><w:t>123</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
expect(doc.blocks[0].runs![0].cs).toBe(true)
|
||||
expect(doc.blocks[0].runs![0].bold).toBeUndefined()
|
||||
})
|
||||
|
||||
it('an untouched Arabic run keeps its w:b/w:sz bytes on paragraph rebuild', async () => {
|
||||
const bodyXml = '<w:p><w:r><w:rPr><w:b/><w:sz w:val="28"/></w:rPr><w:t>عنوان</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const run = doc.blocks[0].runs![0]
|
||||
const xml = generateParagraphXml({ type: 'paragraph', runs: [{ ...run }] }, GEN_CTX)
|
||||
expect(xml).toContain('<w:b/>')
|
||||
expect(xml).toContain('<w:sz w:val="28"/>')
|
||||
expect(xml).not.toContain('<w:bCs/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('run-level character shading (w:shd)', () => {
|
||||
it('parses the non-auto fill alongside highlight', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:rPr><w:shd w:val="clear" w:color="auto" w:fill="FFC000"/></w:rPr><w:t>badge</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:highlight w:val="yellow"/><w:shd w:val="clear" w:fill="FFC000"/></w:rPr><w:t>both</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:shd w:val="clear" w:fill="auto"/></w:rPr><w:t>none</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const runs = doc.blocks[0].runs!
|
||||
expect(runs[0].shading).toBe('FFC000')
|
||||
expect(runs[1].shading).toBe('FFC000')
|
||||
expect(runs[1].highlight).toBe('yellow')
|
||||
expect(runs[2].shading).toBeUndefined()
|
||||
})
|
||||
|
||||
it('unchanged shading keeps its exact bytes; a modeled value writes fresh', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:rPr><w:shd w:val="pct15" w:color="FF0000" w:fill="FFC000"/></w:rPr><w:t>x</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml }))
|
||||
const run = doc.blocks[0].runs![0]
|
||||
expect(run.shading).toBe('FFC000')
|
||||
const kept = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, text: 'edited' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(kept).toContain('<w:shd w:val="pct15" w:color="FF0000" w:fill="FFC000"/>')
|
||||
const fresh = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ text: 'z', shading: '00B050' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(fresh).toContain('<w:shd w:val="clear" w:color="auto" w:fill="00B050"/>')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -42,7 +42,12 @@ describe('table display model', () => {
|
||||
|
||||
const header = table.rows[0]
|
||||
expect(header.map((c) => c.paras[0])).toEqual(['排名', '品牌', '份额'])
|
||||
expect(header[0]).toMatchObject({ fill: '1F3864', color: 'FFFFFF', bold: true, align: 'center' })
|
||||
expect(header[0]).toMatchObject({
|
||||
fill: '1F3864',
|
||||
color: 'FFFFFF',
|
||||
bold: true,
|
||||
align: 'center',
|
||||
})
|
||||
|
||||
const dataRow = table.rows[1]
|
||||
expect(dataRow[1].colSpan).toBe(2)
|
||||
@@ -143,3 +148,35 @@ describe('table display model', () => {
|
||||
expect(table.cellMarTwips).toEqual({ left: 200, right: 200 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('cell alignment aggregation and trailing empty paragraphs', () => {
|
||||
it('sets cell.align only when every text paragraph declares the same jc', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="3000"/><w:gridCol w:w="3000"/></w:tblGrid><w:tr>' +
|
||||
// centered title + jc-less body: a td-level center would leak onto the body
|
||||
'<w:tc><w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>标题</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>要点</w:t></w:r></w:p></w:tc>' +
|
||||
// all text paragraphs agree (the empty one does not vote)
|
||||
'<w:tc><w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>甲</w:t></w:r></w:p>' +
|
||||
'<w:p/>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>乙</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const [mixed, agreed] = doc.blocks[0].table!.rows[0]
|
||||
expect(mixed.align).toBeUndefined()
|
||||
expect(agreed.align).toBe('center')
|
||||
})
|
||||
|
||||
it('keeps trailing empty cell paragraphs and their empty-run size', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid><w:tr><w:tc>' +
|
||||
'<w:p><w:r><w:t>内容</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:rPr><w:sz w:val="2"/></w:rPr></w:pPr></w:p>' +
|
||||
'</w:tc></w:tr></w:tbl>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const cell = doc.blocks[0].table!.rows[0][0]
|
||||
expect(cell.paras).toEqual(['内容', ''])
|
||||
expect(cell.richParas?.[1].emptyRunSizeHalfPoints).toBe(2)
|
||||
expect(cell.richParas?.[1].runs).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -301,20 +301,20 @@ describe('cell paragraph properties survive a table rebuild', () => {
|
||||
expect(out).toContain('<w:shd w:val="clear" w:color="auto" w:fill="DDEEFF"/>')
|
||||
})
|
||||
|
||||
it('still falls back to the cell alignment for a paragraph that declared none', async () => {
|
||||
// control: this case is unchanged from before, and passes with or without the fix
|
||||
it("does not stamp another paragraph's alignment onto one that declared none", async () => {
|
||||
// mixed jc: no cell-level alignment, and the jc-less paragraph must stay that way
|
||||
const out = await rebuild(
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>b</w:t></w:r></w:p>' +
|
||||
'</w:tc></w:tr></w:tbl>',
|
||||
)
|
||||
expect(out.match(/<w:jc w:val="center"\/>/g)).toHaveLength(2)
|
||||
expect(out.match(/<w:jc w:val="center"\/>/g)).toHaveLength(1)
|
||||
const second = out.slice(out.lastIndexOf('<w:p>'))
|
||||
expect(second).not.toContain('<w:jc ')
|
||||
})
|
||||
|
||||
it('keeps a direction-neutral cell alignment on a bidi paragraph', async () => {
|
||||
// only left/right are swapped between logical and visual, so centre and justify are safe
|
||||
// to take from the cell even when the paragraph is RTL
|
||||
it('keeps a bidi paragraph free of alignment it never declared', async () => {
|
||||
const out = await rebuild(
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>' +
|
||||
@@ -323,6 +323,33 @@ describe('cell paragraph properties survive a table rebuild', () => {
|
||||
)
|
||||
const second = out.slice(out.lastIndexOf('<w:p>'))
|
||||
expect(second).toContain('<w:bidi/>')
|
||||
expect(second).toContain('<w:jc w:val="center"/>')
|
||||
expect(second).not.toContain('<w:jc ')
|
||||
})
|
||||
|
||||
it("writes every paragraph's jc back when they all agree (cell.align set)", async () => {
|
||||
const out = await rebuild(
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>' +
|
||||
'</w:tc></w:tr></w:tbl>',
|
||||
)
|
||||
expect(out.match(/<w:jc w:val="center"\/>/g)).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('trailing empty cell paragraph size survives regeneration', () => {
|
||||
it('writes the empty paragraph and its w:sz back', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid><w:tr><w:tc>' +
|
||||
'<w:p><w:r><w:t>内容</w:t></w:r></w:p>' +
|
||||
'<w:p><w:pPr><w:rPr><w:sz w:val="2"/></w:rPr></w:pPr></w:p>' +
|
||||
'</w:tc></w:tr></w:tbl>',
|
||||
}),
|
||||
)
|
||||
const out = generateTableModelXml(doc.blocks[0].table!)
|
||||
expect(out.match(/<w:p[\s>]|<w:p\/>/g)).toHaveLength(2)
|
||||
expect(out).toContain('<w:pPr><w:rPr><w:sz w:val="2"/><w:szCs w:val="2"/></w:rPr></w:pPr>')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user