Sync snapshot (2026-08-30) (#168)
- Docs: DOCX rendering fidelity - drop caps, hidden (vanish) runs, paragraph pattern shading, floating-table anchoring and clamping, footnote sizing, justified-line spacing - Docs: editing - page breaks split the paragraph correctly, URLs auto-linkify, Insert Hyperlink prefills from the selection, more stable table pagination - Sheets: large streamed workbooks are splittable and formula-capable for the AI; copy_range carries live formulas; range sort up to 200k cells; 1M-cell copies over 2x faster - Sheets: correctness - sort by raw values, shared-formula edits, typed cached strings, empty-string cells, note edits reach the save; risky structural deletes are rejected up front - Sheets: AI chat can export sheets as standalone files; the formula bar grows to fit wrapped formulas - Slides: right-to-left support - paragraph direction toggle, RTL tables, mirrored margins and bullets - Slides: rendering - scaled gradients, embedded fonts, complex-script shaping, chart plot layouts and legends, theme-override colors - Shell: open documents by dropping them onto the window; per-type document icons for OS file associations - AI: localized busy message for overloaded providers; degenerate tool loops stopped with a unified turn budget - Markdown: prompts to save before pasting images into untitled documents Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
583a045212
commit
2239cce9e7
@@ -5,6 +5,123 @@ import { buildDocx, buildKitchenSinkDocx } from '../tests/helpers/build-docx'
|
||||
|
||||
const outDir = join(dirname(fileURLToPath(import.meta.url)), '../../../fixtures/generated')
|
||||
|
||||
const TABLE_BORDERS =
|
||||
'<w:tblBorders><w:top w:val="single" w:sz="4"/><w:bottom w:val="single" w:sz="4"/>' +
|
||||
'<w:left w:val="single" w:sz="4"/><w:right w:val="single" w:sz="4"/>' +
|
||||
'<w:insideH w:val="single" w:sz="4"/><w:insideV w:val="single" w:sz="4"/></w:tblBorders>'
|
||||
|
||||
/** bordered table with explicit dxa grid columns and deterministic cell text */
|
||||
function capTableXml(options: {
|
||||
tblPrXml: string
|
||||
colWidths: number[]
|
||||
headers: string[]
|
||||
dataRows: number
|
||||
}): string {
|
||||
const { tblPrXml, colWidths, headers, dataRows } = options
|
||||
const grid = colWidths.map((w) => `<w:gridCol w:w="${w}"/>`).join('')
|
||||
const cell = (w: number, text: string) =>
|
||||
`<w:tc><w:tcPr><w:tcW w:w="${w}" w:type="dxa"/></w:tcPr>` +
|
||||
`<w:p><w:r><w:t xml:space="preserve">${text}</w:t></w:r></w:p></w:tc>`
|
||||
const rows = [
|
||||
`<w:tr>${headers.map((h, c) => cell(colWidths[c], h)).join('')}</w:tr>`,
|
||||
...Array.from(
|
||||
{ length: dataRows },
|
||||
(_, r) => `<w:tr>${colWidths.map((w, c) => cell(w, `val-${r}-${c}`)).join('')}</w:tr>`,
|
||||
),
|
||||
].join('')
|
||||
return `<w:tbl><w:tblPr>${tblPrXml}${TABLE_BORDERS}</w:tblPr><w:tblGrid>${grid}</w:tblGrid>${rows}</w:tbl>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Visual-regression corpus (e2e/docs-visual.spec.ts): the cap-table shapes
|
||||
* from the floating-table overflow fix (#1111). All widths overshoot the
|
||||
* A4 content width (9026 dxa) on purpose — the renderer must clamp them.
|
||||
*/
|
||||
async function buildVisualCorpus(): Promise<Array<[string, Uint8Array]>> {
|
||||
const eightCols = [2400, 1600, 1800, 1600, 2000, 1800, 2000, 1600]
|
||||
const captableHeaders = [
|
||||
'Shareholder',
|
||||
'Class',
|
||||
'Shares',
|
||||
'Price',
|
||||
'Invested',
|
||||
'Ownership %',
|
||||
'Fully Diluted %',
|
||||
'Board Seats',
|
||||
'Liquidation Pref',
|
||||
'Anti-dilution',
|
||||
'Vesting',
|
||||
'Notes',
|
||||
]
|
||||
const wrapText =
|
||||
'The parties agree that the capitalization set out above reflects all issued and ' +
|
||||
'outstanding shares on a fully diluted basis as of the closing date.'
|
||||
|
||||
const inline = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Series B Capitalization Table</w:t></w:r></w:p>' +
|
||||
capTableXml({
|
||||
tblPrXml: '<w:tblW w:w="23400" w:type="dxa"/>',
|
||||
colWidths: [2400, 1600, 1800, 1600, 2000, 1800, 2000, 1600, 2200, 2000, 1800, 2600],
|
||||
headers: captableHeaders,
|
||||
dataRows: 3,
|
||||
}) +
|
||||
`<w:p><w:r><w:t xml:space="preserve">${wrapText}</w:t></w:r></w:p>`,
|
||||
})
|
||||
|
||||
const float = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:t>Exhibit A — Ownership Summary</w:t></w:r></w:p>' +
|
||||
capTableXml({
|
||||
tblPrXml:
|
||||
'<w:tblW w:w="14800" w:type="dxa"/>' +
|
||||
'<w:tblpPr w:leftFromText="180" w:rightFromText="180" w:vertAnchor="text" ' +
|
||||
'w:horzAnchor="page" w:tblpX="4000" w:tblpY="200"/>',
|
||||
colWidths: eightCols,
|
||||
headers: eightCols.map((_, c) => `Col${c}`),
|
||||
dataRows: 2,
|
||||
}) +
|
||||
`<w:p><w:r><w:t xml:space="preserve">${wrapText}</w:t></w:r></w:p>` +
|
||||
`<w:p><w:r><w:t xml:space="preserve">${wrapText}</w:t></w:r></w:p>`,
|
||||
})
|
||||
|
||||
// vertAnchor="page": the table must land at 6000 twips from the page top
|
||||
// (≈400 css px) regardless of where its anchor paragraph sits in the flow
|
||||
const pageAnchor = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:t>Exhibit C — Page-Anchored Position</w:t></w:r></w:p>' +
|
||||
`<w:p><w:r><w:t xml:space="preserve">${wrapText}</w:t></w:r></w:p>` +
|
||||
capTableXml({
|
||||
tblPrXml:
|
||||
'<w:tblW w:w="9026" w:type="dxa"/>' +
|
||||
'<w:tblpPr w:leftFromText="180" w:rightFromText="180" w:vertAnchor="page" ' +
|
||||
'w:horzAnchor="margin" w:tblpY="6000"/>',
|
||||
colWidths: [2306, 2240, 2240, 2240],
|
||||
headers: ['Holder', 'Class', 'Shares', 'Notes'],
|
||||
dataRows: 2,
|
||||
}) +
|
||||
`<w:p><w:r><w:t xml:space="preserve">${wrapText}</w:t></w:r></w:p>`,
|
||||
})
|
||||
|
||||
const pct = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:t>Exhibit B — Percentage Width</w:t></w:r></w:p>' +
|
||||
capTableXml({
|
||||
tblPrXml: '<w:tblW w:w="7500" w:type="pct"/>',
|
||||
colWidths: eightCols,
|
||||
headers: eightCols.map((_, c) => `Col${c}`),
|
||||
dataRows: 2,
|
||||
}),
|
||||
})
|
||||
|
||||
return [
|
||||
['visual-captable-inline.docx', inline],
|
||||
['visual-captable-float.docx', float],
|
||||
['visual-captable-pct.docx', pct],
|
||||
['visual-captable-page-anchor.docx', pageAnchor],
|
||||
]
|
||||
}
|
||||
|
||||
async function main() {
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
|
||||
@@ -19,6 +136,10 @@ async function main() {
|
||||
})
|
||||
writeFileSync(join(outDir, 'simple.docx'), simple)
|
||||
|
||||
for (const [name, bytes] of await buildVisualCorpus()) {
|
||||
writeFileSync(join(outDir, name), bytes)
|
||||
}
|
||||
|
||||
console.log(`fixtures written to ${outDir}`)
|
||||
}
|
||||
|
||||
|
||||
@@ -414,18 +414,23 @@ function xmlSegments(
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild one cell's paragraphs with new text, keeping tcPr and the first
|
||||
* paragraph's pPr / first run's rPr (so header bold, alignment, shading stay).
|
||||
* Rebuild one cell's paragraphs, keeping tcPr. String entries keep the legacy
|
||||
* behavior (first paragraph's pPr / first run's rPr for every paragraph); rich
|
||||
* entries regenerate full runs against their own original paragraph's pPr, and
|
||||
* null entries keep the original paragraph bytes untouched.
|
||||
* Returns null when the cell is too complex to patch safely (nested table).
|
||||
*/
|
||||
function patchCellXml(tcXml: string, paras: string[]): string | null {
|
||||
function patchCellXml(tcXml: string, paras: readonly CellParaPatch[]): string | null {
|
||||
if (tcXml.indexOf('<w:tbl', 1) !== -1) return null
|
||||
const openTag = /^<w:tc(?: [^>]*)?>/.exec(tcXml)?.[0]
|
||||
if (!openTag) return null
|
||||
const tcPr = /<w:tcPr[\s\S]*?<\/w:tcPr>|<w:tcPr[^>]*\/>/.exec(tcXml)?.[0] ?? ''
|
||||
const firstP = /<w:p(?: [^>]*)?>[\s\S]*?<\/w:p>/.exec(tcXml)?.[0] ?? ''
|
||||
const pPr = /<w:pPr[\s\S]*?<\/w:pPr>|<w:pPr[^>]*\/>/.exec(firstP)?.[0] ?? ''
|
||||
const firstRun = /<w:r(?: [^>]*)?>[\s\S]*?<\/w:r>/.exec(firstP)?.[0] ?? ''
|
||||
const originals = xmlSegments(tcXml, 'w:p', openTag.length, tcXml.length).map((seg) =>
|
||||
tcXml.slice(seg.start, seg.end),
|
||||
)
|
||||
const pPrOf = (pXml: string) => /<w:pPr[\s\S]*?<\/w:pPr>|<w:pPr[^>]*\/>/.exec(pXml)?.[0] ?? ''
|
||||
const firstPPr = pPrOf(originals[0] ?? '')
|
||||
const firstRun = /<w:r(?: [^>]*)?>[\s\S]*?<\/w:r>/.exec(originals[0] ?? '')?.[0] ?? ''
|
||||
const rPr = /<w:rPr[\s\S]*?<\/w:rPr>/.exec(firstRun)?.[0] ?? ''
|
||||
// picture runs are not part of the text model; carry them over verbatim so a
|
||||
// text edit in a cell with an inline image doesn't drop the image
|
||||
@@ -435,20 +440,88 @@ function patchCellXml(tcXml: string, paras: string[]): string | null {
|
||||
.filter((r) => r.includes('<w:drawing'))
|
||||
.join('')
|
||||
: ''
|
||||
// The run model re-emits every drawing it resolved media for (run.image.xml),
|
||||
// including Word's mc:Choice drawing whose VML w:pict fallback shares the same
|
||||
// media relationship. Only drawings the model cannot see (shapes, textboxes,
|
||||
// charts, blind pict/object) must ride over. Carried copies keep only the
|
||||
// drawing payload children — run-level text belongs to the rich runs, while
|
||||
// text nested inside the drawing (textbox content) stays intact.
|
||||
const mediaRIds = (xml: string) =>
|
||||
[...xml.matchAll(/<(?:a:blip|v:imagedata)\b[^>]*\br:(?:embed|link|id)="([^"]+)"/g)].map(
|
||||
(m) => m[1],
|
||||
)
|
||||
const DRAWING_TAGS = new Set(['mc:AlternateContent', 'w:drawing', 'w:pict', 'w:object'])
|
||||
const carriedRunsOf = (pXml: string, emittedMedia: Set<string>) => {
|
||||
// a payload is a twin of an emitted image when all its media is already
|
||||
// re-emitted and it carries no textbox text of its own
|
||||
const isTwin = (payload: string) => {
|
||||
const ids = mediaRIds(payload)
|
||||
return (
|
||||
ids.length > 0 &&
|
||||
ids.every((id) => emittedMedia.has(id)) &&
|
||||
!/<w:txbxContent[\s>]|<v:textbox[\s>]/.test(payload)
|
||||
)
|
||||
}
|
||||
return xmlSegments(pXml, 'w:r', 0, pXml.length)
|
||||
.map((seg) => pXml.slice(seg.start, seg.end))
|
||||
.filter((r) => /<wp:anchor[\s>]|<w:pict[\s>]|<w:object[\s>]/.test(r))
|
||||
.map((r) => {
|
||||
const open = /^<w:r(?:\s[^>]*)?>/.exec(r)?.[0]
|
||||
if (!open) return ''
|
||||
const kept = splitXmlChildren(r.slice(open.length, r.length - '</w:r>'.length)).filter(
|
||||
(c) => DRAWING_TAGS.has(c.name) && !isTwin(c.xml),
|
||||
)
|
||||
return kept.length > 0 ? `<w:r>${kept.map((c) => c.xml).join('')}</w:r>` : ''
|
||||
})
|
||||
.join('')
|
||||
}
|
||||
const aligned = paras.length === originals.length
|
||||
const body = paras
|
||||
.map((t, i) => {
|
||||
const keep = i === 0 ? drawingRuns : ''
|
||||
return t === ''
|
||||
? `<w:p>${pPr}${keep}</w:p>`
|
||||
: `<w:p>${pPr}<w:r>${rPr}<w:t xml:space="preserve">${escapeXmlText(t)}</w:t></w:r>${keep}</w:p>`
|
||||
.map((entry, i) => {
|
||||
if (entry === null) return originals[i] ?? ''
|
||||
if (typeof entry === 'string') {
|
||||
const keep = i === 0 ? drawingRuns : ''
|
||||
return entry === ''
|
||||
? `<w:p>${firstPPr}${keep}</w:p>`
|
||||
: `<w:p>${firstPPr}<w:r>${rPr}${cellRunContentXml(entry)}</w:r>${keep}</w:p>`
|
||||
}
|
||||
const template = originals[Math.min(i, originals.length - 1)] ?? ''
|
||||
const emitted = runsXml(entry.runs, null)
|
||||
const emittedMedia = new Set(mediaRIds(emitted))
|
||||
const keep = aligned
|
||||
? carriedRunsOf(template, emittedMedia)
|
||||
: i === 0
|
||||
? originals.map((p) => carriedRunsOf(p, emittedMedia)).join('')
|
||||
: ''
|
||||
return `<w:p>${pPrOf(template)}${emitted}${keep}</w:p>`
|
||||
})
|
||||
.join('')
|
||||
return openTag + tcPr + body + '</w:tc>'
|
||||
}
|
||||
|
||||
/** per-cell patch: plain paragraph strings, or nested-table cell texts by nested index */
|
||||
/** cell paragraph texts carry tabs/breaks as control chars (extractRuns encoding);
|
||||
* they must go back as real elements, not literal characters inside w:t */
|
||||
function cellRunContentXml(text: string): string {
|
||||
const CONTROL: Record<string, string> = {
|
||||
'\t': '<w:tab/>',
|
||||
'\n': '<w:br/>',
|
||||
'\f': '<w:br w:type="page"/>',
|
||||
'\v': '<w:br w:type="column"/>',
|
||||
}
|
||||
return text
|
||||
.split(/([\t\n\f\v])/)
|
||||
.map((seg) =>
|
||||
seg === '' ? '' : (CONTROL[seg] ?? `<w:t xml:space="preserve">${escapeXmlText(seg)}</w:t>`),
|
||||
)
|
||||
.join('')
|
||||
}
|
||||
|
||||
/** one cell paragraph: control-char text (legacy first-run-rPr rebuild), rich runs, or null = keep the original paragraph bytes */
|
||||
export type CellParaPatch = string | { runs: Run[] } | null
|
||||
|
||||
/** per-cell patch: paragraph patches, or nested-table cell texts by nested index */
|
||||
export type CellTextsPatch =
|
||||
| readonly string[]
|
||||
| readonly CellParaPatch[]
|
||||
| {
|
||||
/** this cell's own text (optional; rewriting the outer text of a cell containing a nested table is not supported yet) */
|
||||
paras?: readonly string[] | null
|
||||
@@ -2387,11 +2460,12 @@ function mergeRFontsXml(rawXml: string, run: Run): string {
|
||||
attrs.set(slot, escapeXmlAttr(value))
|
||||
attrs.delete(theme)
|
||||
}
|
||||
if (run.fontAscii) {
|
||||
// slots still equal to their theme-resolved value are untouched: keep the theme attrs
|
||||
if (run.fontAscii && run.fontAscii !== run.themeRFonts?.fontAscii) {
|
||||
set('w:ascii', 'w:asciiTheme', run.fontAscii)
|
||||
set('w:hAnsi', 'w:hAnsiTheme', run.fontAscii)
|
||||
}
|
||||
if (run.font && (hadEastAsia || run.font !== rawPrimary)) {
|
||||
if (run.font && run.font !== run.themeRFonts?.font && (hadEastAsia || run.font !== rawPrimary)) {
|
||||
set('w:eastAsia', 'w:eastAsiaTheme', run.font)
|
||||
}
|
||||
if (run.fontCs) set('w:cs', 'w:cstheme', run.fontCs)
|
||||
@@ -2519,9 +2593,13 @@ export function mergeRPrModel(rawRPr: string, run: Run, insideLink: boolean): st
|
||||
// Runs drop unmodeled fields, and losing w:cs on an unrelated edit
|
||||
// would corrupt complex-script runs (mergeRFontsXml likewise only
|
||||
// writes w:cs when the model carries one)
|
||||
// a model value resolved from a theme ref counts as untouched: the literal
|
||||
// attrs can never equal it, and rebuilding would materialize the theme link
|
||||
return (
|
||||
(rawAttr(attrs, 'w:eastAsia') ?? ascii) === run.font &&
|
||||
ascii === run.fontAscii &&
|
||||
((rawAttr(attrs, 'w:eastAsia') ?? ascii) === run.font ||
|
||||
(run.font !== undefined && run.font === run.themeRFonts?.font)) &&
|
||||
(ascii === run.fontAscii ||
|
||||
(run.fontAscii !== undefined && run.fontAscii === run.themeRFonts?.fontAscii)) &&
|
||||
(run.fontCs === undefined || rawAttr(attrs, 'w:cs') === run.fontCs)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ export {
|
||||
buildLineParagraphXml,
|
||||
LINE_KINDS,
|
||||
type TextboxSizePatch,
|
||||
type CellParaPatch,
|
||||
type CellTextsPatch,
|
||||
type FieldTextPatch,
|
||||
type GenerateContext,
|
||||
|
||||
@@ -70,10 +70,40 @@ export function parseNotesXml(xml: string, kind: NoteKind): NoteInfo[] {
|
||||
r.bold || r.italic || r.underline || r.strike || r.color || r.sizeHalfPoints || r.caps,
|
||||
),
|
||||
)
|
||||
return { id, text, ...(hasFormat ? { richParas } : {}) }
|
||||
const styleId = /<w:pStyle w:val="([^"]+)"/.exec(entryXml)?.[1]
|
||||
const spacing = noteDirectSpacing(entryXml)
|
||||
return {
|
||||
id,
|
||||
text,
|
||||
...(hasFormat ? { richParas } : {}),
|
||||
...(styleId ? { styleId } : {}),
|
||||
...(spacing ? { spacing } : {}),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** direct w:spacing attrs of the first note paragraph (they override the style chain) */
|
||||
function noteDirectSpacing(entryXml: string): NoteInfo['spacing'] {
|
||||
const pPr = /<w:pPr>[\s\S]*?<\/w:pPr>/.exec(entryXml)?.[0]
|
||||
const sp = pPr && /<w:spacing [^>]*\/>/.exec(pPr)?.[0]
|
||||
if (!sp) return undefined
|
||||
const num = (attr: string): number | undefined => {
|
||||
const v = new RegExp(`w:${attr}="(-?\\d+)"`).exec(sp)?.[1]
|
||||
return v === undefined ? undefined : parseInt(v, 10)
|
||||
}
|
||||
const rule = /w:lineRule="(auto|atLeast|exact)"/.exec(sp)?.[1] as
|
||||
'auto' | 'atLeast' | 'exact' | undefined
|
||||
const before = num('before')
|
||||
const after = num('after')
|
||||
const line = num('line')
|
||||
if (before === undefined && after === undefined && line === undefined) return undefined
|
||||
return {
|
||||
...(before !== undefined ? { beforeTwips: before } : {}),
|
||||
...(after !== undefined ? { afterTwips: after } : {}),
|
||||
...(line !== undefined ? { lineRawTwips: line, lineRule: rule ?? 'auto' } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Display runs per paragraph (bold/italic/underline/strike, color, size); the footnote self-reference mark run is skipped */
|
||||
function noteRichParas(entryXml: string): NoteRun[][] {
|
||||
const out: NoteRun[][] = []
|
||||
|
||||
@@ -1324,6 +1324,25 @@ function headingLevelOf(
|
||||
return m ? parseInt(m[1], 10) : undefined
|
||||
}
|
||||
|
||||
const defaultParaVanishCache = new WeakMap<Map<string, StyleInfo>, boolean>()
|
||||
|
||||
/** Default paragraph style's w:vanish (cached per styles map): inherited by style-less paragraphs */
|
||||
function defaultParaVanish(styles?: Map<string, StyleInfo>): boolean | undefined {
|
||||
if (!styles) return undefined
|
||||
let v = defaultParaVanishCache.get(styles)
|
||||
if (v === undefined) {
|
||||
v = false
|
||||
for (const info of styles.values()) {
|
||||
if (info.isDefault && info.type === 'paragraph') {
|
||||
v = info.display?.vanish === true
|
||||
break
|
||||
}
|
||||
}
|
||||
defaultParaVanishCache.set(styles, v)
|
||||
}
|
||||
return v || undefined
|
||||
}
|
||||
|
||||
/** No run un-hides itself and nothing anchors here (bookmarks, comments, sectPr,
|
||||
* drawings, numbering): safe to collapse a style-vanished paragraph entirely */
|
||||
function staysVanished(xml: string): boolean {
|
||||
@@ -1373,6 +1392,12 @@ function buildTextParagraph(
|
||||
if (styleId && ctx.styles.get(styleId)?.display?.vanish === true && staysVanished(xml)) {
|
||||
return { ...base, type: 'passthrough', label: 'Hidden paragraph', invisibleMarker: true }
|
||||
}
|
||||
// style-less paragraph under a vanish-carrying default paragraph style: the
|
||||
// mark inherits hidden, so Word gives the line no height (real_run2/93's
|
||||
// trailing paragraph pushed a phantom second page)
|
||||
if (!styleId && defaultParaVanish(ctx.styles) === true && staysVanished(xml)) {
|
||||
return { ...base, type: 'passthrough', label: 'Hidden paragraph', invisibleMarker: true }
|
||||
}
|
||||
// empty paragraph whose mark is hidden by direct w:vanish (label/card
|
||||
// templates end on one): Word gives it no height — rendering it as a normal
|
||||
// empty line can push a trailing blank page
|
||||
@@ -3391,6 +3416,10 @@ function extractParaFormat(pPr: XNode): ParaFormat | undefined {
|
||||
if (shd) {
|
||||
const fill = attrsOf(shd)['w:fill']
|
||||
if (fill && fill !== 'auto') format.shadingFill = stripHash(fill)
|
||||
// pattern shading (pctNN/stripes): white 20pt text on w:shd pct70 was
|
||||
// invisible with the fill-only read (real_run2/61 Font Cascade)
|
||||
const display = shdDisplayFill(shd)
|
||||
if (display && display !== format.shadingFill) format.shadingDisplay = display
|
||||
}
|
||||
const pBdrs = findChildren(pPr, 'w:pBdr')
|
||||
if (pBdrs.length > 0) {
|
||||
@@ -3557,6 +3586,12 @@ function extractRuns(
|
||||
// paragraph-style rtl inherits into runs without their own flag
|
||||
const pStyleId = attrsOf(findChild(findChild(pNode, 'w:pPr') ?? {}, 'w:pStyle') ?? {})['w:val']
|
||||
const paraRtl = pStyleId ? ctx.styles?.get(pStyleId)?.display?.rtl : undefined
|
||||
// paragraph-style hidden text (w:vanish) inherits into runs without their own
|
||||
// flag; style-less paragraphs read the default paragraph style (real_run2/93:
|
||||
// a default style carrying vanish hides every run without an explicit off)
|
||||
const paraVanish = pStyleId
|
||||
? ctx.styles?.get(pStyleId)?.display?.vanish
|
||||
: defaultParaVanish(ctx.styles)
|
||||
// Comments are only tracked when the whole range lives inside this paragraph:
|
||||
// a regenerated paragraph can then re-emit its own markers, while ranges that
|
||||
// span paragraphs are left untouched (their runs get no commentIds).
|
||||
@@ -3683,6 +3718,7 @@ function extractRuns(
|
||||
ctx.styles,
|
||||
paraRtl,
|
||||
ctx.xmlSpacePreserve,
|
||||
paraVanish,
|
||||
)
|
||||
if (cached) {
|
||||
fieldCached += cached.text
|
||||
@@ -3738,6 +3774,7 @@ function extractRuns(
|
||||
ctx.styles,
|
||||
paraRtl,
|
||||
ctx.xmlSpacePreserve,
|
||||
paraVanish,
|
||||
)
|
||||
if (run) pushRun(run, rev)
|
||||
}
|
||||
@@ -3893,7 +3930,14 @@ function themeLangEaSlotFont(fonts: ThemeFonts, eaRef: string | undefined): stri
|
||||
function themedRFonts(
|
||||
attrs: Record<string, string | undefined>,
|
||||
fonts: ThemeFonts | null | undefined,
|
||||
): { ascii?: string; hAnsi?: string; eastAsia?: string; cs?: string; eaSlotEmpty?: boolean } {
|
||||
): {
|
||||
ascii?: string
|
||||
hAnsi?: string
|
||||
eastAsia?: string
|
||||
cs?: string
|
||||
eaSlotEmpty?: boolean
|
||||
themed?: { ascii?: boolean; hAnsi?: boolean; eastAsia?: boolean }
|
||||
} {
|
||||
const themeVal = (ref: string | undefined): string | undefined => {
|
||||
if (!ref || !fonts) return undefined
|
||||
switch (ref) {
|
||||
@@ -3919,12 +3963,19 @@ function themedRFonts(
|
||||
const themedEa = themeVal(eaRef)
|
||||
const eaSlotEmpty =
|
||||
!themedEa && !!fonts && (eaRef === 'majorEastAsia' || eaRef === 'minorEastAsia')
|
||||
const themedAscii = themeVal(attrs['w:asciiTheme'])
|
||||
const themedHAnsi = themeVal(attrs['w:hAnsiTheme'])
|
||||
return {
|
||||
ascii: themeVal(attrs['w:asciiTheme']) ?? attrs['w:ascii'],
|
||||
hAnsi: themeVal(attrs['w:hAnsiTheme']) ?? attrs['w:hAnsi'],
|
||||
ascii: themedAscii ?? attrs['w:ascii'],
|
||||
hAnsi: themedHAnsi ?? attrs['w:hAnsi'],
|
||||
eastAsia: themedEa ?? (eaSlotEmpty ? emptyEaSlotFont(fonts!, eaRef) : attrs['w:eastAsia']),
|
||||
cs: themeVal(attrs['w:cstheme']) ?? attrs['w:cs'],
|
||||
...(eaSlotEmpty ? { eaSlotEmpty } : {}),
|
||||
themed: {
|
||||
ascii: themedAscii !== undefined,
|
||||
hAnsi: themedHAnsi !== undefined,
|
||||
eastAsia: themedEa !== undefined || eaSlotEmpty,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3945,6 +3996,7 @@ function buildRun(
|
||||
styles?: Map<string, StyleInfo>,
|
||||
paraRtl?: boolean,
|
||||
partPreserve?: boolean,
|
||||
paraVanish?: boolean,
|
||||
): Run | null {
|
||||
let text = ''
|
||||
for (const child of childrenOf(rNode)) {
|
||||
@@ -4058,10 +4110,17 @@ function buildRun(
|
||||
if (link) run.link = link
|
||||
// a bare run under an rtl style still selects the Cs set from its style chain
|
||||
if (!rPr && paraRtl) run.cs = true
|
||||
if (!rPr && paraVanish) run.vanish = true
|
||||
if (rPr) {
|
||||
run.rawRPr = serializeXNode(rPr)
|
||||
const rStyle = attrsOf(findChild(rPr, 'w:rStyle') ?? {})['w:val']
|
||||
if (rStyle && rStyle !== 'Hyperlink') run.styleId = rStyle
|
||||
// hidden text: an explicit run w:vanish wins over the character/paragraph
|
||||
// style chain; w:specVanish (style separator) keeps the run visible
|
||||
const vanishOwn = onOffOf(rPr, 'w:specVanish') === true ? undefined : onOffOf(rPr, 'w:vanish')
|
||||
const vanish =
|
||||
vanishOwn ?? (rStyle ? styles?.get(rStyle)?.display?.vanish : undefined) ?? paraVanish
|
||||
if (vanish === true) run.vanish = true
|
||||
// Word picks the whole property set by w:rtl (probed, Word for Mac 2026-08):
|
||||
// rtl runs read w:bCs/w:iCs/w:szCs with no fallback to w:b/w:i/w:sz; non-rtl
|
||||
// runs read the base props and ignore the Cs twins entirely. Script content
|
||||
@@ -4090,6 +4149,20 @@ function buildRun(
|
||||
if (rf.eaSlotEmpty && font && font === rf.eastAsia) run.eaSlotEmpty = true
|
||||
const fontAscii = rf.ascii ?? rf.hAnsi
|
||||
if (fontAscii) run.fontAscii = fontAscii
|
||||
// record which resolved values came from theme refs (per winning slot)
|
||||
const fontThemed =
|
||||
rf.eastAsia !== undefined
|
||||
? rf.themed?.eastAsia
|
||||
: rf.ascii !== undefined
|
||||
? rf.themed?.ascii
|
||||
: rf.themed?.hAnsi
|
||||
const fontAsciiThemed = rf.ascii !== undefined ? rf.themed?.ascii : rf.themed?.hAnsi
|
||||
if ((fontThemed && font) || (fontAsciiThemed && fontAscii)) {
|
||||
run.themeRFonts = {
|
||||
...(fontThemed && font ? { font } : {}),
|
||||
...(fontAsciiThemed && fontAscii ? { fontAscii } : {}),
|
||||
}
|
||||
}
|
||||
// complex-script slot: literal attribute only — theme refs (w:cstheme) stay in
|
||||
// rawRPr so untouched runs keep their original bytes
|
||||
if (rfAttrs['w:cs']) run.fontCs = rfAttrs['w:cs']
|
||||
@@ -5837,19 +5910,45 @@ function fieldDisplayOf(xml: string, styles?: Map<string, StyleInfo>): FieldDisp
|
||||
// face/size of the visible result runs (same rule as tocLine): without
|
||||
// them the passthrough div inherits the document default and a SimSun
|
||||
// field paragraph mis-snaps to a double cell on a typed line grid
|
||||
let sz = 0
|
||||
// dominant size = the size covering the most text: a manual drop-cap letter
|
||||
// (one 48pt "L" before 10pt body) must not inflate the whole field's strut
|
||||
// (real_run2/47 rendered the entire paragraph at 48pt, 10 -> 17 pages)
|
||||
let font: string | undefined
|
||||
const sizedRuns: Array<{ text: string; szHalfPoints?: number }> = []
|
||||
const szWeights = new Map<number, number>()
|
||||
const runRe = /<w:r(?:\s[^>]*)?>([\s\S]*?)<\/w:r>/g
|
||||
let run: RegExpExecArray | null
|
||||
while ((run = runRe.exec(xml)) !== null) {
|
||||
if (!/<w:t(?:\s|>)/.test(run[1]) || run[1].includes('<w:instrText')) continue
|
||||
const text = decodeEntities(
|
||||
Array.from(run[1].matchAll(/<w:t[^>]*>([\s\S]*?)<\/w:t>/g), (m) => m[1]).join(''),
|
||||
)
|
||||
const v = parseInt(/<w:sz w:val="(\d+)"/.exec(run[1])?.[1] ?? '', 10)
|
||||
if (v > sz) sz = v
|
||||
sizedRuns.push({ text, ...(v > 0 ? { szHalfPoints: v } : {}) })
|
||||
// unsized runs vote for the inherited default (key 0): one explicit
|
||||
// drop-cap letter must not out-vote a body of default-sized text
|
||||
const key = v > 0 ? v : 0
|
||||
szWeights.set(key, (szWeights.get(key) ?? 0) + Math.max(text.length, 1))
|
||||
if (!font) {
|
||||
const fonts = /<w:rFonts [^/>]*/.exec(run[1])?.[0] ?? ''
|
||||
font = /w:eastAsia="([^"]+)"/.exec(fonts)?.[1] ?? /w:ascii="([^"]+)"/.exec(fonts)?.[1]
|
||||
}
|
||||
}
|
||||
let sz = 0
|
||||
let szWeight = -1
|
||||
for (const [v, w] of szWeights) {
|
||||
if (w > szWeight || (w === szWeight && v > sz)) {
|
||||
sz = v
|
||||
szWeight = w
|
||||
}
|
||||
}
|
||||
// sized spans only for mixed sizes, and only when the runs reproduce the
|
||||
// visible text (tabs/breaks fall back to the plain string)
|
||||
const norm = (t: string) => t.replace(/\s+/g, ' ').trim()
|
||||
const mixedRuns =
|
||||
szWeights.size > 1 && norm(sizedRuns.map((r) => r.text).join('')) === norm(visible)
|
||||
? sizedRuns.filter((r) => r.text !== '')
|
||||
: undefined
|
||||
// explicit paragraph alignment: the passthrough div would inherit the
|
||||
// document default (justify in CJK docs) and stretch short lines
|
||||
const pPr = /<w:pPr>[\s\S]*?<\/w:pPr>/.exec(xml)?.[0] ?? ''
|
||||
@@ -5872,6 +5971,7 @@ function fieldDisplayOf(xml: string, styles?: Map<string, StyleInfo>): FieldDisp
|
||||
kind: 'text',
|
||||
left: visible,
|
||||
...(sz > 0 ? { szHalfPoints: sz } : {}),
|
||||
...(mixedRuns ? { runs: mixedRuns } : {}),
|
||||
...(font ? { fontFamily: font } : {}),
|
||||
...(align ? { align } : {}),
|
||||
...(line > 0 && lineRule
|
||||
@@ -7366,8 +7466,8 @@ function styleDisplayOf(
|
||||
const jc = attrsOf(findChild(pPr, 'w:jc') ?? {})['w:val']
|
||||
if (jc === 'center' || jc === 'right' || jc === 'left' || jc === 'justify') display.align = jc
|
||||
else if (jc === 'both' || jc === 'distribute') display.align = 'justify'
|
||||
const shdFill = attrsOf(findChild(pPr, 'w:shd') ?? {})['w:fill']
|
||||
if (shdFill && shdFill !== 'auto') display.shadingFill = stripHash(shdFill)
|
||||
const shdDisp = shdDisplayFill(findChild(pPr, 'w:shd'))
|
||||
if (shdDisp) display.shadingFill = shdDisp
|
||||
const stops = tabStopsOf(pPr)
|
||||
if (stops) display.tabStops = stops
|
||||
const ind = findChild(pPr, 'w:ind')
|
||||
|
||||
@@ -37,6 +37,9 @@ export interface Run {
|
||||
fontAscii?: string
|
||||
/** complex-script-slot font (w:rFonts w:cs, literal attribute only — theme refs stay in rawRPr) */
|
||||
fontCs?: string
|
||||
/** font/fontAscii values that were resolved from theme refs at parse time; generate
|
||||
* treats model == resolved as untouched so the raw theme attrs are not materialized */
|
||||
themeRFonts?: { font?: string; fontAscii?: string }
|
||||
/** Complex-script font (w:rFonts cs/cstheme, theme-resolved). Display only; saving is kept faithful by rawRPr */
|
||||
csFont?: string
|
||||
/** right-to-left run (w:rtl): text stored in logical order, rendered RTL */
|
||||
@@ -45,6 +48,10 @@ export interface Run {
|
||||
charSpacingTwips?: number
|
||||
/** w:caps ('all') / w:smallCaps ('small') display transform, 'none' = explicit off. Display only; saving is kept faithful by rawRPr */
|
||||
caps?: 'all' | 'small' | 'none'
|
||||
/** w:vanish hidden text, resolved through the style chain at parse (an explicit
|
||||
* run value wins; w:specVanish style separators stay visible). Display only;
|
||||
* saving is kept faithful by rawRPr */
|
||||
vanish?: boolean
|
||||
/** Horizontal character scale percent (w:w). Display only (approximated as spacing); saving is kept faithful by rawRPr */
|
||||
charScalePct?: number
|
||||
/** OOXML named highlight color (w:highlight), e.g. "yellow" */
|
||||
@@ -303,6 +310,10 @@ export interface ParaFormat {
|
||||
contextualSpacing?: boolean
|
||||
/** paragraph shading fill, hex without '#' (w:shd w:fill) */
|
||||
shadingFill?: string
|
||||
/** display-only blend for pattern shading (w:shd pctNN/stripes over the fill):
|
||||
* drives the rendered background; never written back — the raw w:shd
|
||||
* round-trips through shadingFill */
|
||||
shadingDisplay?: string
|
||||
/** paragraph borders, subset of "tblr" e.g. "b" or "tblr" (w:pBdr, single lines) */
|
||||
borders?: string
|
||||
/**
|
||||
@@ -573,6 +584,15 @@ export interface NoteInfo {
|
||||
text: string
|
||||
/** rich display runs (one group per paragraph); gone when an edit rebuilds the note as plain text */
|
||||
richParas?: NoteRun[][]
|
||||
/** w:pStyle of the first note paragraph (notes without one render with Normal metrics) */
|
||||
styleId?: string
|
||||
/** direct w:spacing of the first note paragraph (overrides the style chain) */
|
||||
spacing?: {
|
||||
beforeTwips?: number
|
||||
afterTwips?: number
|
||||
lineRule?: 'auto' | 'atLeast' | 'exact'
|
||||
lineRawTwips?: number
|
||||
}
|
||||
}
|
||||
|
||||
/** Display/edit model for a protected field paragraph. */
|
||||
@@ -594,6 +614,9 @@ export interface FieldDisplay {
|
||||
szHalfPoints?: number
|
||||
/** face of the visible result runs (text fields): drives the line factor */
|
||||
fontFamily?: string
|
||||
/** per-run sizes for mixed-size text fields (a manual drop-cap letter next to
|
||||
* body text): rendered as sized spans; szHalfPoints keeps the dominant size */
|
||||
runs?: Array<{ text: string; szHalfPoints?: number }>
|
||||
/** explicit paragraph alignment (text fields): overrides the doc default */
|
||||
align?: 'left' | 'center' | 'right'
|
||||
lineRule?: 'auto' | 'atLeast' | 'exact'
|
||||
|
||||
@@ -429,3 +429,38 @@ describe('field cached results in table cells', () => {
|
||||
expect(text).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mixed-size text fields (manual drop cap)', () => {
|
||||
const DROPCAP_FIELD_PARAGRAPH =
|
||||
'<w:p>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> INCLUDEPICTURE "/tmp/x.jpeg" \\* MERGEFORMATINET </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'<w:r><w:rPr><w:sz w:val="96"/></w:rPr><w:t>L</w:t></w:r>' +
|
||||
'<w:r><w:t>ight. Living give. Rule grass light.</w:t></w:r></w:p>'
|
||||
|
||||
it('one oversized letter does not set the whole field size; runs carry per-run sizes', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: DROPCAP_FIELD_PARAGRAPH }))
|
||||
const field = doc.blocks[0].fieldDisplay!
|
||||
expect(field.kind).toBe('text')
|
||||
// dominant size = the inherited default (body text outweighs the cap letter)
|
||||
expect(field.szHalfPoints).toBeUndefined()
|
||||
expect(field.runs).toEqual([
|
||||
{ text: 'L', szHalfPoints: 96 },
|
||||
{ text: 'ight. Living give. Rule grass light.' },
|
||||
])
|
||||
})
|
||||
|
||||
it('a uniform explicit size keeps the single-size shape (no runs)', async () => {
|
||||
const xml =
|
||||
'<w:p>' +
|
||||
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
|
||||
'<w:r><w:instrText xml:space="preserve"> INCLUDEPICTURE "/tmp/x.jpeg" \\* MERGEFORMATINET </w:instrText></w:r>' +
|
||||
'<w:r><w:fldChar w:fldCharType="end"/></w:r>' +
|
||||
'<w:r><w:rPr><w:sz w:val="24"/></w:rPr><w:t>uniform text</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||
const field = doc.blocks[0].fieldDisplay!
|
||||
expect(field.szHalfPoints).toBe(24)
|
||||
expect(field.runs).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -132,3 +132,33 @@ describe('empty-paragraph size write-back (pPr w:rPr)', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('pattern shading display blend', () => {
|
||||
it('pct shading over an auto fill yields a display blend without a shadingFill', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:shd w:val="pct40" w:color="auto" w:fill="auto"/></w:pPr>' +
|
||||
'<w:r><w:t>cascade</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const format = doc.blocks[0].format!
|
||||
expect(format.shadingFill).toBeUndefined()
|
||||
expect(format.shadingDisplay).toBe('999999')
|
||||
// the raw pattern round-trips untouched (display is never written back)
|
||||
expect(mergePPrFormat(doc.blocks[0].rawPPr!, format)).toContain(
|
||||
'<w:shd w:val="pct40" w:color="auto" w:fill="auto"/>',
|
||||
)
|
||||
})
|
||||
|
||||
it('a plain clear fill sets no display blend', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:pPr>' +
|
||||
'<w:r><w:t>plain</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const format = doc.blocks[0].format!
|
||||
expect(format.shadingFill).toBe('D9D9D9')
|
||||
expect(format.shadingDisplay).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -425,3 +425,63 @@ describe('run-level character shading (w:shd)', () => {
|
||||
expect(fresh).toContain('<w:shd w:val="clear" w:color="auto" w:fill="00B050"/>')
|
||||
})
|
||||
})
|
||||
|
||||
// rFonts theme refs: parse resolves w:asciiTheme/w:eastAsiaTheme to literal font
|
||||
// names for the model; regeneration must not materialize the refs into literals
|
||||
const THEME_XML =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office">' +
|
||||
'<a:themeElements><a:fontScheme name="Office">' +
|
||||
'<a:majorFont><a:latin typeface="Calibri Light"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont>' +
|
||||
'<a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont>' +
|
||||
'</a:fontScheme></a:themeElements></a:theme>'
|
||||
|
||||
const THEMED_RFONTS = '<w:rFonts w:ascii="Georgia" w:eastAsiaTheme="minorHAnsi" w:hAnsi="Georgia"/>'
|
||||
const THEMED_PARA = `<w:p><w:r><w:rPr>${THEMED_RFONTS}</w:rPr><w:t>themed</w:t></w:r></w:p>`
|
||||
|
||||
async function parseThemed() {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: THEMED_PARA,
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/theme/theme1.xml',
|
||||
xml: THEME_XML,
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.theme+xml',
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
return doc.blocks[0].runs![0]
|
||||
}
|
||||
|
||||
describe('rFonts theme refs survive regeneration', () => {
|
||||
it('parse resolves the ref and records its theme origin', async () => {
|
||||
const run = await parseThemed()
|
||||
expect(run.font).toBe('Calibri')
|
||||
expect(run.fontAscii).toBe('Georgia')
|
||||
expect(run.themeRFonts).toEqual({ font: 'Calibri' })
|
||||
})
|
||||
|
||||
it('a text-only edit keeps the theme attrs instead of materializing them', async () => {
|
||||
const run = await parseThemed()
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, text: 'edited' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain(THEMED_RFONTS)
|
||||
expect(xml).not.toContain('w:eastAsia="Calibri"')
|
||||
})
|
||||
|
||||
it('a real font edit still materializes the touched slot', async () => {
|
||||
const run = await parseThemed()
|
||||
const xml = generateParagraphXml(
|
||||
{ type: 'paragraph', runs: [{ ...run, font: 'Arial' }] },
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(xml).toContain('w:eastAsia="Arial"')
|
||||
expect(xml).not.toContain('w:eastAsiaTheme')
|
||||
// untouched Latin slot keeps its literal value
|
||||
expect(xml).toContain('w:ascii="Georgia"')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const STYLES =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:style w:type="paragraph" w:styleId="HiddenPara"><w:name w:val="HiddenPara"/>' +
|
||||
'<w:rPr><w:vanish/></w:rPr></w:style>' +
|
||||
'<w:style w:type="character" w:styleId="HiddenChar"><w:name w:val="HiddenChar"/>' +
|
||||
'<w:rPr><w:vanish/></w:rPr></w:style>' +
|
||||
'</w:styles>'
|
||||
|
||||
const DEFAULT_VANISH_STYLES =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
||||
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:style w:type="paragraph" w:default="1" w:styleId="Normlny"><w:name w:val="Normlny"/>' +
|
||||
'<w:rPr><w:vanish/></w:rPr></w:style>' +
|
||||
'</w:styles>'
|
||||
|
||||
const runsOf = async (bodyXml: string) => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml, stylesXml: STYLES }))
|
||||
return doc.blocks[0].runs!
|
||||
}
|
||||
|
||||
describe('run-level hidden text (w:vanish)', () => {
|
||||
it('an explicit run vanish hides the run', async () => {
|
||||
const runs = await runsOf(
|
||||
'<w:p><w:r><w:t>shown</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:vanish/></w:rPr><w:t>hidden</w:t></w:r></w:p>',
|
||||
)
|
||||
expect(runs.map((r) => [r.text, r.vanish ?? false])).toEqual([
|
||||
['shown', false],
|
||||
['hidden', true],
|
||||
])
|
||||
})
|
||||
|
||||
it('w:specVanish (style separator) stays visible', async () => {
|
||||
const runs = await runsOf(
|
||||
'<w:p><w:r><w:rPr><w:vanish/><w:specVanish/></w:rPr><w:t>separator</w:t></w:r></w:p>',
|
||||
)
|
||||
expect(runs[0].vanish).toBeUndefined()
|
||||
})
|
||||
|
||||
it('a paragraph style vanish inherits into runs; an explicit off un-hides', async () => {
|
||||
const runs = await runsOf(
|
||||
'<w:p><w:pPr><w:pStyle w:val="HiddenPara"/></w:pPr>' +
|
||||
'<w:r><w:t>inherited hidden</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:vanish w:val="0"/></w:rPr><w:t>unhidden</w:t></w:r></w:p>',
|
||||
)
|
||||
expect(runs.map((r) => [r.text, r.vanish ?? false])).toEqual([
|
||||
['inherited hidden', true],
|
||||
['unhidden', false],
|
||||
])
|
||||
})
|
||||
|
||||
it('a vanish-carrying default paragraph style hides style-less runs (form docs)', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:t>inherited hidden</w:t></w:r>' +
|
||||
'<w:r><w:rPr><w:vanish w:val="0"/></w:rPr><w:t>unhidden</w:t></w:r></w:p>',
|
||||
stylesXml: DEFAULT_VANISH_STYLES,
|
||||
}),
|
||||
)
|
||||
expect(doc.blocks[0].runs!.map((r) => [r.text, r.vanish ?? false])).toEqual([
|
||||
['inherited hidden', true],
|
||||
['unhidden', false],
|
||||
])
|
||||
})
|
||||
|
||||
it('a character style vanish inherits into its runs', async () => {
|
||||
const runs = await runsOf(
|
||||
'<w:p><w:r><w:rPr><w:rStyle w:val="HiddenChar"/></w:rPr><w:t>char hidden</w:t></w:r>' +
|
||||
'<w:r><w:t>plain</w:t></w:r></w:p>',
|
||||
)
|
||||
expect(runs.map((r) => [r.text, r.vanish ?? false])).toEqual([
|
||||
['char hidden', true],
|
||||
['plain', false],
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -479,3 +479,117 @@ describe('trailing empty cell paragraph size survives regeneration', () => {
|
||||
expect(out).toContain('<w:pPr><w:rPr><w:sz w:val="2"/><w:szCs w:val="2"/></w:rPr></w:pPr>')
|
||||
})
|
||||
})
|
||||
|
||||
// rich cell paragraph patches: per-run formatting and hyperlinks survive a cell
|
||||
// edit; null paragraph entries keep the original bytes untouched
|
||||
const LINK_TABLE_XML =
|
||||
'<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/></w:tblPr>' +
|
||||
'<w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||
'<w:tr><w:tc>' +
|
||||
'<w:p><w:r><w:t xml:space="preserve">contact </w:t></w:r>' +
|
||||
'<w:hyperlink r:id="rId7"><w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>mail me</w:t></w:r></w:hyperlink></w:p>' +
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>second</w:t></w:r></w:p>' +
|
||||
'</w:tc></w:tr></w:tbl>'
|
||||
|
||||
describe('patchTableCellTexts with rich paragraphs', () => {
|
||||
it('keeps the hyperlink wrapper and rId on a real cell edit', () => {
|
||||
const out = patchTableCellTexts(LINK_TABLE_XML, [
|
||||
[
|
||||
[
|
||||
{
|
||||
runs: [
|
||||
{ text: 'contactX ' },
|
||||
{ text: 'mail me', underline: true, link: { href: 'mailto:x@y.z', rId: 'rId7' } },
|
||||
],
|
||||
},
|
||||
null,
|
||||
],
|
||||
],
|
||||
])
|
||||
expect(out).toContain('<w:hyperlink r:id="rId7">')
|
||||
expect(out).toContain('<w:t xml:space="preserve">contactX </w:t>')
|
||||
expect(out).toContain('<w:u w:val="single"/>')
|
||||
// the untouched second paragraph keeps its exact original bytes
|
||||
expect(out).toContain(
|
||||
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>second</w:t></w:r></w:p>',
|
||||
)
|
||||
})
|
||||
|
||||
it('a rebuilt paragraph reuses its own pPr, not the first paragraph’s', () => {
|
||||
const out = patchTableCellTexts(LINK_TABLE_XML, [
|
||||
[[null, { runs: [{ text: 'second edited', italic: true }] }]],
|
||||
])
|
||||
// first paragraph untouched
|
||||
expect(out).toContain('<w:hyperlink r:id="rId7">')
|
||||
expect(out).toContain('<w:t>mail me</w:t>')
|
||||
// second paragraph keeps centered pPr and italic run
|
||||
expect(out).toMatch(
|
||||
/<w:p><w:pPr><w:jc w:val="center"\/><\/w:pPr><w:r><w:rPr><w:i\/><w:iCs\/><\/w:rPr><w:t xml:space="preserve">second edited<\/w:t><\/w:r><\/w:p>/,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('rich cell patch drawing carryover', () => {
|
||||
it('does not duplicate an image whose VML fallback shares the rId', () => {
|
||||
const tbl =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>' +
|
||||
'<w:p><w:r><w:t>caption</w:t></w:r>' +
|
||||
'<w:r><mc:AlternateContent><mc:Choice Requires="wps">' +
|
||||
'<w:drawing><wp:inline><a:blip r:embed="rId5"/></wp:inline></w:drawing>' +
|
||||
'</mc:Choice><mc:Fallback><w:pict><v:shape><v:imagedata r:id="rId5"/></v:shape></w:pict></mc:Fallback></mc:AlternateContent></w:r>' +
|
||||
'</w:p></w:tc></w:tr></w:tbl>'
|
||||
const out = patchTableCellTexts(tbl, [
|
||||
[
|
||||
[
|
||||
{
|
||||
runs: [
|
||||
{ text: 'captionX' },
|
||||
{
|
||||
text: '',
|
||||
image: {
|
||||
dataUrl: 'data:image/png;base64,x',
|
||||
xml: '<w:drawing><wp:inline><a:blip r:embed="rId5"/></wp:inline></w:drawing>',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
],
|
||||
])
|
||||
expect(out.match(/rId5/g)?.length).toBe(1)
|
||||
expect(out).not.toContain('<w:pict')
|
||||
expect(out).toContain('captionX')
|
||||
})
|
||||
|
||||
it('carries a media-less anchored shape over, keeping its textbox content', () => {
|
||||
const tbl =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>' +
|
||||
'<w:p><w:r><w:t>label</w:t></w:r>' +
|
||||
'<w:r><w:t>ghost</w:t><w:drawing><wp:anchor><wps:wsp><wps:txbx>' +
|
||||
'<w:txbxContent><w:p><w:r><w:t>inside box</w:t></w:r></w:p></w:txbxContent>' +
|
||||
'</wps:txbx></wps:wsp></wp:anchor></w:drawing></w:r>' +
|
||||
'</w:p></w:tc></w:tr></w:tbl>'
|
||||
const out = patchTableCellTexts(tbl, [[[{ runs: [{ text: 'labelX' }, { text: 'ghost' }] }]]])
|
||||
expect(out.match(/<wp:anchor/g)?.length).toBe(1)
|
||||
// run-level text is not replayed by the carried copy (the rich runs own it) …
|
||||
expect(out.match(/ghost/g)?.length).toBe(1)
|
||||
// … but text nested inside the drawing survives
|
||||
expect(out).toContain('<w:t>inside box</w:t>')
|
||||
expect(out).toContain('labelX')
|
||||
})
|
||||
|
||||
it('keeps a shape whose click-link shares an rId with an emitted hyperlink', () => {
|
||||
const tbl =
|
||||
'<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>' +
|
||||
'<w:p><w:hyperlink r:id="rId7"><w:r><w:t>site</w:t></w:r></w:hyperlink>' +
|
||||
'<w:r><w:drawing><wp:anchor><wps:wsp><a:hlinkClick r:id="rId7"/></wps:wsp></wp:anchor></w:drawing></w:r>' +
|
||||
'</w:p></w:tc></w:tr></w:tbl>'
|
||||
const out = patchTableCellTexts(tbl, [
|
||||
[[{ runs: [{ text: 'siteX', link: { href: 'https://x.y', rId: 'rId7' } }] }]],
|
||||
])
|
||||
expect(out).toContain('<w:hyperlink r:id="rId7">')
|
||||
// the shape is not a picture twin: relationship reuse must not drop it
|
||||
expect(out.match(/<wp:anchor/g)?.length).toBe(1)
|
||||
expect(out).toContain('<a:hlinkClick r:id="rId7"/>')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user