Sync snapshot (2026-08-23) (#130)

- Convert scanned PDFs to editable text with local OCR, running through the operating system's own engine on macOS and Windows
- Add a much richer AI workflow to Docs, PDF, and Markdown: selection-scoped questions, batched edits, character-level edits, comment and tracked-change awareness, citations back to the source block, and in-document image generation
- Let Slides open the same presentation in a second window and edit it from both
- Improve PDF to Excel table recovery: tables spanning pages merge into one worksheet, and label/value grids and rule-less statement bands become real rows
- Fix a large wave of Word layout fidelity in Docs, Excel parity in Sheets, and PowerPoint import fidelity in Slides

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-08-23 23:10:02 +08:00
committed by GitHub
co-authored by GenOffice
parent f68df70e22
commit 6d9b6812dd
372 changed files with 34693 additions and 3274 deletions
+1
View File
@@ -17,6 +17,7 @@
"fixtures": "tsx scripts/generate-fixtures.ts"
},
"dependencies": {
"@genoffice/pptx-engine": "*",
"fast-xml-parser": "^5.3.4",
"jszip": "^3.10.1",
"utif2": "^4.1.0"
+34
View File
@@ -0,0 +1,34 @@
import type { FontTableEntry } from './types'
import { attrsOf, childrenOf, findChild, nameOf, xmlParser, type XNode } from './xml-utils'
export const FONT_TABLE_PART_PATH = 'word/fontTable.xml'
/** word/fontTable.xml → substitution hints (altName / PANOSE / family / pitch) */
export function parseFontTable(xml: string): FontTableEntry[] {
let parsed: XNode[]
try {
parsed = xmlParser.parse(xml) as XNode[]
} catch {
return []
}
const root = parsed.find((n) => nameOf(n) === 'w:fonts')
if (!root) return []
const out: FontTableEntry[] = []
for (const node of childrenOf(root)) {
if (nameOf(node) !== 'w:font') continue
const name = attrsOf(node)['w:name']
if (!name) continue
const val = (tag: string) => attrsOf(findChild(node, tag) ?? {})['w:val'] || undefined
const entry: FontTableEntry = { name }
const altName = val('w:altName')
if (altName) entry.altName = altName
const panose = val('w:panose1')
if (panose) entry.panose = panose
const family = val('w:family')
if (family) entry.family = family
const pitch = val('w:pitch')
if (pitch) entry.pitch = pitch
out.push(entry)
}
return out
}
+150 -50
View File
@@ -316,11 +316,28 @@ export function patchFieldParagraphXml(xml: string, patch: FieldTextPatch): stri
const nodes = textNodes(xml, 'w:t')
if (nodes.length === 0) return xml
// run-level tab only (attribute-less CT_Empty) — `<w:tab w:val=…/>` inside
// w:tabs is a tab-stop definition and must not split the left/right texts
const tabIndex = xml.search(/<w:tab\/>/)
if (patch.right !== undefined && tabIndex === -1) return xml
const leftNodes = tabIndex === -1 ? nodes : nodes.filter((node) => node.start < tabIndex)
const rightNodes = tabIndex === -1 ? [] : nodes.filter((node) => node.start > tabIndex)
// w:tabs is a tab-stop definition and must not split the left/right texts.
// Mirrors fieldDisplayOf: the page number follows the LAST tab, and a short
// space-free first segment before ≥2 tabs is the outline-number cell (not
// part of the editable title).
const tabStarts: number[] = []
const tabRe = /<w:tab\/>/g
let tabMatch: RegExpExecArray | null
while ((tabMatch = tabRe.exec(xml)) !== null) tabStarts.push(tabMatch.index)
const lastTab = tabStarts.length > 0 ? tabStarts[tabStarts.length - 1] : -1
if (patch.right !== undefined && lastTab === -1) return xml
let leftFrom = -1
if (tabStarts.length >= 2) {
const firstSeg = nodes
.filter((node) => node.start < tabStarts[0])
.map((node) => node.text)
.join('')
.trim()
if (/^\S{1,15}$/.test(firstSeg)) leftFrom = tabStarts[0]
}
const leftNodes =
lastTab === -1 ? nodes : nodes.filter((node) => node.start > leftFrom && node.start < lastTab)
const rightNodes = lastTab === -1 ? [] : nodes.filter((node) => node.start > lastTab)
if (patch.left !== undefined && leftNodes.length === 0) return xml
if (patch.right !== undefined && rightNodes.length === 0) return xml
@@ -580,49 +597,99 @@ function patchTxbxContent(
}
/**
* Replace textbox paragraphs inside a paragraph fragment that carries
* anchored DrawingML textboxes. `boxes[box]` = per-paragraph patches for that
* box (visible-shape order, matching Block.textboxes), or null/undefined to
* leave the box untouched. Word pairs every DrawingML shape with a VML twin
* inside mc:Fallback whose w:txbxContent duplicates the content — fallback
* copies are patched with the same paragraphs as the preceding visible box so
* both renderings stay in sync.
* Text patches for the anchored boxes of one paragraph fragment. `byIndex` is
* sparse, indexed by TextboxDisplay.txbxIndex — the ordinal of the box's
* w:txbxContent among all non-fallback segments, empty ones included, so the
* mapping survives paragraphs that mix text-bearing boxes with ink-only
* shapes. `inject` carries the first text of shapes that have no
* w:txbxContent at all, addressed by their wps:cNvPr id.
*/
export function patchTextboxParas(
paragraphXml: string,
boxes: ReadonlyArray<ReadonlyArray<TextboxParaPatch | null | undefined> | null | undefined>,
): string {
export interface TextboxParasPatchSet {
byIndex?: ReadonlyArray<ReadonlyArray<TextboxParaPatch | null | undefined> | null | undefined>
inject?: ReadonlyArray<{ shapeId: string; paras: TextboxParaPatch[] }>
}
/**
* Replace textbox paragraphs inside a paragraph fragment that carries
* anchored DrawingML textboxes. Word pairs every DrawingML shape with a VML
* twin inside mc:Fallback whose w:txbxContent duplicates the content —
* fallback copies are patched with the same paragraphs as the preceding
* visible box so both renderings stay in sync.
*/
export function patchTextboxParas(paragraphXml: string, patches: TextboxParasPatchSet): string {
const byIndex = patches.byIndex ?? []
const segs = xmlSegments(paragraphXml, 'w:txbxContent', 0, paragraphXml.length)
if (segs.length === 0) return paragraphXml
const fallbacks: Array<{ start: number; end: number }> = []
const fbRe = /<mc:Fallback>[\s\S]*?<\/mc:Fallback>/g
let fb: RegExpExecArray | null
while ((fb = fbRe.exec(paragraphXml)) !== null) {
fallbacks.push({ start: fb.index, end: fb.index + fb[0].length })
}
const inFallback = (pos: number) => fallbacks.some((f) => pos >= f.start && pos < f.end)
let out = ''
let cursor = 0
let boxIndex = -1
let lastVisibleCounted = false
for (const seg of segs) {
const segXml = paragraphXml.slice(seg.start, seg.end)
if (!inFallback(seg.start)) {
// display extraction skips all-empty boxes, so only boxes with text
// consume an index; a fallback twin repeats the preceding visible box
lastVisibleCounted = paraPlainText(segXml) !== ''
if (lastVisibleCounted) boxIndex++
} else if (!lastVisibleCounted) {
continue
let xml = paragraphXml
if (segs.length > 0 && byIndex.length > 0) {
const fallbacks: Array<{ start: number; end: number }> = []
const fbRe = /<mc:Fallback>[\s\S]*?<\/mc:Fallback>/g
let fb: RegExpExecArray | null
while ((fb = fbRe.exec(paragraphXml)) !== null) {
fallbacks.push({ start: fb.index, end: fb.index + fb[0].length })
}
const paras = boxIndex >= 0 && lastVisibleCounted ? boxes[boxIndex] : null
if (paras == null) continue
out += paragraphXml.slice(cursor, seg.start) + patchTxbxContent(segXml, paras)
cursor = seg.end
const inFallback = (pos: number) => fallbacks.some((f) => pos >= f.start && pos < f.end)
let out = ''
let cursor = 0
let ordinal = -1
let current: ReadonlyArray<TextboxParaPatch | null | undefined> | null = null
for (const seg of segs) {
// a fallback twin repeats the preceding visible segment's patch
if (!inFallback(seg.start)) current = byIndex[++ordinal] ?? null
if (current == null) continue
out +=
paragraphXml.slice(cursor, seg.start) +
patchTxbxContent(paragraphXml.slice(seg.start, seg.end), current)
cursor = seg.end
}
xml = out + paragraphXml.slice(cursor)
}
return out + paragraphXml.slice(cursor)
for (const entry of patches.inject ?? []) xml = injectShapeText(xml, entry)
return xml
}
/**
* First text on a shape that has no <w:txbxContent>: inject a fresh wps:txbx
* into the shape carrying the cNvPr id, before wps:bodyPr per the
* CT_WordprocessingShape sequence. Word centers shape text, so a bodyPr
* without an anchor gains anchor="ctr" — matching the editable box's live
* preview. A shape that already has a txbx (stale inject) has its content
* rewritten instead. The VML fallback twin is left alone: only pre-2010 Word
* builds read it, and pairing it up is not worth corrupting on a miss.
*/
function injectShapeText(
paragraphXml: string,
entry: { shapeId: string; paras: TextboxParaPatch[] },
): string {
for (const seg of xmlSegments(paragraphXml, 'wps:wsp', 0, paragraphXml.length)) {
let shapeXml = paragraphXml.slice(seg.start, seg.end)
const id = /<wps:cNvPr\b[^>]*\bid="([^"]+)"/.exec(shapeXml)?.[1]
if (id !== entry.shapeId) continue
if (shapeXml.includes('<wps:txbx')) {
const content = xmlSegments(shapeXml, 'w:txbxContent', 0, shapeXml.length)[0]
if (!content) return paragraphXml
shapeXml =
shapeXml.slice(0, content.start) +
patchTxbxContent(shapeXml.slice(content.start, content.end), entry.paras) +
shapeXml.slice(content.end)
} else {
const body = entry.paras
.map((p) => `<w:p>${pPrWithJc('', p.align)}${runsXml(p.runs, null)}</w:p>`)
.join('')
const txbx = `<wps:txbx><w:txbxContent>${body}</w:txbxContent></wps:txbx>`
const bodyPrAt = shapeXml.search(/<wps:bodyPr[\s/>]/)
shapeXml =
bodyPrAt === -1
? shapeXml.replace('</wps:wsp>', `${txbx}<wps:bodyPr anchor="ctr"/></wps:wsp>`)
: shapeXml.slice(0, bodyPrAt) +
txbx +
shapeXml
.slice(bodyPrAt)
.replace(/<wps:bodyPr\b(?![^>]*\banchor=")/, '<wps:bodyPr anchor="ctr"')
}
return paragraphXml.slice(0, seg.start) + shapeXml + paragraphXml.slice(seg.end)
}
return paragraphXml
}
/** Resize fixed DrawingML textboxes while preserving their anchors and styling. */
@@ -955,10 +1022,16 @@ function paraSpacingXml(format: ParaFormat): string {
if (format.spaceBefore && format.spaceBefore > 0) {
attrs.push(`w:before="${Math.round(format.spaceBefore)}"`)
}
// explicit "0" must be written back: a bare literal would not override a
// style-chain autospacing (Word resolves the attributes independently)
if (format.spaceBeforeAuto !== undefined)
attrs.push(`w:beforeAutospacing="${format.spaceBeforeAuto ? 1 : 0}"`)
// explicit 0 overrides the style's space-after in Word, so it must be written back
if (format.spaceAfter !== undefined && format.spaceAfter >= 0) {
attrs.push(`w:after="${Math.round(format.spaceAfter)}"`)
}
if (format.spaceAfterAuto !== undefined)
attrs.push(`w:afterAutospacing="${format.spaceAfterAuto ? 1 : 0}"`)
if ((format.lineRule === 'exact' || format.lineRule === 'atLeast') && format.lineRawTwips) {
// Exact/at-least line height: write the twips back verbatim (previously only auto was
// recognized, so edited paragraphs lost their line spacing)
@@ -1021,8 +1094,10 @@ function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
if (format.bidi && (jc === 'left' || jc === 'right')) jc = jc === 'left' ? 'right' : 'left'
out.push({ name: 'w:jc', xml: `<w:jc w:val="${jc}"/>` })
}
if (format.tabStops && format.tabStops.length > 0) {
const tabXml = format.tabStops
// rel stops are display-only w:ptab mirrors: never written into w:tabs
const realStops = (format.tabStops ?? []).filter((ts) => !ts.rel)
if (realStops.length > 0) {
const tabXml = realStops
.map((ts) => {
let xml = `<w:tab w:val="${escapeXmlAttr(ts.val)}" w:pos="${ts.pos}"`
if (ts.leader && ts.leader !== 'none') xml += ` w:leader="${escapeXmlAttr(ts.leader)}"`
@@ -1123,6 +1198,10 @@ function rawSpacingUnchanged(raw: string | undefined, f: ParaFormat): boolean {
const fAfter =
f.spaceAfter !== undefined && f.spaceAfter >= 0 ? Math.round(f.spaceAfter) : undefined
if (rawBefore !== fBefore || rawAfter !== fAfter) return false
const rawAuto = (v: string | undefined): boolean | undefined =>
v === undefined ? undefined : v === '1' || v === 'true'
if (rawAuto(rawAttr(raw, 'w:beforeAutospacing')) !== f.spaceBeforeAuto) return false
if (rawAuto(rawAttr(raw, 'w:afterAutospacing')) !== f.spaceAfterAuto) return false
if ((f.lineRule === 'exact' || f.lineRule === 'atLeast') && f.lineRawTwips) {
return line > 0 && rule === f.lineRule && line === Math.round(f.lineRawTwips)
}
@@ -1186,7 +1265,9 @@ function rawPBdrUnchanged(raw: string | undefined, f: ParaFormat): boolean {
return normLines(rawLines) === normLines(f.borderLines)
}
function rawTabsUnchanged(raw: string | undefined, stops: TabStop[]): boolean {
function rawTabsUnchanged(raw: string | undefined, allStops: TabStop[]): boolean {
// display-only w:ptab mirrors are not part of w:tabs
const stops = allStops.filter((s) => !s.rel)
const rawStops: TabStop[] = []
if (raw) {
const inner = raw.replace(/^<w:tabs[^>]*>/, '').replace(/<\/w:tabs>$/, '')
@@ -2671,16 +2752,33 @@ export function buildShapeParagraphXml(opts: {
`<a:ln><a:solidFill><a:srgbClr val="${borderHex}"/></a:solidFill></a:ln>` +
`</wps:spPr>`
// Word centers autoshape text both ways (a survey of 279 Word-authored documents
// puts anchor="ctr" on 72% and w:jc="center" on 74% of them). A text box is the
// opposite case and stays top-left, which is why buildTextboxParagraphXml differs.
const seededPara = `<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t xml:space="preserve"> </w:t></w:r></w:p>`
const txbxPart = opts.withTextbox
? `<wps:txbx><w:txbxContent><w:p><w:r><w:t xml:space="preserve"> </w:t></w:r></w:p></w:txbxContent></wps:txbx>`
? `<wps:txbx><w:txbxContent>${seededPara}</w:txbxContent></wps:txbx>`
: ''
// Gallery shapes carry a style block, and its a:fontRef is what gives them light
// text on the accent fill — Word writes no color on the runs. The fill/line refs
// are inert here because spPr states both explicitly, but CT_ShapeStyle requires
// all four children in this order.
const style =
`<wps:style>` +
`<a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef>` +
`<a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef>` +
`<a:effectRef idx="0"><a:schemeClr val="accent1"/></a:effectRef>` +
`<a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef>` +
`</wps:style>`
const wsp =
`<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">` +
`<wps:cNvSpPr/>` +
spPr +
style +
txbxPart +
`<wps:bodyPr/>` +
`<wps:bodyPr anchor="ctr"/>` +
`</wps:wsp>`
const graphicData =
@@ -2711,8 +2809,10 @@ export function buildShapeParagraphXml(opts: {
const vmlRect =
`<v:rect xmlns:v="urn:schemas-microsoft-com:vml" style="position:absolute;width:${widthEmu / EMU_PER_PT}pt;height:${heightEmu / EMU_PER_PT}pt" filled="t" stroked="t">` +
// The VML twin renders in place of the shape on older Word builds, so it has to
// carry the same centering (v:textbox takes the vertical half as an attribute)
(opts.withTextbox
? `<v:textbox><w:txbxContent><w:p><w:r><w:t xml:space="preserve"> </w:t></w:r></w:p></w:txbxContent></v:textbox>`
? `<v:textbox style="v-text-anchor:middle"><w:txbxContent>${seededPara}</w:txbxContent></v:textbox>`
: '') +
`</v:rect>`
+2
View File
@@ -1,4 +1,5 @@
export * from './types'
export { parseFontTable } from './font-table'
export { parseDocx, styleRunFormat, type ParseExtras } from './parse'
export {
saveDocx,
@@ -46,6 +47,7 @@ export {
type GenerateContext,
type ImagePatch,
type TextboxParaPatch,
type TextboxParasPatchSet,
type TableGenOptions,
type TocEntry,
} from './generate'
+11
View File
@@ -179,6 +179,17 @@ export function computeListMarkerInfos(
const c = counters.get(def.abstractNumId) ?? []
counters.set(def.abstractNumId, c)
// Word: an item at level L instantiates untouched shallower levels at
// their start value, so a later explicit item there increments past it
// ("1.1 Objetivos" before any level-0 item makes the first level-0 "2.")
for (let a = 0; a < lvl; a++) {
if (c[a] !== undefined) continue
const aKey = `${def.numId}:${a}`
if (def.startOverrides[a] !== undefined && !overrideApplied.has(aKey)) {
overrideApplied.add(aKey)
c[a] = def.startOverrides[a]
} else c[a] = def.levels[a]?.start ?? 1
}
const overrideKey = `${def.numId}:${lvl}`
if (def.startOverrides[lvl] !== undefined && !overrideApplied.has(overrideKey)) {
overrideApplied.add(overrideKey)
+15 -4
View File
@@ -32,6 +32,15 @@ function looksLikeEmf(bytes: Uint8Array): boolean {
return dv.getUint32(0, true) === 1 && dv.getUint32(40, true) === 0x464d4520
}
/** placeable-WMF magic, or a standard META_HEADER (type 1/2, HeaderSize 9) */
function looksLikeWmf(bytes: Uint8Array): boolean {
if (bytes.length < 18) return false
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
if (dv.getUint32(0, true) === 0x9ac6cdd7) return true
const type = dv.getUint16(0, true)
return (type === 1 || type === 2) && dv.getUint16(2, true) === 9
}
/**
* Render EMF/WMF (or gzipped EMZ/WMZ) bytes to a PNG data URL via the vendored
* emf-converter. Returns null on parse failure or when no canvas API exists
@@ -46,11 +55,13 @@ export async function metafileToDataUrl(
let u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
if (isGzip(u8)) u8 = await gunzip(u8)
const buffer = u8.slice().buffer
if (!isMetafileMime(mime)) return null
// signature beats the declared mime: HWP-exported docx ship EMF bytes
// under .wmf part names; mime only decides indeterminate bytes
let isEmf: boolean
if (EMF_MIMES.has(mime)) isEmf = true
else if (WMF_MIMES.has(mime)) isEmf = false
else if (EMZ_MIMES.has(mime) || WMZ_MIMES.has(mime)) isEmf = looksLikeEmf(u8)
else return null
if (looksLikeEmf(u8)) isEmf = true
else if (looksLikeWmf(u8)) isEmf = false
else isEmf = EMF_MIMES.has(mime) || EMZ_MIMES.has(mime)
const result = isEmf
? await convertEmfToDataUrl(buffer, { dpiScale: 2 })
: await convertWmfToDataUrl(buffer, { dpiScale: 2 })
File diff suppressed because it is too large Load Diff
+30
View File
@@ -42,6 +42,33 @@ function hasVisiblePageBorder(xml: string): boolean {
})
}
/** Styling details of a visible w:pgBorders box (undefined when no visible side). */
function pageBorderPropsOf(xml: string): SectionSettings['pageBorderProps'] {
const pgBorders = /<w:pgBorders[^>]*\/>|<w:pgBorders[\s\S]*?<\/w:pgBorders>/.exec(xml)?.[0]
if (!pgBorders || !hasVisiblePageBorder(xml)) return undefined
const display = /w:display="(firstPage|notFirstPage)"/.exec(pgBorders)?.[1] as
'firstPage' | 'notFirstPage' | undefined
const offsetFrom = /w:offsetFrom="(page|text)"/.exec(pgBorders)?.[1] as
'page' | 'text' | undefined
let spacePt = 0
let szEighths = 0
let color: string | undefined
for (const side of pgBorders.match(/<w:(?:top|left|bottom|right)\b[^>]*\/?>/g) ?? []) {
const val = /w:val="([^"]*)"/.exec(side)?.[1]
if (!val || val === 'none' || val === 'nil') continue
spacePt = Math.max(spacePt, intAttr(side, 'w:space', 0))
szEighths = Math.max(szEighths, intAttr(side, 'w:sz', 0))
color ??= /w:color="([0-9A-Fa-f]{6})"/.exec(side)?.[1]
}
return {
...(display ? { display } : {}),
...(offsetFrom ? { offsetFrom } : {}),
spacePt,
widthPt: szEighths / 8,
...(color ? { color } : {}),
}
}
/** Page setup from one w:sectPr XML slice. */
export function sectionSettingsFromXml(xml: string): SectionSettings {
const pgSz = /<w:pgSz[^>]*\/?>/.exec(xml)?.[0] ?? ''
@@ -69,6 +96,8 @@ export function sectionSettingsFromXml(xml: string): SectionSettings {
.map((tag) => intAttr(tag, 'w:w', 0))
.filter((w) => w > 0)
const pageBorderProps = pageBorderPropsOf(xml)
return {
pageWidth: intAttr(pgSz, 'w:w', DEFAULT_SECTION.pageWidth),
pageHeight: intAttr(pgSz, 'w:h', DEFAULT_SECTION.pageHeight),
@@ -81,6 +110,7 @@ export function sectionSettingsFromXml(xml: string): SectionSettings {
footerDist: intAttr(pgMar, 'w:footer', 720),
...(vAlignOf(xml) ? { vAlign: vAlignOf(xml) } : {}),
pageBorder: hasVisiblePageBorder(xml),
...(pageBorderProps ? { pageBorderProps } : {}),
columns: intAttr(/<w:cols[^>]*\/?>/.exec(xml)?.[0] ?? '', 'w:num', 1),
colSpace: intAttr(/<w:cols[^>]*\/?>/.exec(xml)?.[0] ?? '', 'w:space', 720),
...(colWidths.length >= 2 ? { colWidths } : {}),
+15
View File
@@ -25,6 +25,8 @@ export function readThemeFonts(themeXml: string): ThemeFonts | null {
const majorEastAsia = slot('a:majorFont', 'a:ea')
const minorCs = slot('a:minorFont', 'a:cs')
const majorCs = slot('a:majorFont', 'a:cs')
const majorScripts = scriptFontsOf(themeXml, 'a:majorFont')
const minorScripts = scriptFontsOf(themeXml, 'a:minorFont')
return {
major: major ?? '',
minor: minor ?? '',
@@ -32,9 +34,22 @@ export function readThemeFonts(themeXml: string): ThemeFonts | null {
...(majorEastAsia ? { majorEastAsia } : {}),
...(minorCs ? { minorCs } : {}),
...(majorCs ? { majorCs } : {}),
...(majorScripts ? { majorScripts } : {}),
...(minorScripts ? { minorScripts } : {}),
}
}
/** per-script faces of a font group (<a:font script="Hang" typeface="…"/>) */
function scriptFontsOf(themeXml: string, tag: string): Record<string, string> | undefined {
const section = sectionOf(themeXml, tag)
if (!section) return undefined
const out: Record<string, string> = {}
for (const m of section.matchAll(/<a:font script="([^"]+)" typeface="([^"]+)"/g)) {
out[m[1]] = m[2]
}
return Object.keys(out).length > 0 ? out : undefined
}
function sectionOf(xml: string, tag: string): string | null {
return new RegExp(`<${tag}(?:\\s[^>]*)?>[\\s\\S]*?</${tag}>`).exec(xml)?.[0] ?? null
}
+84 -3
View File
@@ -208,12 +208,15 @@ export interface SdtShell {
/** One custom tab stop from w:tabs/w:tab. Positions are in twips. */
export interface TabStop {
/** position in twips (w:pos) */
/** position in twips (w:pos); percent of the text column when rel is set */
pos: number
/** tab alignment (w:val) */
val: 'left' | 'center' | 'right' | 'decimal' | 'bar' | 'clear'
/** leader character (w:leader): none/dot/hyphen/underscore/heavy/middleDot */
leader?: 'none' | 'dot' | 'hyphen' | 'underscore' | 'heavy' | 'middleDot'
/** display-only stop synthesized from a w:ptab (absolute position tab):
* pos is a percent of the column width. Never written back to w:tabs. */
rel?: 'margin'
}
/** Declared look of one w:pBdr side. */
@@ -275,6 +278,10 @@ export interface ParaFormat {
spaceBefore?: number
/** space below the paragraph in twips (w:spacing w:after) */
spaceAfter?: number
/** w:beforeAutospacing: Word ignores the literal and uses its HTML auto value (14pt) */
spaceBeforeAuto?: boolean
/** w:afterAutospacing: Word ignores the literal and uses its HTML auto value (14pt) */
spaceAfterAuto?: boolean
/** start the paragraph on a new page (w:pageBreakBefore) */
pageBreakBefore?: boolean
/** keep this paragraph on same page as the next paragraph (w:keepNext) */
@@ -287,7 +294,7 @@ export interface ParaFormat {
snapToGrid?: boolean
/** CJK-Latin/digit auto spacing (w:autoSpaceDE/DN; Word default=true); false when both are explicitly off */
autoSpace?: boolean
/** ignore space-after when followed by same-style para (w:contextualSpacing) */
/** ignore spacing next to same-style paras (w:contextualSpacing); false = explicit off overriding the style */
contextualSpacing?: boolean
/** paragraph shading fill, hex without '#' (w:shd w:fill) */
shadingFill?: string
@@ -355,6 +362,19 @@ export interface SectionSettings {
marginLeft: number
/** simple single-line box page border (w:pgBorders) */
pageBorder: boolean
/** page border box details (parse-side; pageBorder stays the on/off flag) */
pageBorderProps?: {
/** pages the border applies to (w:display); undefined = all pages */
display?: 'firstPage' | 'notFirstPage'
/** distance basis (w:offsetFrom): 'page' = space from the page edge, 'text' = from the text area */
offsetFrom?: 'page' | 'text'
/** border distance in points (max across sides' w:space) */
spacePt: number
/** line width in points (max across sides' w:sz eighth-points) */
widthPt: number
/** hex without '#', first side declaring a literal color */
color?: string
}
/** number of text columns (w:cols w:num), 1 = normal */
columns: number
/** column gap (w:cols w:space, twips; OOXML default 720) */
@@ -562,6 +582,12 @@ export interface FieldDisplay {
anchor?: string
/** numbering marker of the entry's w:numPr ("1.", "1.1."), computed at parse time */
num?: string
/** display-only metrics of the entry paragraph (direct pPr/run values; Word
* sizes TOC lines by them while the style carries nothing) */
szHalfPoints?: number
lineRule?: 'auto' | 'atLeast' | 'exact'
lineRawTwips?: number
lineSpacing?: number
}
/** Editable text tokens inside an OMML formula; the surrounding math tree is preserved. */
@@ -703,6 +729,8 @@ export interface TableCell {
nestedTables?: TableModel[]
/** anchored shapes/textboxes inside cell paragraphs (display-only; Word grows the row to hold them) */
anchoredBoxes?: TextboxDisplay[]
/** per anchored box: index of its anchor paragraph (positionV "paragraph" origin); absent = cell top */
anchoredBoxAnchors?: number[]
/** per nested table: how many cell paragraphs precede it (reading-order anchor); absent = after all paragraphs */
nestedTableAnchors?: number[]
colSpan?: number
@@ -738,7 +766,7 @@ export interface TableModel {
colWidthsTwips?: number[]
/** table width as a percentage of the body width (w:tblW type="pct"); absolute widths are ignored when set */
widthPct?: number
/** autofit layout (w:tblW auto/absent/zero, no fixed w:tblLayout): display may widen columns to min-content */
/** autofit layout (no fixed w:tblLayout; w:tblW auto/absent/zero or pct): display may widen columns to min-content */
autoLayout?: boolean
/** table-level default cell margins (w:tblCellMar) */
cellMarTwips?: CellMargins
@@ -1067,6 +1095,11 @@ export interface TextboxDisplay {
* Absent for plain rectangular textboxes (rect = default).
*/
prst?: string
/**
* a:custGeom outline as normalized SVG path channels (coords 0..1, scaled to
* the box by the renderer), display-only. Wins over prst when present.
*/
pathData?: { path?: string; fillPath?: string; strokePath?: string }
/**
* WordArt preset id (e.g. 'wordArt-1'). When set, the editor applies
* large-text CSS approximation (color + optional text-stroke).
@@ -1079,6 +1112,21 @@ export interface TextboxDisplay {
nowrap?: boolean
/** vertical anchoring of the text body (wps:bodyPr anchor="ctr|b"), display-only */
vAlign?: 'center' | 'bottom'
/** default text color from the shape style's a:fontRef (hex without '#'); a run's own color wins */
textColor?: string
/**
* Ordinal of this box's first w:txbxContent among all non-fallback
* w:txbxContent segments in the block XML. The save path addresses the box
* by it — positional matching skews whenever a paragraph also renders boxes
* that consume no segment (ink-only shapes, WordArt, pictures).
*/
txbxIndex?: number
/**
* wps:cNvPr id of the owning DrawingML shape. A box with no txbxIndex has
* no w:txbxContent yet: its first text commit injects a fresh wps:txbx into
* the shape addressed by this id.
*/
shapeId?: string
/**
* Content holds tables / content controls flattened into display lines, so
* paras do not map 1:1 onto the w:txbxContent w:p children the patch-save
@@ -1095,6 +1143,15 @@ export interface TextboxDisplay {
* paragraph with other drawings — leave the flow like Word (absolute
* position, no flow height) instead of stacking as blocks */
floating?: boolean
/** behindDoc="1" anchor: this box paints under the body text */
behind?: boolean
/** first-page page-anchored cover art: offsets are raw page coordinates and
* the box positions against the page box, not the anchor paragraph */
pagePinned?: boolean
/** page/margin-relative posOffset V rendered from the anchor paragraph: the
* canvas re-pins the box to its page top (Word treats the offset as
* absolute on the anchor's page, wherever the anchor sits) */
pageRelV?: boolean
/** wrapTopAndBottom (paragraph/line-relative V): the anchor paragraph keeps
* flow height down to this box bottom (px) so following text resumes below */
bandBottomPx?: number
@@ -1194,6 +1251,9 @@ export interface StyleDisplay {
lineRawTwips?: number
spaceBeforeTwips?: number
spaceAfterTwips?: number
/** style-level w:beforeAutospacing / w:afterAutospacing (Word HTML auto = 14pt) */
spaceBeforeAuto?: boolean
spaceAfterAuto?: boolean
/** indents from the style definition (w:pPr w:ind, twips; hanging is stored as a negative firstLine) */
indentLeftTwips?: number
indentRightTwips?: number
@@ -1294,6 +1354,9 @@ export interface DocDefaults {
spaceBeforeTwips?: number
/** F1: paragraph spacing after default (twips); undefined = not set in docDefaults */
spaceAfterTwips?: number
/** docDefaults-level w:beforeAutospacing / w:afterAutospacing (Word HTML auto = 14pt) */
spaceBeforeAuto?: boolean
spaceAfterAuto?: boolean
/** rPrDefault w:lang w:val (BCP-47) — hyphenation/locale of the body text */
lang?: string
}
@@ -1359,6 +1422,22 @@ export interface ThemeFonts {
minorCs?: string
/** settings.xml w:themeFontLang w:eastAsia — picks Word's face for empty EA theme slots */
eaLang?: string
/** per-script faces (<a:font script="Hang" typeface="…"/>) of each font group */
majorScripts?: Record<string, string>
minorScripts?: Record<string, string>
}
/** One word/fontTable.xml entry — Word's substitution hints for missing fonts. */
export interface FontTableEntry {
name: string
/** w:altName — the face Word substitutes when the font is missing */
altName?: string
/** w:panose1 hex digits (byte 2 = serif style: 02-0A serif, 0B-0F sans) */
panose?: string
/** w:family — roman / swiss / modern / script / decorative / auto */
family?: string
/** w:pitch — fixed / variable / default */
pitch?: string
}
/** Color scheme values (hex without '#') from a:clrScheme. */
@@ -1393,6 +1472,8 @@ export interface ParsedDoc {
inks: InkInfo[]
/** theme font pair from word/theme/theme1.xml, null when the doc has no theme part */
themeFonts?: ThemeFonts | null
/** word/fontTable.xml entries (substitution hints), absent when the part is missing/empty */
fontTable?: FontTableEntry[]
/** color scheme from word/theme/theme1.xml, null when the doc has no theme part */
themeColors?: ThemeColors | null
/** editing restriction from word/settings.xml, null when none */
+93
View File
@@ -46,6 +46,99 @@ describe('RTL paragraphs (w:bidi + Word jc left/right swap)', () => {
})
})
describe('run-level w:rtl without paragraph w:bidi (HTML-converted docs)', () => {
const INFERRED_BODY =
'<w:p><w:pPr><w:jc w:val="right"/></w:pPr>' +
'<w:r><w:rPr><w:rtl/></w:rPr><w:t>مرحبا بالعالم</w:t></w:r></w:p>'
it('keeps format.bidi unset and jc unswapped; the run carries rtl', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: INFERRED_BODY }))
expect(doc.blocks[0].format?.bidi).toBeUndefined()
expect(doc.blocks[0].format?.align).toBe('right')
expect(doc.blocks[0].runs?.[0].rtl).toBe(true)
})
it('stays byte-identical on save', async () => {
const bytes = await buildDocx({ bodyXml: INFERRED_BODY })
const doc = await parseDocx(bytes)
const blocks = doc.blocks
.filter((b) => !b.hidden && b.docxIndex !== null)
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
expect(await saveDocx(doc, blocks)).toEqual(bytes)
})
})
describe('before/afterAutospacing', () => {
const SPACING =
'<w:spacing w:before="100" w:beforeAutospacing="1" w:after="100" w:afterAutospacing="1"/>'
it('models the auto flags and keeps the literals (renderer applies Word auto 14pt)', async () => {
const body =
'<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>' +
SPACING +
'</w:pPr><w:r><w:t>item</w:t></w:r></w:p>' +
'<w:p><w:pPr>' +
SPACING +
'</w:pPr><w:r><w:t>plain</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: body, withNumbering: true }))
for (const block of doc.blocks.slice(0, 2)) {
expect(block.format).toMatchObject({
spaceBefore: 100,
spaceAfter: 100,
spaceBeforeAuto: true,
spaceAfterAuto: true,
})
}
})
it('stays byte-identical on save', async () => {
const raw = `<w:pPr>${SPACING}</w:pPr>`
const doc = await parseDocx(
await buildDocx({ bodyXml: `<w:p>${raw}<w:r><w:t>x</w:t></w:r></w:p>` }),
)
expect(mergePPrFormat(raw, doc.blocks[0].format)).toBe(raw)
})
it('emits the autospacing attributes when the spacing group is rebuilt', () => {
const out = mergePPrFormat('<w:pPr><w:spacing w:before="60"/></w:pPr>', {
spaceBefore: 100,
spaceBeforeAuto: true,
spaceAfterAuto: true,
})
expect(out).toContain('w:beforeAutospacing="1"')
expect(out).toContain('w:afterAutospacing="1"')
})
it('parses an explicit "0" as false and writes it back (overrides a style-chain auto)', async () => {
const raw = '<w:pPr><w:spacing w:before="100" w:beforeAutospacing="0"/></w:pPr>'
const doc = await parseDocx(
await buildDocx({ bodyXml: `<w:p>${raw}<w:r><w:t>x</w:t></w:r></w:p>` }),
)
expect(doc.blocks[0].format?.spaceBeforeAuto).toBe(false)
// unchanged: bytes preserved
expect(mergePPrFormat(raw, doc.blocks[0].format)).toBe(raw)
// rebuilt: the explicit off must survive, or the style's auto wins again in Word
const out = mergePPrFormat('<w:pPr><w:spacing w:before="60"/></w:pPr>', {
spaceBefore: 100,
spaceBeforeAuto: false,
})
expect(out).toContain('w:beforeAutospacing="0"')
})
})
describe('contextualSpacing tri-state', () => {
it('parses explicit off (w:val="0") as false so it can override a style-chain true', async () => {
const body =
'<w:p><w:pPr><w:contextualSpacing w:val="0"/></w:pPr><w:r><w:t>off</w:t></w:r></w:p>' +
'<w:p><w:pPr><w:contextualSpacing/></w:pPr><w:r><w:t>on</w:t></w:r></w:p>' +
'<w:p><w:r><w:t>absent</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
expect(doc.blocks[0].format?.contextualSpacing).toBe(false)
expect(doc.blocks[1].format?.contextualSpacing).toBe(true)
expect(doc.blocks[2].format?.contextualSpacing).toBeUndefined()
})
})
describe('RTL tables (tblPr w:bidiVisual)', () => {
it('parses bidiVisual into the table model', async () => {
const xml =
@@ -14,6 +14,23 @@ const TRIANGLE_ANCHOR =
'<a:prstGeom prst="triangle"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val="4472C4"/></a:solidFill></wps:spPr>' +
'<wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>'
// fixed-height (noAutofit) textbox: sysClr fill, prstClr border, exact one-line spacing
const TEXTBOX_ANCHOR =
'<w:drawing><wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="2" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/>' +
'<wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>9525</wp:posOffset></wp:positionV>' +
'<wp:extent cx="1000000" cy="152400"/><wp:wrapNone/>' +
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">' +
'<a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1000000" cy="152400"/></a:xfrm>' +
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>' +
'<a:solidFill><a:sysClr val="window" lastClr="FFFFFF"/></a:solidFill>' +
'<a:ln w="6350"><a:solidFill><a:prstClr val="black"/></a:solidFill></a:ln></wps:spPr>' +
'<wps:txbx><w:txbxContent><w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr>' +
'<w:r><w:t>box text</w:t></w:r></w:p></w:txbxContent></wps:txbx>' +
'<wps:bodyPr><a:noAutofit/></wps:bodyPr></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>'
function tableXml(cellExtra: string): string {
return (
'<w:tbl><w:tblPr><w:tblW w:w="9000" w:type="dxa"/></w:tblPr>' +
@@ -23,6 +40,18 @@ function tableXml(cellExtra: string): string {
)
}
function multiParaTableXml(secondParaExtra: string): string {
return (
'<w:tbl><w:tblPr><w:tblW w:w="9000" w:type="dxa"/></w:tblPr>' +
'<w:tblGrid><w:gridCol w:w="9000"/></w:tblGrid>' +
'<w:tr><w:tc><w:tcPr/>' +
'<w:p><w:r><w:t>first</w:t></w:r></w:p>' +
`<w:p><w:r><w:t>second</w:t></w:r><w:r>${secondParaExtra}</w:r></w:p>` +
'<w:p><w:r><w:t>third</w:t></w:r></w:p>' +
'</w:tc></w:tr></w:tbl>'
)
}
describe('anchored shapes inside table cells (tdf134277)', () => {
it('extracts the shape as a cell display box and keeps the cell text', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: tableXml(TRIANGLE_ANCHOR) }))
@@ -45,4 +74,41 @@ describe('anchored shapes inside table cells (tdf134277)', () => {
// the fallback's txbxContent text must not leak into the cell's plain text
expect(cell.paras[0]).not.toContain('box text')
})
it('strips mc:Fallback twins whose tag carries attributes (Word 2024 output)', async () => {
const wrapped =
'<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' +
`<mc:Choice Requires="wps">${TRIANGLE_ANCHOR}</mc:Choice>` +
'<mc:Fallback xmlns:w16sdtfl="http://schemas.microsoft.com/office/word/2024/wordSdtFallback">' +
'<w:pict><v:rect xmlns:v="urn:schemas-microsoft-com:vml" style="position:absolute;width:46pt;height:42pt">' +
'<v:textbox><w:txbxContent><w:p><w:r><w:t>box text</w:t></w:r></w:p></w:txbxContent></v:textbox>' +
'</v:rect></w:pict></mc:Fallback></mc:AlternateContent>'
const doc = await parseDocx(await buildDocx({ bodyXml: tableXml(wrapped) }))
const cell = doc.blocks[0].table!.rows[0][0]
expect(cell.anchoredBoxes).toHaveLength(1)
expect(cell.paras[0]).not.toContain('box text')
})
it('records the anchor paragraph index of each box', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: multiParaTableXml(TEXTBOX_ANCHOR) }))
const cell = doc.blocks[0].table!.rows[0][0]
expect(cell.paras).toEqual(['first', 'second', 'third'])
expect(cell.anchoredBoxes).toHaveLength(1)
expect(cell.anchoredBoxAnchors).toEqual([1])
})
it('resolves a:sysClr fill and a:prstClr border colors', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: tableXml(TEXTBOX_ANCHOR) }))
const box = doc.blocks[0].table!.rows[0][0].anchoredBoxes![0]
expect(box.fill).toBe('FFFFFF')
expect(box.borderColor).toBe('000000')
})
it('keeps the exact line rule of textbox paragraphs', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: tableXml(TEXTBOX_ANCHOR) }))
const para = doc.blocks[0].table!.rows[0][0].anchoredBoxes![0].paras[0]
expect(para.lineRule).toBe('exact')
expect(para.lineRawTwips).toBe(240)
expect(para.lineSpacing).toBeUndefined()
})
})
@@ -46,6 +46,19 @@ describe('metafileToDataUrl routing', () => {
}
expect(convertWmfToDataUrl).toHaveBeenLastCalledWith(expect.any(ArrayBuffer), { dpiScale: 2 })
})
it('routes by content signature when it contradicts the mime', async () => {
// EMF bytes under a wmf mime (HWP-exported docx)
const emf = new Uint8Array(44)
const dv = new DataView(emf.buffer)
dv.setUint32(0, 1, true)
dv.setUint32(40, 0x464d4520, true)
expect(await metafileToDataUrl(emf, 'image/wmf')).toBe('data:image/png;base64,EMFPNG')
// placeable WMF bytes under an emf mime
const wmf = new Uint8Array(18)
new DataView(wmf.buffer).setUint32(0, 0x9ac6cdd7, true)
expect(await metafileToDataUrl(wmf, 'image/emf')).toBe('data:image/png;base64,WMFPNG')
})
})
describe('parseDocx with emf media', () => {
@@ -60,6 +60,73 @@ describe('field paragraph display model', () => {
const doc = await parseDocx(await buildDocx({ bodyXml: TOC_ENTRY_PARAGRAPH }))
expect(doc.blocks[0].fieldDisplay?.anchor).toBe('_Toc1')
})
it('page number follows the LAST tab; a leading outline number becomes the num cell', async () => {
const xml =
'<w:p><w:pPr><w:pStyle w:val="TOC2"/></w:pPr>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> TOC \\o "1-3" </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:t>1.1.</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>Latar Belakang Masalah</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>7</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
expect(doc.blocks[0].fieldDisplay).toMatchObject({
kind: 'tocLine',
num: '1.1.',
left: 'Latar Belakang Masalah',
right: '7',
level: 2,
})
})
it('a long first segment stays part of the title, not the num cell', async () => {
const xml =
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
'<w:r><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:instrText xml:space="preserve"> TOC </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:t>BAB I</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>PENDAHULUAN</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>1</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
expect(doc.blocks[0].fieldDisplay).toMatchObject({
kind: 'tocLine',
left: 'BAB I PENDAHULUAN',
right: '1',
})
expect(doc.blocks[0].fieldDisplay?.num).toBeUndefined()
})
it('entry font size comes from visible result runs, not field-machinery runs', async () => {
const xml =
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
'<w:r><w:rPr><w:sz w:val="32"/></w:rPr><w:fldChar w:fldCharType="begin"/></w:r>' +
'<w:r><w:rPr><w:sz w:val="32"/></w:rPr><w:instrText xml:space="preserve"> TOC \\o "1-2" </w:instrText></w:r>' +
'<w:r><w:rPr><w:sz w:val="32"/></w:rPr><w:fldChar w:fldCharType="separate"/></w:r>' +
'<w:r><w:rPr><w:sz w:val="21"/></w:rPr><w:t>Chapter One</w:t></w:r>' +
'<w:r><w:tab/></w:r><w:r><w:t>3</w:t></w:r>' +
'<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
expect(doc.blocks[0].fieldDisplay?.szHalfPoints).toBe(21)
})
it('TableofFigures entries render as level-1 toc lines (dot leader + protection)', async () => {
const xml =
'<w:p><w:pPr><w:pStyle w:val="TableofFigures"/></w:pPr>' +
'<w:r><w:t>Tabel 2. 1 Sintaks model pembelajaran</w:t></w:r>' +
'<w:r><w:tab/></w:r><w:r><w:t>11</w:t></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: xml }))
expect(doc.blocks[0].type).toBe('passthrough')
expect(doc.blocks[0].fieldDisplay).toMatchObject({
kind: 'tocLine',
left: 'Tabel 2. 1 Sintaks model pembelajaran',
right: '11',
level: 1,
})
})
})
describe('generateTocFieldXml', () => {
@@ -150,6 +217,24 @@ describe('HYPERLINK field folding', () => {
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
expect(doc.blocks[0].type).toBe('passthrough')
})
it('a non-convertible HYPERLINK inside a textbox keeps its cached text visible', async () => {
// production resumes carry file:///C:\... HYPERLINK fields (backslashes)
// inside header textboxes; the cached email text must not vanish
const field = hyperlinkField(
'HYPERLINK "file:///C:\\Users\\u\\INetCache\\ph.hussam@gmail.com"',
).replace('creativets.org', 'ph.hussam@gmail.com')
const para =
'<w:p><w:r><w:drawing><wp:anchor behindDoc="0"><wp:extent cx="914400" cy="914400"/>' +
'<a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent>' +
`<w:p>${field}</w:p>` +
'</w:txbxContent></wps:txbx></wps:wsp></a:graphicData></a:graphic>' +
'</wp:anchor></w:drawing></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const box = doc.blocks[0].textboxes?.[0]
const text = box?.paras.map((p) => p.runs.map((r) => r.text).join('')).join('\n')
expect(text).toContain('ph.hussam@gmail.com')
})
})
// Legacy FORMCHECKBOX form field as Word writes it (POI checkboxes.docx):
@@ -0,0 +1,156 @@
/**
* word/fontTable.xml substitution hints + empty-EA-slot resolution priority
* (theme script table / themeFontLang vs the docDefaults w:lang backfill).
*/
import { describe, expect, it } from 'vitest'
import JSZip from 'jszip'
import { parseDocx, parseFontTable } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const FONT_TABLE_XML =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:font w:name="원신한 Light"><w:panose1 w:val="020B0303000000000000"/>' +
'<w:charset w:val="81"/><w:family w:val="modern"/><w:pitch w:val="variable"/></w:font>' +
'<w:font w:name="汉仪旗黑-50简"><w:altName w:val="黑体"/>' +
'<w:panose1 w:val="00000000000000000000"/><w:family w:val="auto"/><w:pitch w:val="default"/></w:font>' +
'<w:font w:name="Calibri"><w:panose1 w:val="020F0502020204030204"/></w:font>' +
'</w:fonts>'
const FONT_TABLE_PART = {
path: 'word/fontTable.xml',
xml: FONT_TABLE_XML,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml',
}
describe('parseFontTable', () => {
it('reads name / altName / panose / family / pitch per entry', () => {
const entries = parseFontTable(FONT_TABLE_XML)
expect(entries).toEqual([
{ name: '원신한 Light', panose: '020B0303000000000000', family: 'modern', pitch: 'variable' },
{
name: '汉仪旗黑-50简',
altName: '黑体',
panose: '00000000000000000000',
family: 'auto',
pitch: 'default',
},
{ name: 'Calibri', panose: '020F0502020204030204' },
])
})
it('degrades to empty on malformed or rootless xml', () => {
expect(parseFontTable('<w:font w:name="X"/>')).toEqual([])
expect(parseFontTable('not xml <')).toEqual([])
})
})
describe('ParsedDoc.fontTable', () => {
it('exposes word/fontTable.xml entries', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
extraParts: [FONT_TABLE_PART],
}),
)
expect(doc.fontTable?.map((e) => e.name)).toEqual(['원신한 Light', '汉仪旗黑-50简', 'Calibri'])
expect(doc.fontTable?.[1].altName).toBe('黑体')
})
it('is absent when the doc has no fontTable part', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }))
expect(doc.fontTable).toBeUndefined()
})
})
const themePart = (minorFontExtra: string) => ({
path: 'word/theme/theme1.xml',
xml:
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="T">' +
'<a:themeElements><a:fontScheme name="T">' +
'<a:majorFont><a:latin typeface="Aptos Display"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont>' +
`<a:minorFont><a:latin typeface="Aptos"/><a:ea typeface=""/><a:cs typeface=""/>${minorFontExtra}</a:minorFont>` +
'</a:fontScheme></a:themeElements></a:theme>',
contentType: 'application/vnd.openxmlformats-officedocument.theme+xml',
})
const settingsPart = (eaLang: string) => ({
path: 'word/settings.xml',
xml:
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
`<w:themeFontLang w:val="en-US" w:eastAsia="${eaLang}"/></w:settings>`,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml',
})
const HANG_SCRIPT = '<a:font script="Hang" typeface="맑은 고딕"/>'
/** docDefaults with an empty-EA theme ref and a stale w:lang */
async function withDocDefaults(
rPr: string,
extraParts: Parameters<typeof buildDocx>[0]['extraParts'],
) {
const zip = await JSZip.loadAsync(
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>', extraParts }),
)
const stylesXml = await zip.file('word/styles.xml')!.async('string')
zip.file(
'word/styles.xml',
stylesXml.replace(
/(<w:styles[^>]*>)/,
`$1<w:docDefaults><w:rPrDefault><w:rPr>${rPr}</w:rPr></w:rPrDefault></w:docDefaults>`,
),
)
return parseDocx(await zip.generateAsync({ type: 'uint8array' }))
}
describe('empty EA slot resolution priority', () => {
const RFONTS = '<w:rFonts w:asciiTheme="minorHAnsi" w:eastAsiaTheme="minorEastAsia"/>'
it('theme script table entry wins for the themeFontLang script', async () => {
const para =
'<w:p><w:r><w:rPr><w:rFonts w:eastAsiaTheme="minorEastAsia"/></w:rPr><w:t>본문</w:t></w:r></w:p>'
const doc = await parseDocx(
await buildDocx({
bodyXml: para,
extraParts: [themePart(HANG_SCRIPT), settingsPart('ko-KR')],
}),
)
expect(doc.blocks[0].runs![0].font).toBe('맑은 고딕')
})
it('themeFontLang outranks a stale docDefaults w:lang backfill', async () => {
const doc = await withDocDefaults(`${RFONTS}<w:lang w:val="en-US" w:eastAsia="zh-CN"/>`, [
themePart(HANG_SCRIPT),
settingsPart('ko-KR'),
])
expect(doc.docDefaults?.eastAsiaFont).toBe('맑은 고딕')
expect(doc.docDefaults?.eaSlotEmpty).toBe(true)
})
it('without a script table the probed locale default still outranks w:lang', async () => {
const doc = await withDocDefaults(`${RFONTS}<w:lang w:eastAsia="zh-CN"/>`, [
themePart(''),
settingsPart('ko-KR'),
])
expect(doc.docDefaults?.eastAsiaFont).toBe('Malgun Gothic')
})
it('without themeFontLang the w:lang backfill keeps deciding', async () => {
const doc = await withDocDefaults(`${RFONTS}<w:lang w:eastAsia="zh-CN"/>`, [
themePart(HANG_SCRIPT),
])
expect(doc.docDefaults?.eastAsiaFont).toBe('SimSun')
})
it('themeFontLang alone must not invent an EA face when w:lang would not backfill', async () => {
const enLang = await withDocDefaults(`${RFONTS}<w:lang w:val="en-US" w:eastAsia="en-US"/>`, [
themePart(HANG_SCRIPT),
settingsPart('ja-JP'),
])
expect(enLang.docDefaults?.eastAsiaFont).toBeUndefined()
const noLang = await withDocDefaults(RFONTS, [themePart(HANG_SCRIPT), settingsPart('ja-JP')])
expect(noLang.docDefaults?.eastAsiaFont).toBeUndefined()
})
})
@@ -164,6 +164,64 @@ describe('rich header / footer', () => {
])
})
it('direct w:tabs merge with Header style stops instead of replacing them (Word)', async () => {
const HEADER =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:p><w:pPr><w:pStyle w:val="Header"/>' +
'<w:tabs><w:tab w:val="left" w:pos="8928"/><w:tab w:val="left" w:pos="8928"/></w:tabs>' +
'</w:pPr><w:r><w:tab/><w:t>Right text</w:t></w:r></w:p>' +
'</w:hdr>'
const STYLES =
'<w:style w:type="paragraph" w:styleId="Header"><w:name w:val="header"/>' +
'<w:pPr><w:tabs><w:tab w:val="center" w:pos="4680"/><w:tab w:val="right" w:pos="9360"/></w:tabs></w:pPr></w:style>'
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>body</w:t></w:r></w:p>',
extraStylesXml: STYLES,
extraRels:
'<Relationship Id="rId61" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
extraParts: [
{
path: 'word/header1.xml',
xml: HEADER,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
},
],
sectPrExtra: '<w:headerReference w:type="default" r:id="rId61"/>',
})
const parsed = await parseDocx(bytes)
expect(parsed.headerParas![0].tabStops).toEqual([
{ pos: 4680, val: 'center' },
{ pos: 8928, val: 'left' },
{ pos: 9360, val: 'right' },
])
})
it('legacy <w:pgNum/> renders as a PAGE field (page number, hasPageNumber)', async () => {
const FOOTER =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
'<w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:p><w:r><w:t xml:space="preserve">Page </w:t></w:r>' +
'<w:r><w:pgNum/></w:r></w:p>' +
'</w:ftr>'
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>body</w:t></w:r></w:p>',
extraRels:
'<Relationship Id="rId62" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>',
extraParts: [
{
path: 'word/footer1.xml',
xml: FOOTER,
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml',
},
],
sectPrExtra: '<w:footerReference w:type="default" r:id="rId62"/>',
})
const parsed = await parseDocx(bytes)
expect(parsed.footerHasPageNumber).toBe(true)
expect(parsed.footerParas![0].runs.map((r) => r.text).join('')).toBe(`Page ${PAGE_MARK}`)
})
it('w:framePr xAlign surfaces as frameXAlign (POI WordWithAttachments page number frame)', async () => {
const HEADER =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
@@ -23,6 +23,8 @@ export interface BuildDocxOptions {
binaryParts?: Array<{ path: string; base64: string; extension: string; contentType: string }>
/** extra sectPr children inserted first (headerReference/footerReference…) */
sectPrExtra?: string
/** extra attributes on the <w:document> root (e.g. xml:space="preserve") */
docRootExtraAttrs?: string
}
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
@@ -118,7 +120,7 @@ export async function buildDocx(options: BuildDocxOptions): Promise<Uint8Array>
'</w:sectPr>'
zip.file(
'word/document.xml',
`${XML_DECL}<w:document ${DOC_NS}><w:body>${options.bodyXml}${sectPr}</w:body></w:document>`,
`${XML_DECL}<w:document ${DOC_NS}${options.docRootExtraAttrs ? ` ${options.docRootExtraAttrs}` : ''}><w:body>${options.bodyXml}${sectPr}</w:body></w:document>`,
)
// Pin zip entry mtimes (JSZip defaults them to "now") so regenerating the
@@ -351,7 +351,8 @@ describe('tight / through wrap (wrapPolygon fidelity)', () => {
const doc = await parseDocx(await buildDocx({ bodyXml: body, withImage: true }))
const imgs = (doc.blocks[0].runs ?? []).filter((r) => r.image)
expect(imgs).toHaveLength(2)
expect(imgs[0].image!.wrap).toBe('square-left')
// positionH align=center + wrapSquare maps to the centered topBottom slot
expect(imgs[0].image!.wrap).toBe('topBottom')
// the colliding allowOverlap="0" picture leaves the flow as a front overlay
// under the collider's box
expect(imgs[1].image!.wrap).toBe('front')
@@ -24,6 +24,43 @@ describe('w:t whitespace handling', () => {
const doc = await parseDocx(bytes)
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('L1:cancelled kept ')
})
it('xml:space="preserve" on the document root covers every w:t (inherited XML scope)', async () => {
const bytes = await buildDocx({
docRootExtraAttrs: 'xml:space="preserve"',
bodyXml:
'<w:p><w:r><w:t>Memorandum</w:t></w:r>' +
'<w:r><w:rPr><w:spacing w:val="-49"/></w:rPr><w:t> </w:t></w:r>' +
'<w:r><w:t>of</w:t></w:r>' +
'<w:r><w:rPr><w:b/></w:rPr><w:t xml:space="default">\n\t x \n</w:t></w:r></w:p>',
})
const doc = await parseDocx(bytes)
// whitespace-only run survives; an explicit xml:space="default" still trims
expect(doc.blocks[0].runs!.map((r) => r.text)).toEqual(['Memorandum', ' ', 'of', 'x'])
})
it('xml:space="preserve" on a footer part root covers its w:t too', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>body</w:t></w:r></w:p>',
extraRels:
'<Relationship Id="rId70" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>',
extraParts: [
{
path: 'word/footer1.xml',
xml:
XML_DECL +
'<w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xml:space="preserve">' +
'<w:p><w:r><w:t>END</w:t></w:r>' +
'<w:r><w:rPr><w:spacing w:val="-4"/></w:rPr><w:t> </w:t></w:r>' +
'<w:r><w:t>OF</w:t></w:r></w:p></w:ftr>',
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml',
},
],
sectPrExtra: '<w:footerReference w:type="default" r:id="rId70"/>',
})
const doc = await parseDocx(bytes)
expect(doc.footerParas![0].runs.map((r) => r.text)).toEqual(['END', ' ', 'OF'])
})
})
describe('hex color tolerance', () => {
@@ -54,22 +91,39 @@ describe('default style resolution', () => {
expect(defaults.map((s) => s.styleId)).toEqual(['Title'])
})
it('without any w:default, the first style of the type is the default', async () => {
it('without any w:default, a style id/named "Normal" is the default (not the first style)', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
stylesXml:
XML_DECL +
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:style w:type="paragraph" w:styleId="Normal"><w:name w:val="Normal"/>' +
'<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/>' +
'<w:rPr><w:b/><w:sz w:val="56"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="Style7"><w:name w:val="normal"/>' +
'<w:rPr><w:color w:val="FF00FF"/><w:sz w:val="48"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="MyStyle"><w:name w:val="MyStyle"/></w:style>' +
'</w:styles>',
})
const doc = await parseDocx(bytes)
const defaults = [...doc.styles.values()].filter((s) => s.isDefault && s.type === 'paragraph')
expect(defaults.map((s) => s.styleId)).toEqual(['Normal'])
expect(defaults.map((s) => s.styleId)).toEqual(['Style7'])
expect(defaults[0].display?.color).toBe('FF00FF')
})
it('without any w:default or Normal style, no paragraph style is the default', async () => {
const bytes = await buildDocx({
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
stylesXml:
XML_DECL +
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/>' +
'<w:pPr><w:jc w:val="center"/></w:pPr><w:rPr><w:b/><w:sz w:val="56"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="MyStyle"><w:name w:val="MyStyle"/></w:style>' +
'</w:styles>',
})
const doc = await parseDocx(bytes)
const defaults = [...doc.styles.values()].filter((s) => s.isDefault)
expect(defaults).toEqual([])
})
})
describe('settings.xml layout flags', () => {
@@ -118,8 +118,8 @@ describe('page/margin-anchored textboxes outside the body column', () => {
expect(box.offsetYEmu).toBe(PAGE_H - 2 * MARGIN - 1000000)
})
it('leaves plain posOffset anchors on the legacy paragraph-relative path', async () => {
const posH = `<wp:positionH relativeFrom="page"><wp:posOffset>100000</wp:posOffset></wp:positionH>`
it('converts page-relative posOffset to column-relative; paragraph-relative stays put', async () => {
const posH = `<wp:positionH relativeFrom="page"><wp:posOffset>1000000</wp:posOffset></wp:positionH>`
const posV = `<wp:positionV relativeFrom="paragraph"><wp:posOffset>50000</wp:posOffset></wp:positionV>`
const para = anchorPara(
posH,
@@ -130,7 +130,8 @@ describe('page/margin-anchored textboxes outside the body column', () => {
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [box] = doc.blocks[0].textboxes!
expect(box.floating).toBeUndefined()
expect(box.offsetXEmu).toBe(100000)
// page X measures from the page edge: the 1440-twip left margin comes off
expect(box.offsetXEmu).toBe(1000000 - 1440 * 635)
expect(box.offsetYEmu).toBe(50000)
})
@@ -1,9 +1,5 @@
import { describe, expect, it } from 'vitest'
import {
parseDocx,
patchFieldParagraphXml,
patchMathTokens,
} from '../src/index'
import { parseDocx, patchFieldParagraphXml, patchMathTokens } from '../src/index'
import { buildDocx } from './helpers/build-docx'
const TOC_ENTRY =
@@ -39,6 +35,19 @@ describe('protected visible-text patching', () => {
expect(parsed.blocks[0].fieldDisplay?.right).toBe('12')
})
it('patches the page number after the LAST tab, leaving the title and num intact', async () => {
const entry =
'<w:p><w:pPr><w:pStyle w:val="TOC2"/></w:pPr>' +
'<w:r><w:t>1.1.</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>Latar Belakang</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>7</w:t></w:r></w:p>'
const patched = patchFieldParagraphXml(entry, { left: 'Judul Baru', right: '9' })
expect(patched).toContain('<w:t>1.1.</w:t>')
expect(patched).toContain('<w:t>Judul Baru</w:t>')
expect(patched).toContain('<w:t>9</w:t>')
expect(patched).not.toContain('Latar Belakang')
})
it('edits OMML tokens while preserving the formula tree', async () => {
const patched = patchMathTokens(FORMULA, ['x & 1', 'y'])
expect(patched).toContain('<m:f><m:num>')
@@ -545,3 +545,36 @@ describe('SaveOptions.numbering write-back', () => {
expect(reparsed.numbering.get('9')!.levels[0].numFmt).toBe('bullet')
})
})
describe('pgBorders details', () => {
it('parses display/offsetFrom/space/sz/color from the sides', async () => {
const { sectionSettingsFromXml } = await import('../src/section')
const s = sectionSettingsFromXml(
'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>' +
'<w:pgMar w:top="1417" w:right="1134" w:bottom="1134" w:left="1417"/>' +
'<w:pgBorders w:display="firstPage" w:offsetFrom="page">' +
'<w:top w:val="single" w:sz="18" w:space="24" w:color="1F497D"/>' +
'<w:left w:val="single" w:sz="18" w:space="24" w:color="1F497D"/>' +
'<w:bottom w:val="single" w:sz="18" w:space="24" w:color="1F497D"/>' +
'<w:right w:val="single" w:sz="18" w:space="24" w:color="1F497D"/>' +
'</w:pgBorders></w:sectPr>',
)
expect(s.pageBorder).toBe(true)
expect(s.pageBorderProps).toEqual({
display: 'firstPage',
offsetFrom: 'page',
spacePt: 24,
widthPt: 2.25,
color: '1F497D',
})
})
it('none-only sides leave pageBorderProps unset', async () => {
const { sectionSettingsFromXml } = await import('../src/section')
const s = sectionSettingsFromXml(
'<w:sectPr><w:pgBorders><w:top w:val="none"/></w:pgBorders></w:sectPr>',
)
expect(s.pageBorder).toBe(false)
expect(s.pageBorderProps).toBeUndefined()
})
})
@@ -0,0 +1,439 @@
import { describe, expect, it } from 'vitest'
import { parseDocx } from '../src/parse'
import { buildDocx } from './helpers/build-docx'
const WPS_NS = 'xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"'
const WPG_NS = 'xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"'
const MC_NS = 'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"'
/** rectangle custGeom in a w×h path space (the shape Word writes for cards/rules) */
function custGeomXml(w: number, h: number): string {
return (
`<a:custGeom><a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/><a:rect l="l" t="t" r="r" b="b"/>` +
`<a:pathLst><a:path w="${w}" h="${h}">` +
`<a:moveTo><a:pt x="0" y="${h}"/></a:moveTo>` +
`<a:lnTo><a:pt x="${w}" y="${h}"/></a:lnTo>` +
`<a:lnTo><a:pt x="${w}" y="0"/></a:lnTo>` +
`<a:lnTo><a:pt x="0" y="0"/></a:lnTo>` +
`<a:close/></a:path></a:pathLst></a:custGeom>`
)
}
function custWsp(opts: {
offX?: number
offY?: number
cx: number
cy: number
fill?: string
}): string {
const fill = opts.fill === 'grp' ? '<a:grpFill/>' : opts.fill
return (
`<wps:wsp ${WPS_NS}><wps:cNvSpPr/><wps:spPr>` +
`<a:xfrm><a:off x="${opts.offX ?? 0}" y="${opts.offY ?? 0}"/>` +
`<a:ext cx="${opts.cx}" cy="${opts.cy}"/></a:xfrm>` +
custGeomXml(opts.cx, opts.cy) +
(fill ?? '') +
`</wps:spPr><wps:bodyPr/></wps:wsp>`
)
}
function anchorParagraph(inner: string, uri: string): string {
return (
`<w:p><w:r><w:drawing><wp:anchor behindDoc="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">` +
`<wp:simplePos x="0" y="0"/>` +
`<wp:positionH relativeFrom="column"><wp:posOffset>100000</wp:posOffset></wp:positionH>` +
`<wp:positionV relativeFrom="paragraph"><wp:posOffset>200000</wp:posOffset></wp:positionV>` +
`<wp:extent cx="952500" cy="952500"/><wp:wrapNone/>` +
`<wp:docPr id="7" name="Shape 7"/>` +
`<a:graphic><a:graphicData uri="${uri}">${inner}</a:graphicData></a:graphic>` +
`</wp:anchor></w:drawing></w:r></w:p>`
)
}
const SHAPE_URI = 'http://schemas.microsoft.com/office/word/2010/wordprocessingShape'
const GROUP_URI = 'http://schemas.microsoft.com/office/word/2010/wordprocessingGroup'
describe('shape-style fontRef supplies the text color', () => {
/** Gallery shape: accent fill from spPr, text color left to the style's fontRef. */
const styledWsp = (fontRefClr: string) =>
`<wps:wsp ${WPS_NS}><wps:cNvSpPr/><wps:spPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="952500" cy="476250"/></a:xfrm>` +
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
`<a:solidFill><a:srgbClr val="4472C4"/></a:solidFill></wps:spPr>` +
`<wps:style><a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef>` +
`<a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef>` +
`<a:effectRef idx="0"><a:schemeClr val="accent1"/></a:effectRef>` +
`<a:fontRef idx="minor"><a:schemeClr val="${fontRefClr}"/></a:fontRef></wps:style>` +
`<wps:txbx><w:txbxContent><w:p><w:r><w:t>Label</w:t></w:r></w:p></w:txbxContent></wps:txbx>` +
`<wps:bodyPr anchor="ctr"/></wps:wsp>`
const boxOf = async (xml: string) =>
(await parseDocx(await buildDocx({ bodyXml: anchorParagraph(xml, SHAPE_URI) }))).blocks[0]
.textboxes?.[0]
// Word writes no color on the runs of a gallery shape; lt1 is why the default
// blue shape shows white text in Word and PowerPoint alike.
it('fontRef lt1 becomes the box text color', async () => {
expect((await boxOf(styledWsp('lt1')))?.textColor).toBe('FFFFFF')
})
it('fontRef tx1 gives dark text instead', async () => {
expect((await boxOf(styledWsp('tx1')))?.textColor).toBe('000000')
})
it('a shape with no style block has no box-level color to impose', async () => {
const plain = styledWsp('lt1').replace(/<wps:style>[\s\S]*?<\/wps:style>/, '')
expect((await boxOf(plain))?.textColor).toBeUndefined()
})
it('anchor="ctr" still reaches vAlign alongside the color', async () => {
expect((await boxOf(styledWsp('lt1')))?.vAlign).toBe('center')
})
})
describe('textless custGeom shapes', () => {
it('a solid-filled custGeom becomes a readOnly box with normalized pathData', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(
custWsp({
cx: 952500,
cy: 476250,
fill: '<a:solidFill><a:srgbClr val="1A295D"/></a:solidFill>',
}),
SHAPE_URI,
),
}),
)
const box = doc.blocks[0].textboxes?.[0]
expect(box).toBeTruthy()
expect(box!.readOnly).toBe(true)
expect(box!.fill).toBe('1A295D')
expect(box!.pathData?.path).toBe('M 0 1 L 1 1 L 1 0 L 0 0 Z')
expect(box!.widthPx).toBe(100)
expect(box!.heightPx).toBe(50)
})
it('a custGeom with no fill and no outline still renders nothing', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: anchorParagraph(custWsp({ cx: 952500, cy: 476250 }), SHAPE_URI),
}),
)
expect(doc.blocks[0].textboxes).toBeUndefined()
})
it('a:grpFill inherits the enclosing wpg group fill through nesting', async () => {
const group =
`<wpg:wgp ${WPG_NS} ${WPS_NS}><wpg:cNvGrpSpPr/><wpg:grpSpPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="952500" cy="952500"/>` +
`<a:chOff x="0" y="0"/><a:chExt cx="952500" cy="952500"/></a:xfrm>` +
`<a:solidFill><a:srgbClr val="0070C0"/></a:solidFill>` +
`</wpg:grpSpPr>` +
custWsp({ offX: 190500, offY: 95250, cx: 476250, cy: 476250, fill: 'grp' }) +
`</wpg:wgp>`
const doc = await parseDocx(await buildDocx({ bodyXml: anchorParagraph(group, GROUP_URI) }))
const box = doc.blocks[0].textboxes?.[0]
expect(box).toBeTruthy()
expect(box!.fill).toBe('0070C0')
expect(box!.floating).toBe(true)
expect(box!.offsetXEmu).toBe(100000 + 190500)
expect(box!.offsetYEmu).toBe(200000 + 95250)
})
it('a page-relative posOffset group anchors its children column-relative', async () => {
const group =
`<wpg:wgp ${WPG_NS} ${WPS_NS}><wpg:cNvGrpSpPr/><wpg:grpSpPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="5867400" cy="4785360"/>` +
`<a:chOff x="0" y="0"/><a:chExt cx="5867400" cy="4785360"/></a:xfrm>` +
`</wpg:grpSpPr>` +
custWsp({
offX: 1353311,
offY: 0,
cx: 1899285,
cy: 1179830,
fill: '<a:solidFill><a:srgbClr val="1A295D"/></a:solidFill>',
}) +
`</wpg:wgp>`
const para = anchorParagraph(group, GROUP_URI)
.replace(
'<wp:positionH relativeFrom="column"><wp:posOffset>100000</wp:posOffset></wp:positionH>',
'<wp:positionH relativeFrom="page"><wp:posOffset>1213103</wp:posOffset></wp:positionH>',
)
.replace(
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>200000</wp:posOffset></wp:positionV>',
'<wp:positionV relativeFrom="page"><wp:posOffset>3465576</wp:posOffset></wp:positionV>',
)
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const box = doc.blocks[0].textboxes?.[0]
expect(box).toBeTruthy()
// page coords lose the 1440-twip margins: X exact, Y assumes the anchor
// paragraph at body top (exact for a first-block anchor)
expect(box!.pagePinned).toBeUndefined()
expect(box!.offsetXEmu).toBe(1213103 - 1440 * 635 + 1353311)
expect(box!.offsetYEmu).toBe(3465576 - 1440 * 635)
})
it('a later-block page-anchored group pins to the page box (raw page coordinates)', async () => {
const group =
`<wpg:wgp ${WPG_NS} ${WPS_NS}><wpg:cNvGrpSpPr/><wpg:grpSpPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="5867400" cy="4785360"/>` +
`<a:chOff x="0" y="0"/><a:chExt cx="5867400" cy="4785360"/></a:xfrm>` +
`</wpg:grpSpPr>` +
custWsp({
offX: 1353311,
offY: 0,
cx: 1899285,
cy: 1179830,
fill: '<a:solidFill><a:srgbClr val="1A295D"/></a:solidFill>',
}) +
`</wpg:wgp>`
const para =
'<w:p><w:r><w:t>heading above</w:t></w:r></w:p>' +
anchorParagraph(group, GROUP_URI)
.replace(
'<wp:positionH relativeFrom="column"><wp:posOffset>100000</wp:posOffset></wp:positionH>',
'<wp:positionH relativeFrom="page"><wp:posOffset>1213103</wp:posOffset></wp:positionH>',
)
.replace(
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>200000</wp:posOffset></wp:positionV>',
'<wp:positionV relativeFrom="page"><wp:posOffset>3465576</wp:posOffset></wp:positionV>',
)
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const box = doc.blocks[1].textboxes?.[0]
expect(box).toBeTruthy()
expect(box!.pagePinned).toBe(true)
expect(box!.floating).toBe(true)
expect(box!.offsetXEmu).toBe(1213103 + 1353311)
expect(box!.offsetYEmu).toBe(3465576)
})
})
describe('grouped and sibling pictures', () => {
const GROUP_WITH_PIC =
`<wpg:wgp ${WPG_NS} ${WPS_NS}><wpg:cNvGrpSpPr/><wpg:grpSpPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="952500" cy="952500"/>` +
`<a:chOff x="0" y="0"/><a:chExt cx="952500" cy="952500"/></a:xfrm>` +
`</wpg:grpSpPr>` +
`<pic:pic><pic:nvPicPr><pic:cNvPr id="2" name="Image 2"/><pic:cNvPicPr/></pic:nvPicPr>` +
`<pic:blipFill><a:blip r:embed="rId10"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>` +
`<pic:spPr><a:xfrm><a:off x="95250" y="190500"/><a:ext cx="476250" cy="238125"/></a:xfrm>` +
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>` +
custWsp({
offX: 0,
offY: 0,
cx: 476250,
cy: 476250,
fill: '<a:solidFill><a:srgbClr val="C8A24B"/></a:solidFill>',
}) +
`</wpg:wgp>`
it('a pic:pic inside a wpg group becomes a photo box at the mapped offset', async () => {
const doc = await parseDocx(
await buildDocx({ bodyXml: anchorParagraph(GROUP_WITH_PIC, GROUP_URI), withImage: true }),
)
const boxes = doc.blocks[0].textboxes
expect(boxes?.length).toBe(2)
const [photo, shape] = boxes!
expect(photo.fillImageDataUrl).toContain('data:image/png')
expect(photo.readOnly).toBe(true)
expect(photo.floating).toBe(true)
expect(photo.widthPx).toBe(50)
expect(photo.heightPx).toBe(25)
expect(photo.offsetXEmu).toBe(100000 + 95250)
expect(photo.offsetYEmu).toBe(200000 + 190500)
// document order preserved: the shape paints over the photo
expect(shape.fill).toBe('C8A24B')
})
it('a rotated grouped pic:pic carries its rotation onto the photo box', async () => {
const rotated = GROUP_WITH_PIC.replace('<pic:spPr><a:xfrm>', '<pic:spPr><a:xfrm rot="5400000">')
const doc = await parseDocx(
await buildDocx({ bodyXml: anchorParagraph(rotated, GROUP_URI), withImage: true }),
)
expect(doc.blocks[0].textboxes?.[0]?.rotDeg).toBe(90)
})
it('an inline picture sharing its paragraph with a text-bearing textbox becomes a photo box', async () => {
const textbox = anchorParagraph(
`<wps:wsp ${WPS_NS}><wps:cNvSpPr/><wps:spPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="952500" cy="476250"/></a:xfrm>` +
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
`</wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>card</w:t></w:r></w:p>` +
`</w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp>`,
SHAPE_URI,
).replace(/<\/w:p>$/, '')
const inlinePic =
`<w:r><w:drawing><wp:inline><wp:extent cx="476250" cy="238125"/>` +
`<wp:docPr id="8" name="Image 8"/>` +
`<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">` +
`<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill>` +
`<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="476250" cy="238125"/></a:xfrm></pic:spPr>` +
`</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: textbox + inlinePic, withImage: true }))
// the inline pic flows as a stray run image: a non-floating photo box
// would knock the block out of the zero-height floating overlay
const boxes = doc.blocks[0].textboxes
expect(boxes?.length).toBe(1)
expect(boxes![0].paras[0]?.runs[0]?.text).toBe('card')
const img = doc.blocks[0].strayRuns?.find((r) => r.image)?.image
expect(img?.dataUrl).toContain('data:image/png')
expect(img?.widthPx).toBe(50)
expect(img?.heightPx).toBe(25)
})
it('an anchored sibling picture becomes a floating photo box carrying its rotation', async () => {
const textbox = anchorParagraph(
`<wps:wsp ${WPS_NS}><wps:cNvSpPr/><wps:spPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="952500" cy="476250"/></a:xfrm>` +
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
`</wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>card</w:t></w:r></w:p>` +
`</w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp>`,
SHAPE_URI,
).replace(/<\/w:p>$/, '')
const anchoredPic = anchorParagraph(
`<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill>` +
`<pic:spPr><a:xfrm rot="-2700000"><a:off x="0" y="0"/>` +
`<a:ext cx="476250" cy="238125"/></a:xfrm></pic:spPr></pic:pic>`,
'http://schemas.openxmlformats.org/drawingml/2006/picture',
).replace('<w:p>', '')
const doc = await parseDocx(
await buildDocx({ bodyXml: textbox + anchoredPic, withImage: true }),
)
const boxes = doc.blocks[0].textboxes
expect(boxes?.length).toBe(2)
const photo = boxes![1]
expect(photo.fillImageDataUrl).toContain('data:image/png')
expect(photo.floating).toBe(true)
expect(photo.rotDeg).toBe(-45)
expect(doc.blocks[0].strayRuns).toBeUndefined()
})
it('a drawing inside mc:AlternateContent/mc:Choice still yields a run image', async () => {
const body =
`<w:p><w:r><w:t xml:space="preserve">before </w:t></w:r>` +
`<w:r><mc:AlternateContent ${MC_NS}><mc:Choice Requires="wps">` +
`<w:drawing><wp:inline><wp:extent cx="476250" cy="238125"/>` +
`<wp:docPr id="9" name="Image 9"/>` +
`<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">` +
`<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>` +
`</a:graphicData></a:graphic></wp:inline></w:drawing>` +
`</mc:Choice><mc:Fallback><w:pict/></mc:Fallback></mc:AlternateContent></w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: body, withImage: true }))
const block = doc.blocks[0]
expect(block.type).toBe('paragraph')
const imageRun = block.runs?.find((r) => r.image)
expect(imageRun?.image?.dataUrl).toContain('data:image/png')
expect(imageRun?.image?.widthPx).toBe(50)
})
})
describe('zero-height horizontal lines', () => {
it('a cy="0" anchored line renders as a decorative rule, not a chip', async () => {
const body =
`<w:p><w:r><w:drawing><wp:anchor behindDoc="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">` +
`<wp:simplePos x="0" y="0"/>` +
`<wp:positionH relativeFrom="page"><wp:posOffset>735965</wp:posOffset></wp:positionH>` +
`<wp:positionV relativeFrom="paragraph"><wp:posOffset>95250</wp:posOffset></wp:positionV>` +
`<wp:extent cx="6724015" cy="0"/><wp:wrapNone/>` +
`<wp:docPr id="2" name="Line 26"/>` +
`<a:graphic><a:graphicData uri="${SHAPE_URI}">` +
`<wps:wsp ${WPS_NS}><wps:cNvCnPr/><wps:spPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="6724015" cy="0"/></a:xfrm>` +
`<a:prstGeom prst="line"><a:avLst/></a:prstGeom><a:noFill/>` +
`<a:ln w="9144"><a:solidFill><a:srgbClr val="000000"/></a:solidFill><a:round/><a:headEnd/><a:tailEnd/></a:ln>` +
`</wps:spPr><wps:bodyPr/></wps:wsp>` +
`</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
const block = doc.blocks[0]
expect(block.decorative).toBe(true)
expect(block.ruleColorHex).toBe('000000')
expect(block.ruleThicknessPx).toBe(1)
expect(block.ruleWidthPx).toBe(706)
})
it('a zero-extent drawing does not become a rule', async () => {
const body =
`<w:p><w:r><w:drawing><wp:inline><wp:extent cx="0" cy="0"/>` +
`<a:graphic><a:graphicData uri="${SHAPE_URI}"><wps:wsp ${WPS_NS}><wps:spPr/></wps:wsp>` +
`</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
expect(doc.blocks[0].decorative).toBeFalsy()
})
})
describe('text-empty filled textboxes', () => {
it('a white full-page box with empty paragraphs keeps its extent as a fill-only box', async () => {
const body = anchorParagraph(
`<wps:wsp ${WPS_NS}><wps:cNvSpPr txBox="1"/><wps:spPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="7078980" cy="9629775"/></a:xfrm>` +
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
`<a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill>` +
`<a:ln w="9525"><a:noFill/></a:ln>` +
`</wps:spPr><wps:txbx><w:txbxContent><w:p/><w:p/></w:txbxContent></wps:txbx>` +
`<wps:bodyPr><a:noAutofit/></wps:bodyPr></wps:wsp>`,
SHAPE_URI,
)
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
const box = doc.blocks[0].textboxes?.[0]
expect(box).toBeTruthy()
expect(box!.fill).toBe('FFFFFF')
// display keeps the pure-ink extent, but the w:txbxContent stays
// addressable so typing into the empty box still commits
expect(box!.readOnly).toBeUndefined()
expect(box!.txbxIndex).toBe(0)
expect(box!.paras).toEqual([])
expect(box!.heightPx).toBe(Math.round(9629775 / 9525))
})
it('a text-empty box without visible ink still renders nothing', async () => {
const body = anchorParagraph(
`<wps:wsp ${WPS_NS}><wps:cNvSpPr txBox="1"/><wps:spPr>` +
`<a:xfrm><a:off x="0" y="0"/><a:ext cx="952500" cy="476250"/></a:xfrm>` +
`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/>` +
`</wps:spPr><wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx>` +
`<wps:bodyPr/></wps:wsp>`,
SHAPE_URI,
)
const doc = await parseDocx(await buildDocx({ bodyXml: body }))
expect(doc.blocks[0].textboxes).toBeUndefined()
})
})
describe('centered wrapSquare pictures', () => {
it('positionH align=center + wrapSquare maps to the centered topBottom slot', async () => {
const body =
`<w:p><w:r><w:drawing><wp:anchor behindDoc="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">` +
`<wp:simplePos x="0" y="0"/>` +
`<wp:positionH relativeFrom="column"><wp:align>center</wp:align></wp:positionH>` +
`<wp:positionV relativeFrom="paragraph"><wp:posOffset>133350</wp:posOffset></wp:positionV>` +
`<wp:extent cx="3293110" cy="594360"/>` +
`<wp:wrapSquare wrapText="bothSides"/>` +
`<wp:docPr id="1" name="Image 1"/>` +
`<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">` +
`<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>` +
`</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: body, withImage: true }))
const block = doc.blocks[0]
expect(block.type).toBe('image')
expect(block.imageWrap).toBe('topBottom')
expect(block.imageOffsetXEmu).toBeUndefined()
expect(block.imageOffsetYEmu).toBe(133350)
})
it('a left-offset wrapSquare picture keeps the square-left float', async () => {
const body =
`<w:p><w:r><w:drawing><wp:anchor behindDoc="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">` +
`<wp:simplePos x="0" y="0"/>` +
`<wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH>` +
`<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>` +
`<wp:extent cx="3293110" cy="594360"/>` +
`<wp:wrapSquare wrapText="bothSides"/>` +
`<wp:docPr id="1" name="Image 1"/>` +
`<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">` +
`<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>` +
`</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: body, withImage: true }))
expect(doc.blocks[0].imageWrap).toBe('square-left')
})
})
+39
View File
@@ -73,3 +73,42 @@ describe('tab stops roundtrip', () => {
expect(xml).toContain('w:pos="2880"')
})
})
describe('w:ptab absolute position tabs', () => {
const PTAB_P =
'<w:p><w:r><w:t>1. Introduction</w:t></w:r>' +
'<w:r><w:ptab w:relativeTo="margin" w:alignment="right" w:leader="dot"/></w:r>' +
'<w:r><w:t xml:space="preserve"> </w:t></w:r></w:p>'
it('parses into a display-only margin-relative stop and a tab character', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: PTAB_P }))
const block = doc.blocks[0]
expect(block.runs?.map((r) => r.text).join('')).toBe('1. Introduction\t ')
expect(block.format?.tabStops).toEqual([
{ pos: 100, val: 'right', leader: 'dot', rel: 'margin' },
])
})
it('rel stops never reach w:tabs: untouched paragraph saves byte-identical', async () => {
const bytes = await buildDocx({ bodyXml: PTAB_P })
const doc = await parseDocx(bytes)
const saved = await saveDocx(doc, [{ kind: 'original', docxIndex: 0 }])
const reparsed = await parseDocx(saved)
expect(reparsed.internal.documentXml).toContain('<w:ptab')
expect(reparsed.internal.documentXml).not.toContain('<w:tabs>')
})
it('regenerating a format with only rel stops emits no w:tabs', async () => {
const { generateParagraphXml } = await import('../src/generate')
const block = {
type: 'paragraph' as const,
runs: [{ text: 'test' }],
format: { tabStops: [{ pos: 100, val: 'right', rel: 'margin' }] as TabStop[] },
}
const xml = generateParagraphXml(block, {
headingStyleIds: new Map(),
allocateHyperlinkRel: () => 'rId1',
})
expect(xml).not.toContain('<w:tabs>')
})
})
+229 -50
View File
@@ -145,21 +145,23 @@ describe('textbox editing', () => {
})
it('regenerates changed paragraphs from rich runs and keeps unchanged bytes', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[
para({
runs: [
{
text: '**Current date:** July 21',
font: 'Courier New',
color: '415461',
sizeHalfPoints: 22,
},
],
}),
null, // untouched
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [
[
para({
runs: [
{
text: '**Current date:** July 21',
font: 'Courier New',
color: '415461',
sizeHalfPoints: 22,
},
],
}),
null, // untouched
],
],
])
})
expect(out).toContain('<w:t xml:space="preserve">**Current date:** July 21</w:t>')
expect(out).not.toContain('{Month}')
// rich run styles regenerated from the Run model
@@ -176,17 +178,19 @@ describe('textbox editing', () => {
})
it('applies new run formatting (color, bold) to edited paragraphs', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[
para({
runs: [
{ text: 'red part', color: 'FF0000' },
{ text: ' bold part', bold: true, sizeHalfPoints: 28 },
],
}),
null,
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [
[
para({
runs: [
{ text: 'red part', color: 'FF0000' },
{ text: ' bold part', bold: true, sizeHalfPoints: 28 },
],
}),
null,
],
],
])
})
expect(out).toContain(
'<w:r><w:rPr><w:color w:val="FF0000"/></w:rPr><w:t xml:space="preserve">red part</w:t></w:r>',
)
@@ -196,69 +200,75 @@ describe('textbox editing', () => {
})
it('rewrites, keeps, or removes w:jc according to align', () => {
const centered = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[para({ runs: [{ text: 'Hi' }], align: 'center' }), null],
])
const centered = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [[para({ runs: [{ text: 'Hi' }], align: 'center' }), null]],
})
expect(centered).toContain(
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t xml:space="preserve">Hi</w:t></w:r></w:p>',
)
// align undefined keeps the template pPr (second para is centered)
const kept = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[null, para({ runs: [{ text: 'STILL', bold: true }] })],
])
const kept = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [[null, para({ runs: [{ text: 'STILL', bold: true }] })]],
})
expect(kept).toContain(
'<w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:bCs/></w:rPr><w:t xml:space="preserve">STILL</w:t></w:r>',
)
// align null strips the centered jc from the second paragraph
const removed = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[null, para({ runs: [{ text: 'LEFT', bold: true }], align: null })],
])
const removed = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [[null, para({ runs: [{ text: 'LEFT', bold: true }], align: null })]],
})
expect(removed).toContain(
'<w:p><w:r><w:rPr><w:b/><w:bCs/></w:rPr><w:t xml:space="preserve">LEFT</w:t></w:r></w:p>',
)
})
it('patches the VML fallback twin with the same paragraphs', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [[para({ runs: [{ text: 'NEW' }] }), null]])
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [[para({ runs: [{ text: 'NEW' }] }), null]],
})
const hits = out.match(/<w:t xml:space="preserve">NEW<\/w:t>/g) ?? []
expect(hits).toHaveLength(2) // mc:Choice + mc:Fallback
expect(out).not.toContain('{Month}')
})
it('added paragraphs inherit the last original pPr; removed ones drop', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[null, null, para({ runs: [{ text: 'line3', bold: true }] }), para({ runs: [] })],
])
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [[null, null, para({ runs: [{ text: 'line3', bold: true }] }), para({ runs: [] })]],
})
// new paragraph reuses the centered pPr of the last original
expect(out).toContain(
'<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/><w:bCs/></w:rPr><w:t xml:space="preserve">line3</w:t></w:r></w:p>',
)
// empty paragraph keeps pPr only
expect(out).toContain('<w:p><w:pPr><w:jc w:val="center"/></w:pPr></w:p>')
const fewer = patchTextboxParas(TEXTBOX_PARAGRAPH, [[para({ runs: [{ text: 'only line' }] })]])
const fewer = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [[para({ runs: [{ text: 'only line' }] })]],
})
expect(fewer).not.toContain('CRITICAL')
})
it('escapes special characters and converts tabs/newlines to OOXML elements', () => {
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[para({ runs: [{ text: 'a < b & c\tD\nE' }] }), null],
])
const out = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [[para({ runs: [{ text: 'a < b & c\tD\nE' }] }), null]],
})
expect(out).toContain(
'<w:t xml:space="preserve">a &lt; b &amp; c</w:t><w:tab/><w:t xml:space="preserve">D</w:t><w:br/><w:t xml:space="preserve">E</w:t>',
)
})
it('round-trips: patched XML re-parses with the new rich formatting', async () => {
const patched = patchTextboxParas(TEXTBOX_PARAGRAPH, [
[
para({
runs: [{ text: '**Current date:** July 21', font: 'Courier New', color: 'FF0000' }],
}),
para({ runs: [{ text: 'IMPORTANT', bold: true, color: '0070C0' }], align: 'center' }),
const patched = patchTextboxParas(TEXTBOX_PARAGRAPH, {
byIndex: [
[
para({
runs: [{ text: '**Current date:** July 21', font: 'Courier New', color: 'FF0000' }],
}),
para({ runs: [{ text: 'IMPORTANT', bold: true, color: '0070C0' }], align: 'center' }),
],
],
])
})
const doc = await parseDocx(await buildDocx({ bodyXml: patched }))
const box = doc.blocks[0].textboxes?.[0]
expect(box?.fill).toBe('F5F5F5')
@@ -273,9 +283,178 @@ describe('textbox editing', () => {
})
it('leaves the paragraph untouched when every box is null', () => {
expect(patchTextboxParas(TEXTBOX_PARAGRAPH, [null])).toBe(TEXTBOX_PARAGRAPH)
expect(patchTextboxParas('<w:p><w:r><w:t>plain</w:t></w:r></w:p>', [])).toBe(
expect(patchTextboxParas(TEXTBOX_PARAGRAPH, { byIndex: [null] })).toBe(TEXTBOX_PARAGRAPH)
expect(patchTextboxParas('<w:p><w:r><w:t>plain</w:t></w:r></w:p>', {})).toBe(
'<w:p><w:r><w:t>plain</w:t></w:r></w:p>',
)
})
})
const wspShape = (opts: {
id?: string
prst?: string
txbx?: string
bodyPr?: string
fill?: string
}): string =>
'<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
(opts.id !== undefined ? `<wps:cNvPr id="${opts.id}" name="Shape ${opts.id}"/>` : '') +
'<wps:cNvSpPr/>' +
'<wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1800000" cy="1080000"/></a:xfrm>' +
`<a:prstGeom prst="${opts.prst ?? 'star5'}"><a:avLst/></a:prstGeom>` +
`<a:solidFill><a:srgbClr val="${opts.fill ?? '4472C4'}"/></a:solidFill></wps:spPr>` +
(opts.txbx ?? '') +
(opts.bodyPr ?? '') +
'</wps:wsp>'
/** anchored drawing holding several shapes (each in its own anchor, one run) */
const drawingParagraph = (shapes: string[]): string =>
'<w:p><w:r>' +
shapes
.map(
(wsp) =>
'<w:drawing>' +
'<wp:anchor behindDoc="0" simplePos="0" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/><wp:extent cx="1800000" cy="1080000"/>' +
'<wp:wrapSquare wrapText="bothSides"/>' +
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
wsp +
'</a:graphicData></a:graphic></wp:anchor></w:drawing>',
)
.join('') +
'</w:r></w:p>'
const EMPTY_TXBX = '<wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx>'
const HELLO_TXBX =
'<wps:txbx><w:txbxContent><w:p><w:r><w:t>hello</w:t></w:r></w:p></w:txbxContent></wps:txbx>'
describe('textbox patch addressing', () => {
const MIXED = drawingParagraph([
wspShape({ id: '10', txbx: EMPTY_TXBX }),
wspShape({ id: '11', txbx: HELLO_TXBX }),
])
it('parse surfaces txbxIndex/shapeId; empty and textless ink shapes stay editable', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml: drawingParagraph([wspShape({ id: '7' }), wspShape({ id: '8', txbx: HELLO_TXBX })]),
}),
)
const boxes = doc.blocks[0].textboxes ?? []
expect(boxes).toHaveLength(2)
// textless ink shape: no segment to patch, addressable by cNvPr id
expect(boxes[0]).toMatchObject({ shapeId: '7', vAlign: 'center' })
expect(boxes[0].txbxIndex).toBeUndefined()
expect(boxes[0].readOnly).toBeUndefined()
expect(boxes[1]).toMatchObject({ shapeId: '8', txbxIndex: 0 })
expect(boxes[1].readOnly).toBeUndefined()
})
it('a textless shape without a cNvPr id stays read-only', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: drawingParagraph([wspShape({})]) }))
expect(doc.blocks[0].textboxes?.[0].readOnly).toBe(true)
})
it('empty w:txbxContent segments still consume an ordinal on both sides', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: MIXED }))
const boxes = doc.blocks[0].textboxes ?? []
expect(boxes.map((b) => b.txbxIndex)).toEqual([0, 1])
expect(boxes[0].readOnly).toBeUndefined() // empty ink box: typing commits
// patching ordinal 1 must land in the second segment, not the first
const out = patchTextboxParas(MIXED, {
byIndex: [undefined, [para({ runs: [{ text: 'edited' }] })]],
})
expect(out).toContain('<w:t xml:space="preserve">edited</w:t>')
expect(out).not.toContain('hello')
expect(out).toContain('<w:txbxContent><w:p/></w:txbxContent>') // first box untouched
})
it('injects a fresh wps:txbx before bodyPr with centered defaults', async () => {
const source = drawingParagraph([wspShape({ id: '5', bodyPr: '<wps:bodyPr rot="0"/>' })])
const out = patchTextboxParas(source, {
inject: [{ shapeId: '5', paras: [{ runs: [{ text: 'typed' }], align: 'center' }] }],
})
expect(out).toContain(
'<wps:txbx><w:txbxContent><w:p><w:pPr><w:jc w:val="center"/></w:pPr>' +
'<w:r><w:t xml:space="preserve">typed</w:t></w:r></w:p></w:txbxContent></wps:txbx>' +
'<wps:bodyPr anchor="ctr" rot="0"/>',
)
// round-trip: the reopened shape carries the text, centered both ways
const doc = await parseDocx(await buildDocx({ bodyXml: out }))
const box = doc.blocks[0].textboxes?.[0]
expect(box?.paras[0].runs[0].text).toBe('typed')
expect(box?.paras[0].align).toBe('center')
expect(box?.vAlign).toBe('center')
expect(box?.txbxIndex).toBe(0)
})
it('inject keeps an explicit anchor and adds bodyPr when missing', () => {
const anchored = patchTextboxParas(
drawingParagraph([wspShape({ id: '5', bodyPr: '<wps:bodyPr anchor="t"/>' })]),
{ inject: [{ shapeId: '5', paras: [{ runs: [{ text: 'x' }] }] }] },
)
expect(anchored).toContain('<wps:bodyPr anchor="t"/>')
expect(anchored).not.toContain('anchor="ctr"')
const noBodyPr = patchTextboxParas(drawingParagraph([wspShape({ id: '5' })]), {
inject: [{ shapeId: '5', paras: [{ runs: [{ text: 'x' }] }] }],
})
expect(noBodyPr).toContain('</w:txbxContent></wps:txbx><wps:bodyPr anchor="ctr"/></wps:wsp>')
})
it('inject onto a shape that already has a txbx rewrites its content instead', () => {
const out = patchTextboxParas(drawingParagraph([wspShape({ id: '5', txbx: HELLO_TXBX })]), {
inject: [{ shapeId: '5', paras: [{ runs: [{ text: 'replaced' }] }] }],
})
expect(out).toContain('replaced')
expect(out).not.toContain('hello')
expect((out.match(/<wps:txbx>/g) ?? []).length).toBe(1)
})
it('a shape nested inside another box consumes no ordinal and stays read-only', async () => {
const inner = wspShape({ id: '30', txbx: HELLO_TXBX })
const outerTxbx =
'<wps:txbx><w:txbxContent><w:p><w:r><w:t>outer</w:t></w:r></w:p>' +
'<w:p><w:r><w:drawing><wp:inline><wp:extent cx="900000" cy="900000"/>' +
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
inner +
'</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>' +
'</w:txbxContent></wps:txbx>'
const bodyXml = drawingParagraph([
wspShape({ id: '31', txbx: outerTxbx }),
wspShape({
id: '32',
txbx: '<wps:txbx><w:txbxContent><w:p><w:r><w:t>last</w:t></w:r></w:p></w:txbxContent></wps:txbx>',
}),
])
const doc = await parseDocx(await buildDocx({ bodyXml }))
const boxes = doc.blocks[0].textboxes ?? []
expect(boxes).toHaveLength(3)
// outer box: commit would flatten the nested shape away
expect(boxes[0]).toMatchObject({ txbxIndex: 0, readOnly: true })
// nested box: unaddressable, xmlSegments never sees its segment
expect(boxes[1].readOnly).toBe(true)
expect(boxes[1].txbxIndex).toBeUndefined()
expect(boxes[1].shapeId).toBeUndefined()
// the box after the nested one still lines up with its top-level segment
expect(boxes[2]).toMatchObject({ shapeId: '32', txbxIndex: 1 })
const out = patchTextboxParas(bodyXml, {
byIndex: [undefined, [para({ runs: [{ text: 'edited' }] })]],
})
expect(out).toContain('edited')
expect(out).not.toContain('last')
expect(out).toContain('outer')
expect(out).toContain('hello')
})
it('inject targets the shape by id, not by position', () => {
const out = patchTextboxParas(
drawingParagraph([wspShape({ id: '20', txbx: HELLO_TXBX }), wspShape({ id: '21' })]),
{ inject: [{ shapeId: '21', paras: [{ runs: [{ text: 'second' }] }] }] },
)
expect(out).toContain('hello') // first shape untouched
expect(out).toContain('second')
expect(out.indexOf('second')).toBeGreaterThan(out.indexOf('hello'))
})
})