Sync snapshot (2026-09-02) (#181)

- Docs: DOCX rendering and pagination fidelity (page borders, VML pictures, header/footer images, cross-page tables, anchored floats, character-unit indents, CJK typography)
- Docs: more reliable PDF export for huge documents; AI rewrites keep the replaced content's formatting
- Sheets: merge workbooks; Excel-standard keyboard shortcuts; PDF export with header/footer variants and pictures
- Sheets: rendering, conditional formatting, chart and formula fidelity fixes; right-to-left sheet support
- Slides: WordArt text warp, improved text layout and font substitution; AI table edits keep formatting

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-09-03 00:12:17 +08:00
committed by GitHub
co-authored by GenOffice
parent 93b8938c45
commit 9f971edafa
491 changed files with 128943 additions and 103513 deletions
+20
View File
@@ -63,6 +63,14 @@ export function parseChartPartXml(
? scatterStyle === undefined || scatterStyle.toLowerCase().includes('marker')
: false
const scatterLines = kind === 'scatter' && /line|smooth/i.test(scatterStyle ?? '')
const holeVal = attrsOf(findChild(plot, 'c:holeSize') ?? {})['val']
const holePct =
nameOf(plot) === 'c:doughnutChart'
? holeVal !== undefined
? parseInt(holeVal, 10) || 0
: 50
: 0
const legendPos = legendPosOf(chart)
let categories: string[] = []
const series: ChartSeries[] = []
@@ -115,6 +123,8 @@ export function parseChartPartXml(
...(horizontal ? { horizontal } : {}),
...(grouping ? { grouping } : {}),
...(markers ? { markers } : {}),
...(holePct > 0 ? { holePct } : {}),
...(legendPos ? { legendPos } : {}),
...(title !== undefined ? { title } : {}),
categories,
series,
@@ -122,6 +132,16 @@ export function parseChartPartXml(
}
}
const LEGEND_POSITIONS = new Set(['b', 'l', 'r', 't', 'tr'])
/** c:legend position; the schema default when c:legendPos is absent is "r" */
function legendPosOf(chart: XNode): ChartDisplay['legendPos'] {
const legend = findChild(chart, 'c:legend')
if (!legend) return undefined
const val = attrsOf(findChild(legend, 'c:legendPos') ?? {})['val']
return (val !== undefined && LEGEND_POSITIONS.has(val) ? val : 'r') as ChartDisplay['legendPos']
}
/** numeric cache of a c:val / c:yVal / c:xVal / c:bubbleSize container */
function cacheNumbers(container: XNode): (number | null)[] {
return cachePoints(container).map((v) => {
+80 -10
View File
@@ -1,4 +1,5 @@
import type {
CharIndents,
GeneratedBlock,
ImageWrap,
ParaFormat,
@@ -1153,7 +1154,8 @@ function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
// into the margin) are valid and must survive a paragraph rebuild; the
// old > 0 guard silently dropped them, shifting rebuilt paragraphs
// rightward on save (alpha ledger r116).
if (format.indentLeft) indAttrs.push(`w:left="${Math.round(format.indentLeft)}"`)
// explicit w:left="0" must be written back: it cancels a numbering-level indent
if (format.indentLeft !== undefined) indAttrs.push(`w:left="${Math.round(format.indentLeft)}"`)
if (format.indentRight) indAttrs.push(`w:right="${Math.round(format.indentRight)}"`)
if (format.indentFirstLine) {
if (format.indentFirstLine > 0)
@@ -1289,14 +1291,14 @@ function rawIndUnchanged(raw: string | undefined, f: ParaFormat): boolean {
const right = parseInt(rawAttr(raw, 'w:right') ?? rawAttr(raw, 'w:end') ?? '', 10)
const firstLine = parseInt(rawAttr(raw, 'w:firstLine') ?? '', 10)
const hanging = parseInt(rawAttr(raw, 'w:hanging') ?? '', 10)
const rawLeft = Number.isFinite(left) && left !== 0 ? left : undefined
// left mirrors the parse side: explicit 0 stays distinct from absent
const rawLeft = Number.isFinite(left) ? left : undefined
const rawRight = Number.isFinite(right) && right !== 0 ? right : undefined
const rawFirst = hanging > 0 ? -hanging : firstLine > 0 ? firstLine : undefined
const norm = (v: number | undefined) => (v ? Math.round(v) : undefined)
const normLeft = f.indentLeft !== undefined ? Math.round(f.indentLeft) : undefined
return (
rawLeft === norm(f.indentLeft) &&
rawRight === norm(f.indentRight) &&
rawFirst === norm(f.indentFirstLine)
rawLeft === normLeft && rawRight === norm(f.indentRight) && rawFirst === norm(f.indentFirstLine)
)
}
@@ -1376,7 +1378,47 @@ function rawFramePrUnchanged(raw: string | undefined, f: ParaFormat): boolean {
}
/** True when re-parsing the raw child yields the current model value, i.e. the group was not edited */
function pprGroupUnchanged(tag: string, raw: string | undefined, f: ParaFormat): boolean {
/**
* Same indent in two format models (twips, rounded like the emitted attributes).
* Used when the caller knows the paragraph's parsed format: a raw w:ind whose
* character-unit attributes (w:firstLineChars…) resolved to the model's twips
* has no twips twin to compare against, so raw-vs-model would rebuild it and
* lose the character unit on an unrelated format edit.
*/
function sameIndent(a: ParaFormat, b: ParaFormat): boolean {
const norm = (v: number | undefined) => (v !== undefined ? Math.round(v) : undefined)
const nz = (v: number | undefined) => (v ? Math.round(v) : undefined)
return (
norm(a.indentLeft) === norm(b.indentLeft) &&
nz(a.indentRight) === nz(b.indentRight) &&
nz(a.indentFirstLine) === nz(b.indentFirstLine)
)
}
/**
* Cancel attributes for the character-unit indents a paragraph was laid out
* with. A rebuilt w:ind carries twips only, and Word keeps preferring a
* `*Chars` from the style chain over a twips twin (probed) — so an indent edit
* on a paragraph in a CJK "first line 2 characters" style must write the
* explicit `w:firstLineChars="0"` Word itself writes for pt indents, or the
* style's character indent supersedes the edit on reload.
*/
function charIndentCancelAttrs(chars: CharIndents | undefined): string[] {
if (!chars) return []
const out: string[] = []
if (chars.left) out.push('w:leftChars="0"')
if (chars.right) out.push('w:rightChars="0"')
if (chars.hanging) out.push('w:hangingChars="0"')
else if (chars.firstLine) out.push('w:firstLineChars="0"')
return out
}
function pprGroupUnchanged(
tag: string,
raw: string | undefined,
f: ParaFormat,
original?: ParaFormat,
): boolean {
switch (tag) {
case 'w:pageBreakBefore':
return rawBool(raw) === !!f.pageBreakBefore
@@ -1393,6 +1435,12 @@ function pprGroupUnchanged(tag: string, raw: string | undefined, f: ParaFormat):
case 'w:spacing':
return rawSpacingUnchanged(raw, f)
case 'w:ind':
if (original !== undefined) {
if (sameIndent(original, f)) return true
// laid out with character-unit indents (possibly from the style alone, with no
// raw w:ind at all): the edit must rebuild so the cancel attributes get written
if (original.charIndents) return false
}
return rawIndUnchanged(raw, f)
case 'w:pBdr':
return rawPBdrUnchanged(raw, f)
@@ -1419,16 +1467,38 @@ function pprGroupUnchanged(tag: string, raw: string | undefined, f: ParaFormat):
* the current model value the group was not edited and keeps its original bytes,
* so unmodeled attributes (w:firstLineChars, w:afterLines, autospacing, border
* colors, shading patterns…) survive. Only genuinely changed groups are rebuilt
* from the model (at their schema position) — a rebuilt w:ind intentionally drops
* firstLineChars/leftChars so the user's new twips indent wins over the CJK
* from the model (at their schema position) — a rebuilt w:ind is written in twips
* and, when the paragraph was laid out with character-unit indents, carries the
* `*Chars="0"` that cancels them, so the user's new indent wins over the CJK
* char-unit variant Word would otherwise prefer. Everything unmanaged — keepNext,
* paragraph-mark rPr, pPrChange revision records... — keeps its original bytes.
* When format.tabStops is set, w:tabs is also managed (replaced or removed).
* When format.dropCap is set, w:framePr is also managed.
* `original` is the paragraph's parsed format when the caller has it: an indent
* equal to it keeps its raw bytes even when those bytes carry no twips twin
* (character-unit indents resolved at parse time), and its `charIndents` say
* which cancel attributes an indent edit has to write.
*/
export function mergePPrFormat(rawPPr: string, format: ParaFormat | undefined): string {
export function mergePPrFormat(
rawPPr: string,
format: ParaFormat | undefined,
original?: ParaFormat,
): string {
const open = /^<w:pPr(?: [^>]*)?>/.exec(rawPPr)?.[0]
const fresh = formatPPrChildren(format)
// an indent edit on a paragraph laid out with character-unit indents: the
// twips-only rebuild also cancels them (`w:firstLineChars="0"`…), or Word — and
// this parser — would keep resolving the character indent over the new value
if (original?.charIndents && !sameIndent(original, format ?? {})) {
const cancel = charIndentCancelAttrs(original.charIndents)
const at = fresh.findIndex((c) => c.name === 'w:ind')
const xml =
at === -1
? `<w:ind ${cancel.join(' ')}/>`
: fresh[at].xml.replace(/\/>$/, ` ${cancel.join(' ')}/>`)
if (at === -1) fresh.push({ name: 'w:ind', xml })
else fresh[at] = { name: 'w:ind', xml }
}
if (!open) {
// '<w:pPr/>' or unrecognized: rebuild from the format model alone, in schema order
// (formatPPrChildren emits by concern, and CT_PPr order is not optional)
@@ -1447,7 +1517,7 @@ export function mergePPrFormat(rawPPr: string, format: ParaFormat | undefined):
const rawChildren = splitXmlChildren(inner)
const rawOf = (tag: string) => rawChildren.find((c) => c.name === tag)?.xml
const rebuilt = new Set(
[...managedTags].filter((tag) => !pprGroupUnchanged(tag, rawOf(tag), format ?? {})),
[...managedTags].filter((tag) => !pprGroupUnchanged(tag, rawOf(tag), format ?? {}, original)),
)
const rank = (n: string) => PPR_CHILD_ORDER.indexOf(n)
// the interleave below walks freshOut once with a monotonic index, so it has to arrive in
+8 -2
View File
@@ -1,6 +1,11 @@
import { convertEmfToDataUrl, convertWmfToDataUrl } from './vendor/emf-converter/index.mjs'
const EMF_MIMES = new Set(['image/emf', 'image/x-emf'])
// localized GDI facenames mapped to their CSS-resolvable names
const FONT_FAMILY_MAP = {
游ゴシック: 'Yu Gothic', // yuu goshikku
游明朝: 'Yu Mincho', // yuu minchou
}
const WMF_MIMES = new Set(['image/wmf', 'image/x-wmf'])
// gzip-compressed metafiles (.emz/.wmz)
const EMZ_MIMES = new Set(['image/emz', 'image/x-emz'])
@@ -62,9 +67,10 @@ export async function metafileToDataUrl(
if (looksLikeEmf(u8)) isEmf = true
else if (looksLikeWmf(u8)) isEmf = false
else isEmf = EMF_MIMES.has(mime) || EMZ_MIMES.has(mime)
const opts = { dpiScale: 2, fontFamilyMap: FONT_FAMILY_MAP }
const result = isEmf
? await convertEmfToDataUrl(buffer, { dpiScale: 2 })
: await convertWmfToDataUrl(buffer, { dpiScale: 2 })
? await convertEmfToDataUrl(buffer, opts)
: await convertWmfToDataUrl(buffer, opts)
if (result === null) {
console.warn(`metafileToDataUrl: converter returned null (${mime}, ${u8.byteLength} bytes)`)
}
+4
View File
@@ -72,12 +72,16 @@ export function parseNotesXml(xml: string, kind: NoteKind): NoteInfo[] {
)
const styleId = /<w:pStyle w:val="([^"]+)"/.exec(entryXml)?.[1]
const spacing = noteDirectSpacing(entryXml)
// Word draws the entry number only where a self-reference mark run exists
// (empty-body notes keep their line but show no numeral — Word probe 2026-09-01)
const noRefMark = !/<w:footnoteRef\/>|<w:endnoteRef\/>/.test(entryXml)
return {
id,
text,
...(hasFormat ? { richParas } : {}),
...(styleId ? { styleId } : {}),
...(spacing ? { spacing } : {}),
...(noRefMark ? { noRefMark: true as const } : {}),
}
})
}
@@ -0,0 +1,132 @@
// Whole-document passes run after the block list is built: protected leading
// breaks, balanced DBCS spacing, image z-order normalization.
import type { Block, Run, TableModel, TextboxDisplay } from './types'
/**
* Word writes wp:anchor relativeHeight as 251658240 + rank, which decodes to
* small z-orders; other producers write arbitrary values (LibreOffice: 1, 2,
* …) that decode to huge magnitudes, defeating the editor's ±1 reorder steps
* and its CSS bands. When any decoded rank is wild, re-rank every anchored
* image by its decoded value (stable by document order) starting at 0; rank 0
* is the base level, so its attribute is dropped like an untouched anchor.
*/
/**
* A protected image block swallows the paragraph's runs, so a page-break run
* written before the drawing (`<w:p><w:r><w:br w:type="page"/></w:r><w:r>
* <w:drawing>...`) would silently vanish while Word turns the page there.
* Nothing visible can sit between such a break and the drawing, so the
* paragraph-level pageBreakBefore is an equivalent model.
*/
export function applyProtectedLeadingBreaks(blocks: Block[]): void {
for (const b of blocks) {
if (b.type !== 'image' || b.format?.pageBreakBefore) continue
const xml = b.originalXml
if (!xml) continue
const drawing = xml.search(/<w:drawing[\s>]|<w:pict[\s>]|<w:object[\s>]/)
const head = xml.slice(0, drawing === -1 ? xml.length : drawing)
const br = head.search(/<w:br\s[^>]*w:type="page"/)
if (br === -1) continue
const textBefore = [...head.slice(0, br).matchAll(/<w:t[^>]*>([^<]*)<\/w:t>/g)]
.map((m) => m[1])
.join('')
if (textBefore.trim() === '') b.format = { ...b.format, pageBreakBefore: true }
}
}
/** wide (double-byte) glyph fraction of a run's text (CJK/hangul/fullwidth forms) */
function wideGlyphFraction(text: string): number {
let wide = 0
let n = 0
for (const ch of text) {
const cp = ch.codePointAt(0)!
if (
(cp >= 0x1100 && cp <= 0x11ff) ||
(cp >= 0x2e80 && cp <= 0x9fff) ||
(cp >= 0xac00 && cp <= 0xd7af) ||
(cp >= 0xf900 && cp <= 0xfaff) ||
(cp >= 0xff00 && cp <= 0xff60) ||
cp >= 0x20000
)
wide++
n++
}
return n > 0 ? wide / n : 0
}
/**
* settings.xml balanceSingleByteDoubleByteWidth (standard in HWP-exported
* docx) makes rPr w:spacing count double on double-byte characters: a Word
* probe (2026-08-24) moves hangul advances 2pt per 20 twips with the flag and
* 1pt without, Latin runs unchanged either way. CSS letter-spacing cannot
* vary per character, so scale the display-only charSpacingTwips by each
* run's wide-glyph mix (the charScaleEm approximation precedent); saving
* stays byte-faithful through rawRPr.
*/
export function applyBalancedDbcsSpacing(runGroups: Array<Run[] | undefined>): void {
for (const runs of runGroups) {
if (!runs) continue
for (const r of runs) {
if (!r.charSpacingTwips || !r.text) continue
const frac = wideGlyphFraction(r.text)
if (frac > 0) r.charSpacingTwips = Math.round(r.charSpacingTwips * (1 + frac) * 10) / 10
}
}
}
/** every run container reachable from the parsed blocks (tables, textboxes, nested tables) */
export function blockRunGroups(blocks: Block[]): Array<Run[] | undefined> {
const groups: Array<Run[] | undefined> = []
const fromBoxes = (boxes?: TextboxDisplay[]) => {
for (const box of boxes ?? []) for (const para of box.paras) groups.push(para.runs)
}
const fromTable = (table?: TableModel) => {
if (!table) return
for (const row of table.rows) {
for (const cell of row) {
for (const para of cell.richParas ?? []) groups.push(para.runs)
fromBoxes(cell.anchoredBoxes)
for (const nested of cell.nestedTables ?? []) fromTable(nested)
}
}
}
for (const b of blocks) {
groups.push(b.runs)
groups.push(b.strayRuns)
fromTable(b.table ?? undefined)
fromBoxes(b.textboxes)
}
return groups
}
export function normalizeImageZOrders(blocks: Block[]): void {
// images and floating shapes share Word's z space: rank them together so
// cross-type overlaps (photo over a background shape) keep their order
const anchored: Array<{ get: () => number; set: (rank: number) => void }> = []
for (const b of blocks) {
if (b.imageZOrder !== undefined) {
anchored.push({
get: () => b.imageZOrder!,
set: (rank) => {
if (rank === 0) delete b.imageZOrder
else b.imageZOrder = rank
// raw XML still carries the wild value; flag for save-time harmonization
b.imageZOrderNormalized = true
},
})
}
for (const box of b.textboxes ?? []) {
if (box.z !== undefined) {
anchored.push({
get: () => box.z!,
// display-only: the box's XML keeps its raw relativeHeight
set: (rank) => (box.z = rank),
})
}
}
}
if (!anchored.some((e) => Math.abs(e.get()) > 10000)) return
anchored
.map((e, i) => ({ e, i }))
.sort((x, y) => x.e.get() - y.e.get() || x.i - y.i)
.forEach(({ e }, rank) => e.set(rank))
}
@@ -0,0 +1,557 @@
// DrawingML geometry and color helpers: line presets, scheme/preset colors,
// anchor metadata and page-position resolution, group transforms.
import { attrsOf, childrenOf, findChild, nameOf, type XNode } from './xml-utils'
import { EMU_PER_PX } from './parse-xml-text'
import type { SectionSettings, TextboxDisplay, ThemeColors } from './types'
/**
* Display-only extraction of anchored textboxes: DrawingML (wps:wsp, converter
* output for code boxes / callout cards) and legacy VML (v:shape etc. inside
* w:pict, common in broker research templates). Expects
* fallback-stripped XML, otherwise the mc:Fallback VML twin would duplicate
* every box.
*/
export const LINE_PRSTS_RE =
/<a:prstGeom[^>]*prst="(?:line|straightConnector1|bentConnector[234]|curvedConnector[234])"/
/** stroke-only line/connector prsts shown as display boxes despite no text body */
export const LINE_PRSTS = new Set([
'line',
'straightConnector1',
'bentConnector2',
'bentConnector3',
'bentConnector4',
'curvedConnector2',
'curvedConnector3',
'curvedConnector4',
])
/** wps line shape → display-only line box (synthetic prst carries the arrow ends) */
export function lineBoxOf(shape: XNode, theme?: ThemeColors | null): TextboxDisplay | null {
const spPr = findChild(shape, 'wps:spPr')
if (!spPr) return null
const prst = attrsOf(findChild(spPr, 'a:prstGeom') ?? {})['prst']
if (!prst || !LINE_PRSTS.has(prst)) return null
const box: TextboxDisplay = { paras: [], readOnly: true }
const ln = findChild(spPr, 'a:ln')
const border =
(ln
? attrsOf(findChild(findChild(ln, 'a:solidFill') ?? {}, 'a:srgbClr') ?? {})['val']
: undefined) ??
// theme-styled connectors (Word gallery): stroke from wps:style a:lnRef
colorNodeHex(findChild(findChild(shape, 'wps:style') ?? {}, 'a:lnRef'), theme)
box.borderColor = border ?? '000000'
const arrowEnd = (name: string): boolean => {
const type = attrsOf(findChild(ln ?? {}, name) ?? {})['type']
return !!type && type !== 'none'
}
const head = arrowEnd('a:headEnd')
const tail = arrowEnd('a:tailEnd')
box.prst = prst.startsWith('bentConnector')
? 'lineBent'
: prst.startsWith('curvedConnector')
? 'lineCurved'
: head && tail
? 'lineArrowDouble'
: head || tail
? 'lineArrow'
: 'line'
const xfrm = findChild(spPr, 'a:xfrm')
const xfrmAttrs = attrsOf(xfrm ?? {})
const ext = findChild(xfrm ?? {}, 'a:ext')
const cx = ext ? parseInt(attrsOf(ext)['cx'] ?? '', 10) : NaN
const cy = ext ? parseInt(attrsOf(ext)['cy'] ?? '', 10) : NaN
if (Number.isFinite(cx) && cx > 0) box.widthPx = Math.round(cx / EMU_PER_PX)
const straight = box.prst === 'line' || box.prst === 'lineArrow' || box.prst === 'lineArrowDouble'
// flips apply at any height: Word's horizontal lines carry cy="0", and a
// flipH there still reverses which tip holds the arrow
if (straight) {
if (xfrmAttrs['flipH'] === '1' || xfrmAttrs['flipH'] === 'true') box.flipH = true
if (xfrmAttrs['flipV'] === '1' || xfrmAttrs['flipV'] === 'true') box.flipV = true
}
if (Number.isFinite(cy) && cy > 0) {
box.heightPx = Math.round(cy / EMU_PER_PX)
box.minHeightPx = box.heightPx
// a real vertical extent means the connector runs corner to corner
// (≤12 px stays level: our own inserted lines keep a 12 px grab band)
if (straight && (box.heightPx > 12 || box.flipH || box.flipV)) box.lineDiag = true
} else {
// zero-height extent = Word's horizontal line; keep a 12 px grab band
box.heightPx = 12
}
// a:headEnd decorates the start point: a head-only arrow renders as the
// reversed segment so the renderer's single arrowhead lands on the right tip
if (head && !tail && box.prst === 'lineArrow') {
const fh = !box.flipH
const fv = !box.flipV
delete box.flipH
delete box.flipV
if (fh) box.flipH = true
if (fv) box.flipV = true
}
box.insetTopPx = 0
box.insetRightPx = 0
box.insetBottomPx = 0
box.insetLeftPx = 0
return box
}
/** a:schemeClr val -> ThemeColors slot (DrawingML names; text/bg aliases mapped) */
const SCHEME_CLR_SLOTS: Record<string, keyof ThemeColors> = {
tx1: 'dk1',
bg1: 'lt1',
tx2: 'dk2',
bg2: 'lt2',
dk1: 'dk1',
lt1: 'lt1',
dk2: 'dk2',
lt2: 'lt2',
accent1: 'accent1',
accent2: 'accent2',
accent3: 'accent3',
accent4: 'accent4',
accent5: 'accent5',
accent6: 'accent6',
hlink: 'hlink',
folHlink: 'folHlink',
}
const PRST_CLR_HEX: Record<string, string> = {
black: '000000',
white: 'FFFFFF',
red: 'FF0000',
green: '008000',
blue: '0000FF',
yellow: 'FFFF00',
cyan: '00FFFF',
magenta: 'FF00FF',
gray: '808080',
}
/** one a:gs stop -> sRGB triple (srgbClr/sysClr/prstClr or theme-resolved schemeClr, lumMod/lumOff applied) */
function gradStopRgb(gs: XNode, theme?: ThemeColors | null): number[] | null {
const srgb = attrsOf(findChild(gs, 'a:srgbClr') ?? {})['val']
let base: string | undefined = srgb
if (!base) {
const sys = findChild(gs, 'a:sysClr')
if (sys) {
// Word writes the resolved system color into lastClr
const a = attrsOf(sys)
base = a['lastClr'] ?? (a['val'] === 'windowText' ? '000000' : 'FFFFFF')
}
}
if (!base) {
const prst = findChild(gs, 'a:prstClr')
if (prst) base = PRST_CLR_HEX[attrsOf(prst)['val'] ?? '']
}
const scheme = base ? undefined : findChild(gs, 'a:schemeClr')
if (!base && scheme) {
const slot = SCHEME_CLR_SLOTS[attrsOf(scheme)['val'] ?? '']
if (!slot) return null
base =
(theme?.[slot] as string | undefined) ??
(slot === 'dk1' ? '000000' : slot === 'lt1' ? 'FFFFFF' : undefined)
}
if (!base || !/^[0-9A-Fa-f]{6}$/.test(base)) return null
let rgb = [0, 2, 4].map((i) => parseInt(base!.slice(i, i + 2), 16))
if (scheme) {
const pct = (name: string): number | null => {
const v = parseInt(attrsOf(findChild(scheme, name) ?? {})['val'] ?? '', 10)
return Number.isFinite(v) ? Math.min(100000, Math.max(0, v)) / 100000 : null
}
const lumMod = pct('a:lumMod')
if (lumMod !== null) rgb = rgb.map((c) => c * lumMod)
const lumOff = pct('a:lumOff')
if (lumOff !== null) rgb = rgb.map((c) => c + 255 * lumOff)
const shade = pct('a:shade')
if (shade !== null) rgb = rgb.map((c) => c * shade)
const tint = pct('a:tint')
if (tint !== null) rgb = rgb.map((c) => c * tint + 255 * (1 - tint))
}
return rgb
}
/** color-bearing node (a:solidFill / a:fillRef / a:lnRef …) → hex without '#' */
export function colorNodeHex(
node: XNode | undefined,
theme?: ThemeColors | null,
): string | undefined {
if (!node) return undefined
const rgb = gradStopRgb(node, theme)
if (!rgb) return undefined
return rgb
.map((c) =>
Math.round(Math.min(255, Math.max(0, c)))
.toString(16)
.padStart(2, '0')
.toUpperCase(),
)
.join('')
}
/** anchored-drawing placement of one top-level w:drawing fragment */
export interface DrawingAnchorMeta {
offsetXEmu?: number
offsetYEmu?: number
/** wrapNone (front) / behindDoc anchors leave the text flow entirely */
noWrap?: boolean
/** behindDoc="1": paints under the body text (z-order only) */
behind?: boolean
/** raw page coordinates for a first-page page-anchored cover drawing: the
* renderer resolves the boxes against the page box, not the paragraph */
pageXEmu?: number
pageYEmu?: number
/** wp:wrapTopAndBottom: body text is excluded from the drawing's vertical band */
topBottom?: boolean
anchored?: boolean
/** wp:positionH/V relativeFrom */
relH?: string
relV?: string
/** wp:align inside wp:positionH/V */
alignH?: string
alignV?: string
/** wp14:pctPosH/VOffset in 1/1000 of a percent of the reference frame */
pctH?: number
pctV?: number
/** wp:extent (drawing size) */
extentXEmu?: number
extentYEmu?: number
/** relativeHeight − Word's 251658240 base: paint order among overlapping anchors */
z?: number
}
/**
* Top-level `<w:drawing>` fragments of a paragraph, balanced (a textbox's
* txbxContent may nest further drawings, which stay inside their parent
* fragment). Used to attach each drawing's own anchor placement to the shapes
* it carries — a paragraph can anchor several drawings at distinct offsets.
*/
/** next `<w:drawing>` open tag at or after `from`, attributes tolerated
* (`<w:drawing mc:MustUnderstand="wps">`, TestFiles mcdoc) */
function drawingOpenAt(xml: string, from: number): number {
const re = /<w:drawing[\s>]/g
re.lastIndex = from
return re.exec(xml)?.index ?? -1
}
export function topLevelDrawings(xml: string): string[] {
const out: string[] = []
let i = 0
for (;;) {
const start = drawingOpenAt(xml, i)
if (start === -1) break
let depth = 0
let j = start
for (;;) {
const open = drawingOpenAt(xml, j + 1)
const close = xml.indexOf('</w:drawing>', j + 1)
if (close === -1) return out // malformed; bail with what we have
if (open !== -1 && open < close) {
depth++
j = open
} else if (depth > 0) {
depth--
j = close
} else {
out.push(xml.slice(start, close + '</w:drawing>'.length))
i = close + '</w:drawing>'.length
break
}
}
}
return out
}
export function drawingAnchorMeta(frag: string): DrawingAnchorMeta {
const anchorTag = /<wp:anchor[^>]*>/.exec(frag)?.[0]
if (!anchorTag) return {}
const meta: DrawingAnchorMeta = { anchored: true }
const posOf = (dir: 'H' | 'V'): number | undefined => {
const m = new RegExp(`<wp:position${dir}[^>]*>\\s*<wp:posOffset>(-?\\d+)</wp:posOffset>`).exec(
frag,
)
const v = m ? parseInt(m[1], 10) : NaN
return Number.isFinite(v) ? v : undefined
}
meta.offsetXEmu = posOf('H')
meta.offsetYEmu = posOf('V')
for (const dir of ['H', 'V'] as const) {
const m = new RegExp(`<wp:position${dir}\\b([^>]*)>([\\s\\S]*?)</wp:position${dir}>`).exec(frag)
if (!m) continue
const rel = /relativeFrom="(\w+)"/.exec(m[1])?.[1]
const align = /<wp:align>(\w+)<\/wp:align>/.exec(m[2])?.[1]
const pct = parseInt(
new RegExp(`<wp14:pctPos${dir}Offset[^>]*>(-?\\d+)<`).exec(m[2])?.[1] ?? '',
10,
)
if (dir === 'H') {
meta.relH = rel
meta.alignH = align
if (Number.isFinite(pct)) meta.pctH = pct
} else {
meta.relV = rel
meta.alignV = align
if (Number.isFinite(pct)) meta.pctV = pct
}
}
const extent = /<wp:extent[^>]*cx="(\d+)"[^>]*cy="(\d+)"/.exec(frag)
if (extent) {
meta.extentXEmu = parseInt(extent[1], 10)
meta.extentYEmu = parseInt(extent[2], 10)
}
if (frag.includes('<wp:wrapNone') || /behindDoc="(?:1|true)"/.test(anchorTag)) meta.noWrap = true
if (/behindDoc="(?:1|true)"/.test(anchorTag)) meta.behind = true
const relHeight = Number(/relativeHeight="(\d+)"/.exec(anchorTag)?.[1] ?? NaN)
if (Number.isFinite(relHeight) && relHeight - 251658240 !== 0) meta.z = relHeight - 251658240
// the anchor's own wrap element sits before a:graphic; a nested drawing's
// wrap must not leak up. behindDoc="1" + wrapTopAndBottom coexist in
// generated docs — Word still excludes the band (behindDoc is z-order only)
const graphicAt = frag.indexOf('<a:graphic')
const ownXml = graphicAt === -1 ? frag : frag.slice(0, graphicAt)
if (ownXml.includes('<wp:wrapTopAndBottom')) meta.topBottom = true
return meta
}
export const EMU_PER_TWIP = 635
/** narrowest column gap beside a float that Word still fills with text (36px) */
export const MIN_WRAP_SLIVER_EMU = 36 * 9525
/** anchor position resolved to EMU offsets from the paragraph flow origin
* (column left / body top), page coordinates recoverable via the margins */
export interface ResolvedAnchorPos {
xEmu: number
yEmu?: number
/** the drawing lies horizontally outside the body column (sidebar layout) */
outsideColumn: boolean
}
/**
* Page/margin-anchored placement (wp14:pctPosH/VOffset or wp:align) resolved
* against the section's page geometry. Plain posOffset anchors keep the
* legacy paragraph-relative path untouched — only the features the parser
* previously ignored resolve here, so in-column wrapSquare boxes are not
* repositioned. The vertical origin approximates the anchor paragraph sitting
* at the top of the body (where Word puts these full-height sidebar groups).
*/
export function resolveAnchorPagePos(
meta: DrawingAnchorMeta,
sect: SectionSettings | undefined,
): ResolvedAnchorPos | null {
if (!sect) return null
// column-relative align in a single-column section: the column IS the margin
// box, so it resolves identically (multi-column needs the hosting column and
// stays on the legacy flow placement)
const relH =
meta.relH === 'column' && sect.columns <= 1 && meta.pctH === undefined ? 'margin' : meta.relH
if (relH !== 'page' && relH !== 'margin') return null
if (meta.pctH === undefined && meta.alignH === undefined) return null
const pageW = sect.pageWidth * EMU_PER_TWIP
const pageH = sect.pageHeight * EMU_PER_TWIP
const marL = sect.marginLeft * EMU_PER_TWIP
const marR = sect.marginRight * EMU_PER_TWIP
const marT = sect.marginTop * EMU_PER_TWIP
const w = meta.extentXEmu ?? 0
const refW = relH === 'page' ? pageW : pageW - marL - marR
const relX =
meta.pctH !== undefined
? Math.round((refW * meta.pctH) / 100000)
: meta.alignH === 'center'
? Math.round((refW - w) / 2)
: meta.alignH === 'right' || meta.alignH === 'outside'
? refW - w
: 0
const pageX = relH === 'page' ? relX : marL + relX
const pos: ResolvedAnchorPos = {
xEmu: pageX - marL,
outsideColumn: pageX + w <= marL || pageX >= pageW - marR,
}
if (
(meta.relV === 'page' || meta.relV === 'margin') &&
(meta.pctV !== undefined || meta.alignV !== undefined)
) {
const marB = sect.marginBottom * EMU_PER_TWIP
const h = meta.extentYEmu ?? 0
const refH = meta.relV === 'page' ? pageH : pageH - marT - marB
const relY =
meta.pctV !== undefined
? Math.round((refH * meta.pctV) / 100000)
: meta.alignV === 'center'
? Math.round((refH - h) / 2)
: meta.alignV === 'bottom' || meta.alignV === 'outside'
? refH - h
: 0
pos.yEmu = (meta.relV === 'page' ? relY : marT + relY) - marT
}
return pos
}
/**
* a:gradFill approximated as a solid color (display only): equal-weight sRGB
* average of all stops — the first stop alone is often white and loses the
* visible tint entirely.
*/
export function gradFillApproxHex(spPr: XNode, theme?: ThemeColors | null): string | undefined {
const gsLst = findChild(findChild(spPr, 'a:gradFill') ?? {}, 'a:gsLst')
if (!gsLst) return undefined
const stops = childrenOf(gsLst)
.filter((n) => nameOf(n) === 'a:gs')
.map((gs) => gradStopRgb(gs, theme))
.filter((rgb): rgb is number[] => rgb !== null)
if (stops.length === 0) return undefined
return [0, 1, 2]
.map((i) => stops.reduce((sum, rgb) => sum + rgb[i], 0) / stops.length)
.map((c) =>
Math.round(Math.min(255, Math.max(0, c)))
.toString(16)
.padStart(2, '0')
.toUpperCase(),
)
.join('')
}
/** sRGB triple → hex without '#' */
function rgbHex(rgb: number[]): string {
return rgb
.map((c) =>
Math.round(Math.min(255, Math.max(0, c)))
.toString(16)
.padStart(2, '0')
.toUpperCase(),
)
.join('')
}
/** w14:srgbClr / w14:schemeClr child → sRGB triple with tint/shade/lum/satMod applied */
function w14ColorRgb(node: XNode, theme?: ThemeColors | null): number[] | null {
const colorNode = findChild(node, 'w14:srgbClr') ?? findChild(node, 'w14:schemeClr')
if (!colorNode) return null
const isScheme = nameOf(colorNode) === 'w14:schemeClr'
let base: string | undefined = attrsOf(colorNode)['w14:val']
if (isScheme) {
const slot = SCHEME_CLR_SLOTS[base ?? '']
if (!slot) return null
base =
(theme?.[slot] as string | undefined) ??
(slot === 'dk1' ? '000000' : slot === 'lt1' ? 'FFFFFF' : undefined)
}
if (!base || !/^[0-9A-Fa-f]{6}$/.test(base)) return null
let rgb = [0, 2, 4].map((i) => parseInt(base!.slice(i, i + 2), 16))
const pct = (name: string): number | null => {
const v = parseInt(attrsOf(findChild(colorNode, name) ?? {})['w14:val'] ?? '', 10)
return Number.isFinite(v) && v >= 0 ? v / 100000 : null
}
const lumMod = pct('w14:lumMod')
if (lumMod !== null) rgb = rgb.map((c) => c * lumMod)
const lumOff = pct('w14:lumOff')
if (lumOff !== null) rgb = rgb.map((c) => c + 255 * lumOff)
const shade = pct('w14:shade')
if (shade !== null) rgb = rgb.map((c) => c * shade)
const tint = pct('w14:tint')
if (tint !== null) rgb = rgb.map((c) => c * tint + 255 * (1 - tint))
const satMod = pct('w14:satMod')
if (satMod !== null && satMod !== 1) rgb = saturationModulate(rgb, satMod)
return rgb
}
/** HSL saturation modulation (a:satMod / w14:satMod semantics, clamped) */
function saturationModulate(rgb: number[], mod: number): number[] {
const [r, g, b] = rgb.map((c) => Math.min(255, Math.max(0, c)) / 255) as [number, number, number]
const max = Math.max(r, g, b)
const min = Math.min(r, g, b)
const l = (max + min) / 2
const d = max - min
if (d === 0) return rgb
let s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
const h =
max === r
? ((g - b) / d + (g < b ? 6 : 0)) / 6
: max === g
? ((b - r) / d + 2) / 6
: ((r - g) / d + 4) / 6
s = Math.min(1, s * mod)
const q = l < 0.5 ? l * (1 + s) : l + s - l * s
const p = 2 * l - q
const hue = (t: number): number => {
if (t < 0) t += 1
if (t > 1) t -= 1
if (t < 1 / 6) return p + (q - p) * 6 * t
if (t < 1 / 2) return q
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6
return p
}
return [hue(h + 1 / 3), hue(h), hue(h - 1 / 3)].map((c) => c * 255)
}
/**
* WordArt-styled run text (w14:textFill): solid fill directly, gradient fill
* as the equal-weight average of its stops — display approximation only.
*/
export function w14TextFillHex(rPr: XNode, theme?: ThemeColors | null): string | undefined {
const tf = findChild(rPr, 'w14:textFill')
if (!tf) return undefined
const solid = findChild(tf, 'w14:solidFill')
if (solid) {
const rgb = w14ColorRgb(solid, theme)
return rgb ? rgbHex(rgb) : undefined
}
const gsLst = findChild(findChild(tf, 'w14:gradFill') ?? {}, 'w14:gsLst')
if (!gsLst) return undefined
const stops = childrenOf(gsLst)
.filter((n) => nameOf(n) === 'w14:gs')
.map((gs) => w14ColorRgb(gs, theme))
.filter((rgb): rgb is number[] => rgb !== null)
if (stops.length === 0) return undefined
return rgbHex([0, 1, 2].map((i) => stops.reduce((sum, rgb) => sum + rgb[i], 0) / stops.length))
}
export interface ExtractTextboxOpts {
/** include textless preset shapes (stars, block arrows…) as display boxes */
shapes?: boolean
/** include picture-only drawings (pic:pic without a shape) as picture boxes */
pictures?: boolean
/** page geometry of the governing section (page/margin-anchored placement) */
section?: SectionSettings
/** document.xml byte offset of the host paragraph: textbox paragraphs resolve
* their character-unit indents under that section's document grid */
docOffset?: number
/** the paragraph sits before the first explicit page break: page-V-anchored
* cover art may pin to the page origin instead of the paragraph origin */
firstPage?: boolean
}
/** child-EMU → anchor-EMU affine transform of a wpg group (X = tx + x·sx) */
export interface GroupCtm {
sx: number
sy: number
tx: number
ty: number
}
export const IDENTITY_CTM: GroupCtm = { sx: 1, sy: 1, tx: 0, ty: 0 }
/** wpg:wgp / wpg:grpSp xfrm (off/ext vs chOff/chExt) composed onto `outer` */
export function composeGroupCtm(group: XNode, outer: GroupCtm): GroupCtm | null {
const xfrm = findChild(findChild(group, 'wpg:grpSpPr') ?? {}, 'a:xfrm')
if (!xfrm) return null
const num = (node: XNode | undefined, key: string, dflt: number): number => {
const v = parseInt(attrsOf(node ?? {})[key] ?? '', 10)
return Number.isFinite(v) ? v : dflt
}
const ox = num(findChild(xfrm, 'a:off'), 'x', 0)
const oy = num(findChild(xfrm, 'a:off'), 'y', 0)
const ex = num(findChild(xfrm, 'a:ext'), 'cx', 0)
const ey = num(findChild(xfrm, 'a:ext'), 'cy', 0)
const chOffX = num(findChild(xfrm, 'a:chOff'), 'x', 0)
const chOffY = num(findChild(xfrm, 'a:chOff'), 'y', 0)
const chExtX = num(findChild(xfrm, 'a:chExt'), 'cx', 0)
const chExtY = num(findChild(xfrm, 'a:chExt'), 'cy', 0)
const sx = ex > 0 && chExtX > 0 ? ex / chExtX : 1
const sy = ey > 0 && chExtY > 0 ? ey / chExtY : 1
return {
sx: outer.sx * sx,
sy: outer.sy * sy,
tx: outer.tx + outer.sx * (ox - chOffX * sx),
ty: outer.ty + outer.sy * (oy - chOffY * sy),
}
}
+245
View File
@@ -0,0 +1,245 @@
// Field-code display (PAGE, TOC, REF, ...) and TOC entry numbering.
import { computeListMarkers, type ListItemRef } from './list-markers'
import { decodeEntities, lineTwipsOf, plainText } from './parse-xml-text'
import type { Block, FieldDisplay, NumberingDef, StyleInfo } from './types'
/**
* Display-only rendering hint for protected field paragraphs. The visible
* field *result* (w:t runs; instruction text lives in w:instrText and is
* excluded) is shown instead of a generic chip. Original XML still saves
* byte-identical.
*/
/** TOC entry level: styleId "TOC1" (Word) / "TOC 1" (Pages), or the style's
* name "toc 1" when the styleId is opaque (html2docx exports numeric ids) */
export function tocLevelOf(styleId: string, styles?: Map<string, StyleInfo>): number | null {
const m =
/^TOC ?([1-9])$/i.exec(styleId) ?? /^toc ?([1-9])$/i.exec(styles?.get(styleId)?.name ?? '')
if (m) return parseInt(m[1], 10)
// table-of-figures entries (TOC \c field results) are level-1 toc lines
if (
/^TableofFigures$/i.test(styleId) ||
/^table of figures$/i.test(styles?.get(styleId)?.name ?? '')
)
return 1
return null
}
export function fieldDisplayOf(
xml: string,
styles?: Map<string, StyleInfo>,
): FieldDisplay | undefined {
const styleId = /<w:pStyle w:val="([^"]+)"/.exec(xml)?.[1] ?? ''
const tocLevel = tocLevelOf(styleId, styles)
if (tocLevel !== null) {
// TOC entry: title <tab with dot leader> page number. The page number
// follows the LAST tab — entries like "1.1.<tab>Title<tab>7" put a leading
// outline number at the first tab stop, not the page number.
const segs: string[] = ['']
const re = /<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>|<w:tab\/>/g
let m: RegExpExecArray | null
while ((m = re.exec(xml)) !== null) {
if (m[0] === '<w:tab/>') segs.push('')
else segs[segs.length - 1] += m[1]
}
const right = segs.length > 1 ? segs.pop()! : ''
// a short space-free first segment at its own tab stop is the outline
// number; it renders in the num cell so the title stays clean for
// heading matching (toc-refresh keys on `left`)
let num: string | undefined
if (segs.length > 1) {
const first = decodeEntities(segs[0]).trim()
if (/^\S{1,15}$/.test(first)) {
num = first
segs.shift()
}
}
const left = segs
.map((s) => decodeEntities(s).trim())
.filter(Boolean)
.join(' ')
const anchor = /<w:hyperlink [^>]*w:anchor="([^"]+)"/.exec(xml)?.[1]
// direct pPr/run metrics: Word sizes TOC lines by them while the style
// (html2docx exports) often carries nothing
const pPr = /<w:pPr>[\s\S]*?<\/w:pPr>/.exec(xml)?.[0] ?? ''
const spacingAttrs = /<w:spacing ([^/>]*)\/>/.exec(pPr)?.[1] ?? ''
const line = lineTwipsOf(/w:line="([^"]+)"/.exec(spacingAttrs)?.[1])
// OOXML defaults w:lineRule to auto when omitted
const lineRule = (/w:lineRule="(auto|atLeast|exact)"/.exec(spacingAttrs)?.[1] ?? 'auto') as
'auto' | 'atLeast' | 'exact'
// font size from visible result runs only: field-machinery runs
// (fldChar/instrText) often carry the target heading's size and would
// inflate the whole line
let sz = 0
const runRe = /<w:r(?:\s[^>]*)?>([\s\S]*?)<\/w:r>/g
let run: RegExpExecArray | null
while ((run = runRe.exec(xml)) !== null) {
if (!/<w:t(?:\s|>)/.test(run[1]) || run[1].includes('<w:instrText')) continue
const v = parseInt(/<w:sz w:val="(\d+)"/.exec(run[1])?.[1] ?? '', 10)
if (v > sz) sz = v
}
return {
kind: 'tocLine',
left,
right: decodeEntities(right).trim(),
level: tocLevel,
...(num ? { num } : {}),
...(anchor ? { anchor } : {}),
...(sz > 0 ? { szHalfPoints: sz } : {}),
...(line > 0 && lineRule
? {
lineRule,
lineRawTwips: line,
...(lineRule === 'auto' ? { lineSpacing: Math.round((line / 240) * 100) / 100 } : {}),
}
: {}),
}
}
const visible = plainText(xml).trim()
if (visible === '' && /<w:br\s[^>]*w:type="page"/.test(xml)) {
return { kind: 'pageBreak' }
}
if (visible !== '') {
// face/size of the visible result runs (same rule as tocLine): without
// them the passthrough div inherits the document default and a SimSun
// field paragraph mis-snaps to a double cell on a typed line grid
// dominant size = the size covering the most text: a manual drop-cap letter
// (one 48pt "L" before 10pt body) must not inflate the whole field's strut
// (real_run2/47 rendered the entire paragraph at 48pt, 10 -> 17 pages)
let font: string | undefined
const sizedRuns: Array<{ text: string; szHalfPoints?: number }> = []
const szWeights = new Map<number, number>()
const runRe = /<w:r(?:\s[^>]*)?>([\s\S]*?)<\/w:r>/g
let run: RegExpExecArray | null
while ((run = runRe.exec(xml)) !== null) {
if (!/<w:t(?:\s|>)/.test(run[1]) || run[1].includes('<w:instrText')) continue
const text = decodeEntities(
Array.from(run[1].matchAll(/<w:t[^>]*>([\s\S]*?)<\/w:t>/g), (m) => m[1]).join(''),
)
const v = parseInt(/<w:sz w:val="(\d+)"/.exec(run[1])?.[1] ?? '', 10)
sizedRuns.push({ text, ...(v > 0 ? { szHalfPoints: v } : {}) })
// unsized runs vote for the inherited default (key 0): one explicit
// drop-cap letter must not out-vote a body of default-sized text
const key = v > 0 ? v : 0
szWeights.set(key, (szWeights.get(key) ?? 0) + Math.max(text.length, 1))
if (!font) {
const fonts = /<w:rFonts [^/>]*/.exec(run[1])?.[0] ?? ''
font = /w:eastAsia="([^"]+)"/.exec(fonts)?.[1] ?? /w:ascii="([^"]+)"/.exec(fonts)?.[1]
}
}
let sz = 0
let szWeight = -1
for (const [v, w] of szWeights) {
if (w > szWeight || (w === szWeight && v > sz)) {
sz = v
szWeight = w
}
}
// sized spans only for mixed sizes, and only when the runs reproduce the
// visible text (tabs/breaks fall back to the plain string)
const norm = (t: string) => t.replace(/\s+/g, ' ').trim()
const mixedRuns =
szWeights.size > 1 && norm(sizedRuns.map((r) => r.text).join('')) === norm(visible)
? sizedRuns.filter((r) => r.text !== '')
: undefined
// explicit paragraph alignment: the passthrough div would inherit the
// document default (justify in CJK docs) and stretch short lines
const pPr = /<w:pPr>[\s\S]*?<\/w:pPr>/.exec(xml)?.[0] ?? ''
const jc = /<w:jc w:val="([^"]+)"/.exec(pPr)?.[1]
const align =
jc === 'left' || jc === 'start'
? 'left'
: jc === 'right' || jc === 'end'
? 'right'
: jc === 'center'
? 'center'
: undefined
// explicit line spacing (same extraction as tocLine): the renderer must
// not collapse a 1.5x field paragraph to single-spacing
const spacingAttrs = /<w:spacing ([^/>]*)\/>/.exec(pPr)?.[1] ?? ''
const line = lineTwipsOf(/w:line="([^"]+)"/.exec(spacingAttrs)?.[1])
const lineRule = (/w:lineRule="(auto|atLeast|exact)"/.exec(spacingAttrs)?.[1] ?? 'auto') as
'auto' | 'atLeast' | 'exact'
return {
kind: 'text',
left: visible,
...(sz > 0 ? { szHalfPoints: sz } : {}),
...(mixedRuns ? { runs: mixedRuns } : {}),
...(font ? { fontFamily: font } : {}),
...(align ? { align } : {}),
...(line > 0 && lineRule
? {
lineRule,
lineRawTwips: line,
...(lineRule === 'auto' ? { lineSpacing: Math.round((line / 240) * 100) / 100 } : {}),
}
: {}),
}
}
return undefined
}
/**
* TOC entries carry their outline number ("1.", "1.1.") as w:numPr numbering
* (Pages exports one numId per entry with startOverride restarts). The field
* result is a display-only cache, so the marker is computed once at parse time
* and stored on the tocLine FieldDisplay. Counters run document-wide in block
* order, shared with editable list items (same abstractNum semantics).
*/
export function applyTocEntryNumbers(blocks: Block[], numbering: Map<string, NumberingDef>): void {
if (numbering.size === 0) return
const items: ListItemRef[] = []
const tocAt = new Map<number, FieldDisplay>()
for (const block of blocks) {
if (block.list?.numId) {
items.push({ numId: block.list.numId, ilvl: block.list.ilvl })
continue
}
const fd = block.fieldDisplay
if (block.type !== 'passthrough' || fd?.kind !== 'tocLine' || !block.originalXml) continue
const numPr = /<w:numPr>[\s\S]*?<\/w:numPr>/.exec(block.originalXml)?.[0]
if (!numPr) continue
const numId = /<w:numId w:val="([^"]+)"/.exec(numPr)?.[1]
if (!numId) continue
const ilvl = parseInt(/<w:ilvl w:val="(\d+)"/.exec(numPr)?.[1] ?? '0', 10)
tocAt.set(items.length, fd)
items.push({ numId, ilvl })
}
if (tocAt.size === 0) return
const markers = computeListMarkers(items, numbering)
for (const [i, fd] of tocAt) {
const marker = markers[i]
// bullets make no sense in front of a TOC entry; only ordered markers show
if (marker && !/^[•◦▪➢❖✓]$/.test(marker)) fd.num = marker
}
}
const FIELD_LABELS: Record<string, string> = {
TOC: 'Auto TOC (updates when opened in Word)',
PAGE: 'Page number field',
NUMPAGES: 'Page count field',
PAGEREF: 'Page reference field',
REF: 'Cross-reference field',
SEQ: 'Caption number field',
HYPERLINK: 'Hyperlink field',
DATE: 'Date field',
TIME: 'Time field',
INCLUDEPICTURE: 'Linked picture field',
STYLEREF: 'Style reference field',
}
/** Human-readable label for a protected field paragraph, based on its field code. */
export function fieldLabel(xml: string): string {
const instr =
/<w:instrText[^>]*>([\s\S]*?)<\/w:instrText>/.exec(xml)?.[1] ??
/<w:fldSimple[^>]*w:instr="([^"]*)"/.exec(xml)?.[1] ??
''
const keyword = instr.trim().split(/\s+/)[0]?.toUpperCase() ?? ''
if (keyword && FIELD_LABELS[keyword]) return FIELD_LABELS[keyword]
if (keyword) return `Field (${keyword})`
// No field code in this paragraph: it only closes a field started earlier
// (e.g. the paragraph holding the TOC's fldChar end + page break).
if (xml.includes('fldCharType="end"') && !xml.includes('fldCharType="begin"')) {
return xml.includes('w:type="page"') ? 'Field end marker + page break' : 'Field end marker'
}
return 'Field (TOC/page number/etc.)'
}
+298
View File
@@ -0,0 +1,298 @@
// Package-level parts: main document path, relationships, comments,
// protection settings and numbering definitions.
import JSZip from 'jszip'
import {
attrsOf,
childrenOf,
findChild,
findChildren,
nameOf,
textOf,
xmlParser,
type XNode,
} from './xml-utils'
import { customEnumItems } from './list-markers'
import { decodeNumericCharRefs, type RelInfo } from './parse-xml-text'
import type {
CommentInfo,
DocProtection,
NumberingDef,
NumberingLevel,
WriteProtection,
} from './types'
/**
* Main document part: word/document.xml when present, else the package-level
* officeDocument relationship target (LO corpus has e.g. word/trial.xml).
*/
export async function resolveMainDocumentPath(zip: JSZip): Promise<string | null> {
if (zip.file('word/document.xml')) return 'word/document.xml'
const rels = await parseRels(zip, '_rels/.rels')
for (const rel of rels.values()) {
if (!/\/officeDocument$/.test(rel.type) || rel.targetMode === 'External') continue
const target = rel.target.replace(/^\//, '')
if (zip.file(target)) return target
}
return null
}
export async function parseRels(zip: JSZip, path: string): Promise<Map<string, RelInfo>> {
const rels = new Map<string, RelInfo>()
const file = zip.file(path)
if (!file) return rels
// fast-xml-parser rejects a DOCTYPE declaring external entities; drop the
// prologue instead of failing the whole document (entities never resolve —
// XXE-safe — and Relationship elements carry everything in attributes)
const relsXml = (await file.async('string')).replace(/<!DOCTYPE(?:[^>[]|\[[\s\S]*?\])*>/i, '')
const parsed = xmlParser.parse(relsXml) as XNode[]
const root = parsed.find((n) => nameOf(n) === 'Relationships')
if (!root) return rels
for (const relNode of findChildren(root, 'Relationship')) {
const attrs = attrsOf(relNode)
if (!attrs['Id']) continue
rels.set(attrs['Id'], {
target: attrs['Target'] ?? '',
type: attrs['Type'] ?? '',
targetMode: attrs['TargetMode'],
})
}
return rels
}
/** word/comments.xml (+ reply/resolved relations from commentsExtended) -> display list, file order */
export async function parseComments(zip: JSZip): Promise<CommentInfo[]> {
const file = zip.file('word/comments.xml')
if (!file) return []
const parsed = xmlParser.parse(await file.async('string')) as XNode[]
const root = parsed.find((n) => nameOf(n) === 'w:comments')
if (!root) return []
const out: CommentInfo[] = []
for (const node of findChildren(root, 'w:comment')) {
const attrs = attrsOf(node)
if (!attrs['w:id']) continue
const paras = findChildren(node, 'w:p')
const paraId = paras.length > 0 ? attrsOf(paras[paras.length - 1])['w14:paraId'] : undefined
out.push({
id: attrs['w:id'],
author: attrs['w:author'] ?? '',
initials: attrs['w:initials'],
date: attrs['w:date'],
text: paras.map((p) => textOf(p)).join('\n'),
...(paraId ? { paraId } : {}),
})
}
// commentsExtended.xml: paraId → parent paraId / done (Word 2013+ replies and resolution)
const extFile = zip.file('word/commentsExtended.xml')
if (extFile) {
const extXml = await extFile.async('string')
const byParaId = new Map(out.filter((c) => c.paraId).map((c) => [c.paraId!, c]))
for (const m of extXml.match(/<w15:commentEx [^>]*\/>/g) ?? []) {
const paraId = /w15:paraId="([^"]+)"/.exec(m)?.[1]
const parentParaId = /w15:paraIdParent="([^"]+)"/.exec(m)?.[1]
const done = /w15:done="(?:1|true)"/.test(m)
const c = paraId ? byParaId.get(paraId) : undefined
if (!c) continue
if (done) c.done = true
if (parentParaId) {
const parent = byParaId.get(parentParaId)
if (parent) c.parentId = parent.id
}
}
}
return out
}
/** w:documentProtection from word/settings.xml (editing restriction) */
export async function parseProtection(zip: JSZip): Promise<DocProtection | null> {
const file = zip.file('word/settings.xml')
if (!file) return null
const xml = await file.async('string')
const tag = /<w:documentProtection[^>]*\/>/.exec(xml)?.[0]
if (!tag) return null
const edit = /w:edit="([^"]+)"/.exec(tag)?.[1]
if (!edit || edit === 'none') return null
const enforcement = /w:enforcement="([^"]+)"/.exec(tag)?.[1]
const hash = /w:hash="([^"]+)"/.exec(tag)?.[1]
const salt = /w:salt="([^"]+)"/.exec(tag)?.[1]
const spin = /w:cryptSpinCount="(\d+)"/.exec(tag)?.[1]
const sid = /w:cryptAlgorithmSid="(\d+)"/.exec(tag)?.[1]
return {
edit,
enforced: enforcement === '1' || enforcement === 'true',
...(hash ? { hash } : {}),
...(salt ? { salt } : {}),
...(spin ? { spinCount: parseInt(spin, 10) } : {}),
...(sid ? { algorithmSid: parseInt(sid, 10) } : {}),
}
}
/** w:writeProtection from word/settings.xml (password to modify / read-only recommended) */
export async function parseWriteProtection(zip: JSZip): Promise<WriteProtection | null> {
const file = zip.file('word/settings.xml')
if (!file) return null
const tag = /<w:writeProtection[^>]*\/>/.exec(await file.async('string'))?.[0]
if (!tag) return null
const recommended = /w:recommended="(?:1|true|on)"/.test(tag)
const hash = /w:hash="([^"]+)"/.exec(tag)?.[1]
const salt = /w:salt="([^"]+)"/.exec(tag)?.[1]
const spin = /w:cryptSpinCount="(\d+)"/.exec(tag)?.[1]
const sid = /w:cryptAlgorithmSid="(\d+)"/.exec(tag)?.[1]
if (!recommended && !hash) return null
return {
...(recommended ? { recommended } : {}),
...(hash ? { hash } : {}),
...(salt ? { salt } : {}),
...(spin ? { spinCount: parseInt(spin, 10) } : {}),
...(sid ? { algorithmSid: parseInt(sid, 10) } : {}),
}
}
/** settings.xml removePersonalInformation (namespace prefix and quote style are arbitrary). */
export async function parseRemovePersonalInfo(zip: JSZip): Promise<boolean> {
const file = zip.file('word/settings.xml')
if (!file) return false
const xml = await file.async('string')
const prefixes = new Set<string>()
const namespace = /\bxmlns(?::([A-Za-z_][\w.-]*))?\s*=\s*(["'])([^"']*)\2/g
let declaration: RegExpExecArray | null
while ((declaration = namespace.exec(xml)) !== null) {
if (
declaration[3] === 'http://schemas.openxmlformats.org/wordprocessingml/2006/main' ||
declaration[3] === 'http://purl.oclc.org/ooxml/wordprocessingml/main'
) {
prefixes.add(declaration[1] ?? '')
}
}
const escapedPrefixes = [...prefixes]
.filter(Boolean)
.map((prefix) => prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
for (const prefix of prefixes) {
const qName = prefix ? `${prefix}:removePersonalInformation` : 'removePersonalInformation'
const escapedName = qName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const tag = new RegExp(`<${escapedName}\\b[^>]*(?:\\/\\s*>|>\\s*<\\/${escapedName}\\s*>)`).exec(
xml,
)?.[0]
if (!tag) continue
const valPrefix = escapedPrefixes.length > 0 ? `(?:${escapedPrefixes.join('|')}):` : ''
const val = new RegExp(`(?:^|\\s)(?:${valPrefix})?val\\s*=\\s*(["'])(0|false)\\1`, 'i')
return !val.test(tag)
}
return false
}
/** w:numFmt of a w:lvl, including w14 custom formats hidden in mc:AlternateContent
* (mc:Choice carries val="custom" + w:format; mc:Fallback the standard substitute) */
function numFmtOfLevel(lvlNode: XNode): { numFmt?: string; customFormat?: string } {
const direct = findChild(lvlNode, 'w:numFmt')
if (direct) return { numFmt: attrsOf(direct)['w:val'] }
const alt = childrenOf(lvlNode).find((c) => nameOf(c)?.endsWith(':AlternateContent'))
if (!alt) return {}
const pick = (local: string) => childrenOf(alt).find((c) => nameOf(c)?.endsWith(`:${local}`))
const choice = attrsOf(findChild(pick('Choice') ?? {}, 'w:numFmt') ?? {})
const format = choice['w:format']
if (choice['w:val'] === 'custom' && format && customEnumItems(format))
return { numFmt: 'custom', customFormat: format }
if (choice['w:val'] && choice['w:val'] !== 'custom') return { numFmt: choice['w:val'] }
return { numFmt: attrsOf(findChild(pick('Fallback') ?? {}, 'w:numFmt') ?? {})['w:val'] }
}
function parseNumberingLevel(lvlNode: XNode): NumberingLevel {
// ECMA-376: a w:lvl without w:start starts at 0 (Word renders "0.")
const start = parseInt(attrsOf(findChild(lvlNode, 'w:start') ?? {})['w:val'] ?? '0', 10)
const { numFmt, customFormat } = numFmtOfLevel(lvlNode)
const level: NumberingLevel = {
numFmt: numFmt ?? 'decimal',
lvlText: decodeNumericCharRefs(attrsOf(findChild(lvlNode, 'w:lvlText') ?? {})['w:val'] ?? ''),
start: Number.isFinite(start) ? start : 0,
}
if (customFormat) level.customFormat = customFormat
const suff = attrsOf(findChild(lvlNode, 'w:suff') ?? {})['w:val']
if (suff === 'space' || suff === 'nothing' || suff === 'tab') level.suff = suff
const lvlPPr = findChild(lvlNode, 'w:pPr')
const ind = lvlPPr ? findChild(lvlPPr, 'w:ind') : undefined
if (ind) {
const attrs = attrsOf(ind)
const left = parseInt(attrs['w:left'] ?? attrs['w:start'] ?? '', 10)
if (left > 0) level.indentLeft = left
const hanging = parseInt(attrs['w:hanging'] ?? '', 10)
if (hanging > 0) level.hanging = hanging
const firstLine = parseInt(attrs['w:firstLine'] ?? '', 10)
if (!level.hanging && firstLine > 0) level.firstLine = firstLine
}
const lvlRPr = findChild(lvlNode, 'w:rPr')
const sz = lvlRPr ? parseInt(attrsOf(findChild(lvlRPr, 'w:sz') ?? {})['w:val'] ?? '', 10) : NaN
if (sz > 0) level.szHalfPoints = sz
const fonts = lvlRPr ? attrsOf(findChild(lvlRPr, 'w:rFonts') ?? {}) : {}
const font = fonts['w:ascii'] ?? fonts['w:hAnsi'] ?? fonts['w:eastAsia']
if (font) level.font = font
return level
}
/** word/numbering.xml -> per-numId level definitions + the bullet/ordered classification */
export async function parseNumbering(
zip: JSZip,
): Promise<{ formats: Map<string, 'bullet' | 'ordered'>; defs: Map<string, NumberingDef> }> {
const formats = new Map<string, 'bullet' | 'ordered'>()
const defs = new Map<string, NumberingDef>()
const file = zip.file('word/numbering.xml')
if (!file) return { formats, defs }
const parsed = xmlParser.parse(await file.async('string')) as XNode[]
const root = parsed.find((n) => nameOf(n) === 'w:numbering')
if (!root) return { formats, defs }
const absLevels = new Map<string, Record<number, NumberingLevel>>()
const numStyleLinks = new Map<string, string>()
const styleLinkAbs = new Map<string, string>()
for (const abs of findChildren(root, 'w:abstractNum')) {
const absId = attrsOf(abs)['w:abstractNumId']
if (!absId) continue
const levels: Record<number, NumberingLevel> = {}
for (const lvl of findChildren(abs, 'w:lvl')) {
const ilvl = parseInt(attrsOf(lvl)['w:ilvl'] ?? '', 10)
if (Number.isFinite(ilvl)) levels[ilvl] = parseNumberingLevel(lvl)
}
absLevels.set(absId, levels)
const numStyleLink = attrsOf(findChild(abs, 'w:numStyleLink') ?? {})['w:val']
if (numStyleLink) numStyleLinks.set(absId, numStyleLink)
const styleLink = attrsOf(findChild(abs, 'w:styleLink') ?? {})['w:val']
if (styleLink) styleLinkAbs.set(styleLink, absId)
}
// w:numStyleLink indirection: the abstractNum is a reference to a numbering style;
// the real levels live on the abstractNum carrying the matching w:styleLink
for (const absId of numStyleLinks.keys()) {
const seen = new Set([absId])
let target = absId
for (;;) {
const styleId = numStyleLinks.get(target)
const next = styleId !== undefined ? styleLinkAbs.get(styleId) : undefined
if (next === undefined || seen.has(next)) break
seen.add(next)
target = next
}
if (target !== absId) {
absLevels.set(absId, { ...absLevels.get(target), ...absLevels.get(absId) })
}
}
for (const num of findChildren(root, 'w:num')) {
const numId = attrsOf(num)['w:numId']
const absId = attrsOf(findChild(num, 'w:abstractNumId') ?? {})['w:val']
if (!numId || !absId) continue
const levels: Record<number, NumberingLevel> = { ...(absLevels.get(absId) ?? {}) }
const startOverrides: Record<number, number> = {}
for (const over of findChildren(num, 'w:lvlOverride')) {
const ilvl = parseInt(attrsOf(over)['w:ilvl'] ?? '', 10)
if (!Number.isFinite(ilvl)) continue
const startVal = attrsOf(findChild(over, 'w:startOverride') ?? {})['w:val']
if (startVal !== undefined) {
const n = parseInt(startVal, 10)
if (Number.isFinite(n)) startOverrides[ilvl] = n
}
const lvl = findChild(over, 'w:lvl')
if (lvl) levels[ilvl] = parseNumberingLevel(lvl)
}
defs.set(numId, { numId, abstractNumId: absId, levels, startOverrides })
formats.set(numId, levels[0]?.numFmt === 'bullet' ? 'bullet' : 'ordered')
}
return { formats, defs }
}
+908
View File
@@ -0,0 +1,908 @@
// Pure XML -> value readers for paragraph, run and table-cell properties
// (no document context, no recursion into block builders).
import {
attrsOf,
childrenOf,
findChild,
findChildren,
nameOf,
textOf,
xmlParser,
type XNode,
} from './xml-utils'
import {
EMU_PER_PX,
decodeEntities,
decodeNumericCharRefs,
onOffOf,
plainText,
stripHash,
} from './parse-xml-text'
import type {
Block,
CellBorders,
CellMargins,
CharIndents,
ParaFormat,
RevisionInfo,
Run,
TableBorders,
TableModel,
ThemeFonts,
} from './types'
/** No run un-hides itself and nothing anchors here (bookmarks, comments, sectPr,
* drawings, numbering): safe to collapse a style-vanished paragraph entirely */
export function staysVanished(xml: string): boolean {
if (/<w:vanish\s[^>]*w:val="(?:0|false|off)"/.test(xml)) return false
return !/<w:(?:drawing|pict|object|sectPr|bookmarkStart|commentRangeStart|commentRangeEnd|numPr)[\s/>]/.test(
xml,
)
}
/** Text-less run content that still affects layout (breaks, tabs, note marks,
* symbol chars): a "visually empty" paragraph carrying one must not collapse.
* w:pPr is skipped so tab-stop definitions (w:tabs > w:tab) don't count. */
const LAYOUT_RUN_CONTENT = /^w:(?:br|cr|tab|sym|footnoteReference|endnoteReference)$/
export function hasLayoutRunContent(node: XNode): boolean {
for (const child of childrenOf(node)) {
const name = nameOf(child)
if (name === 'w:pPr' || name === 'w:rPr') continue
if (name !== undefined && LAYOUT_RUN_CONTENT.test(name)) return true
if (hasLayoutRunContent(child)) return true
}
return false
}
/**
* Cross-paragraph comment range endpoints: comment ids where only one end falls in this
* paragraph (the other end is in a different paragraph). Ranges fully within one
* paragraph are handled by run.commentIds; this only catches cross-paragraph ones so a
* paragraph rebuild does not leave orphaned commentRangeEnd/Start markers.
*/
export function crossParaCommentMarkers(xml: string): {
commentStarts: string[] | undefined
commentEnds: string[] | undefined
} {
const ids = (re: RegExp) => [...xml.matchAll(re)].map((m) => m[1])
const starts = ids(/<w:commentRangeStart [^>]*w:id="([^"]+)"/g)
const ends = ids(/<w:commentRangeEnd [^>]*w:id="([^"]+)"/g)
const onlyStarts = starts.filter((id) => !ends.includes(id))
const onlyEnds = ends.filter((id) => !starts.includes(id))
return {
commentStarts: onlyStarts.length ? onlyStarts : undefined,
commentEnds: onlyEnds.length ? onlyEnds : undefined,
}
}
/** user bookmark names starting in this paragraph; Word internals (_Toc/_Ref/_GoBack…) split out as hiddenBookmarks */
export function bookmarkNamesOf(xml: string): {
bookmarks: string[] | undefined
hiddenBookmarks: string[] | undefined
} {
const names: string[] = []
const hidden: string[] = []
for (const m of xml.matchAll(/<w:bookmarkStart [^>]*w:name="([^"]+)"/g)) {
const name = decodeEntities(m[1])
// A _ prefix marks Word internal bookmarks (_Ref/_Toc/_Hlk): hidden from the UI, but
// they must be re-emitted when the paragraph rebuilds, otherwise REF cross-references
// and TOC anchors pointing at them break
const list = name.startsWith('_') ? hidden : names
if (!list.includes(name)) list.push(name)
}
return {
bookmarks: names.length > 0 ? names : undefined,
hiddenBookmarks: hidden.length > 0 ? hidden : undefined,
}
}
/**
* Exact <w:pPr>...</w:pPr> slice of a paragraph (depth-aware: pPrChange nests
* another w:pPr inside). undefined when the paragraph has no properties.
*/
export function rawPPrOf(xml: string): string | undefined {
// the paragraph's own pPr must be the first child of w:p; a later match
// would belong to nested content (textbox paragraphs)
const openEnd = xml.indexOf('>') + 1
if (openEnd === 0 || !xml.startsWith('<w:pPr', openEnd)) return undefined
const start = openEnd
const re = /<w:pPr(?=[\s/>])|<\/w:pPr>/g
re.lastIndex = start
let depth = 0
let match: RegExpExecArray | null
while ((match = re.exec(xml)) !== null) {
if (match[0] === '</w:pPr>') {
depth--
if (depth === 0) return xml.slice(start, match.index + match[0].length)
} else {
// self-closing <w:pPr/> never opens
const gt = xml.indexOf('>', match.index)
if (xml[gt - 1] === '/') {
if (depth === 0) return xml.slice(start, gt + 1)
continue
}
depth++
}
}
return undefined
}
/**
* A text-less anchored shape no taller than ~10px is almost always a
* decorative horizontal rule (heading underlines, dividers); render those as a
* line instead of a drawing-object chip.
*/
export function isThinRule(xml: string): boolean {
const m = /<wp:extent cx="(\d+)" cy="(\d+)"/.exec(xml)
if (!m) return false
const cx = parseInt(m[1], 10)
const cy = parseInt(m[2], 10)
// Word writes plain horizontal lines with cy="0"
return cy <= 130000 && (cy > 0 || cx > 0)
}
/** stroke color/thickness (a:ln) + extent width of a decorative rule drawing */
export function ruleDisplayOf(
xml: string,
): Pick<Block, 'ruleColorHex' | 'ruleThicknessPx' | 'ruleWidthPx'> {
const out: Pick<Block, 'ruleColorHex' | 'ruleThicknessPx' | 'ruleWidthPx'> = {}
const ln = /<a:ln\b[^>]*>[\s\S]*?<\/a:ln>/.exec(xml)?.[0]
if (ln) {
const color = /<a:solidFill>\s*<a:srgbClr val="([0-9A-Fa-f]{6})"/.exec(ln)?.[1]
if (color) out.ruleColorHex = color.toUpperCase()
const w = parseInt(/<a:ln\b[^>]*\bw="(\d+)"/.exec(ln)?.[1] ?? '', 10)
if (Number.isFinite(w) && w > 0) out.ruleThicknessPx = Math.max(1, Math.round(w / EMU_PER_PX))
}
const cx = parseInt(/<wp:extent cx="(\d+)"/.exec(xml)?.[1] ?? '', 10)
if (Number.isFinite(cx) && cx > 0) out.ruleWidthPx = Math.round(cx / EMU_PER_PX)
return out
}
/**
* Converter artifact: every shape explicitly declares noFill + noFill outline
* and carries no picture, no text and no effects — Word renders nothing, so
* the block renders as nothing too (still passthrough, bytes untouched).
*/
export function isInvisibleEmptyShape(xml: string): boolean {
if (!xml.includes('<wps:wsp') || xml.includes('<a:blip') || plainText(xml).trim() !== '') {
return false
}
let parsed: XNode[]
try {
parsed = xmlParser.parse(xml) as XNode[]
} catch {
return false
}
const shapes: XNode[] = []
collectNodes(parsed, 'wps:wsp', shapes)
if (shapes.length === 0) return false
return shapes.every((shape) => {
const spPr = findChild(shape, 'wps:spPr')
if (!spPr || !findChild(spPr, 'a:noFill')) return false
const ln = findChild(spPr, 'a:ln')
if (!ln || !findChild(ln, 'a:noFill')) return false
const effects = findChild(spPr, 'a:effectLst')
return !effects || childrenOf(effects).length === 0
})
}
/**
* Legacy VML pict that draws nothing: only v:shapetype definitions (geometry
* templates, not drawn), shapes hidden via style visibility:hidden, or white
* strokeless placeholder rectangles (LO fixtures / converter watermark
* furniture). Word renders nothing there — an "Embedded object" chip would
* paint a box on an otherwise blank page.
*/
export function isInvisibleVmlPict(xml: string): boolean {
if (!/<v:(?:shapetype|shape|rect|roundrect|oval|line|polyline)\b/.test(xml)) return false
if (xml.includes('<v:imagedata') || xml.includes('<w:txbxContent')) return false
const shapes = xml.match(/<v:(?:shape|rect|roundrect|oval|line|polyline)\b[^>]*>/g) ?? []
// no drawable instances at all (shapetype-only pict) also renders nothing
return shapes.every((tag) => {
const style = /style="([^"]*)"/.exec(tag)?.[1] ?? ''
if (/visibility:\s*hidden/.test(style)) return true
const fill = /fillcolor="([^"]+)"/.exec(tag)?.[1]?.trim().toLowerCase()
const unstroked = /\bstroked="(?:f|false|0)"/.test(tag)
return unstroked && (fill === 'white' || fill === '#ffffff' || fill === '#fff')
})
}
/** drop textbox content so "does the paragraph itself have text" checks work */
export function stripTextboxes(xml: string): string {
return xml.includes('<w:txbxContent')
? xml.replace(/<w:txbxContent>[\s\S]*?<\/w:txbxContent>/g, '')
: xml
}
/** page-type w:br carried by the anchor paragraph itself (not inside box content) */
export function hostPageBreak(xml: string): boolean {
return /<w:br\s[^>]*w:type="page"/.test(stripTextboxes(xml))
}
/**
* w:tbl or w:sdt among the txbxContent children: the display lines no longer
* map 1:1 onto the w:p segments patch-save rewrites, so the box must stay
* read-only (editing would drop the table / sdt shells).
*/
export function txbxHasStructuredContent(content: XNode): boolean {
return childrenOf(content).some((c) => {
const n = nameOf(c)
return n === 'w:tbl' || n === 'w:sdt'
})
}
export function collectNodes(nodes: XNode[], name: string, out: XNode[]): void {
for (const node of nodes) {
if (nameOf(node) === name) out.push(node)
collectNodes(childrenOf(node), name, out)
}
}
/** like collectNodes, but does not descend into a matched node — top-level
* matches only, the set xmlSegments counts on the save path */
export function collectTopNodes(nodes: XNode[], name: string, out: XNode[]): void {
for (const node of nodes) {
if (nameOf(node) === name) {
out.push(node)
continue
}
collectTopNodes(childrenOf(node), name, out)
}
}
export const JC_ALIGN: Record<string, ParaFormat['align']> = {
left: 'left',
start: 'left',
center: 'center',
right: 'right',
end: 'right',
both: 'justify',
distribute: 'distribute',
}
/** w:autoSpaceDE/DN (Word default on): false only when both are explicitly off */
export function autoSpaceOf(pPr: XNode): boolean | undefined {
const de = onOffOf(pPr, 'w:autoSpaceDE')
const dn = onOffOf(pPr, 'w:autoSpaceDN')
if (de === false && dn === false) return false
if (de === true || dn === true) return true
return undefined
}
/** pPr <w:tabs> → TabStop[] (shared by direct paragraph format and style display) */
export function tabStopsOf(pPr: XNode): import('./types').TabStop[] | undefined {
const tabsEl = findChild(pPr, 'w:tabs')
if (!tabsEl) return undefined
const stops: import('./types').TabStop[] = []
for (const tab of findChildren(tabsEl, 'w:tab')) {
const attrs = attrsOf(tab)
const pos = parseInt(attrs['w:pos'] ?? '', 10)
const val = attrs['w:val'] ?? 'left'
if (!Number.isFinite(pos)) continue
const validVals = ['left', 'center', 'right', 'decimal', 'bar', 'clear'] as const
const safeVal = validVals.includes(val as (typeof validVals)[number])
? (val as (typeof validVals)[number])
: 'left'
const stop: import('./types').TabStop = { pos, val: safeVal }
const leader = attrs['w:leader']
if (leader && leader !== 'none') {
const validLeaders = ['dot', 'hyphen', 'underscore', 'heavy', 'middleDot'] as const
if (validLeaders.includes(leader as (typeof validLeaders)[number])) {
stop.leader = leader as (typeof validLeaders)[number]
}
}
stops.push(stop)
}
return stops.length > 0 ? stops : undefined
}
/** display-only stops for the paragraph's w:ptab elements (left-aligned ones advance nothing) */
export function ptabDisplayStops(pNode: XNode): import('./types').TabStop[] {
const out: import('./types').TabStop[] = []
const walk = (n: XNode): void => {
for (const c of childrenOf(n)) {
const name = nameOf(c)
if (name === 'w:pPr') continue
if (name === 'w:ptab') {
const a = attrsOf(c)
const align = a['w:alignment']
if (align !== 'center' && align !== 'right') continue
const stop: import('./types').TabStop = {
pos: align === 'center' ? 50 : 100,
val: align,
rel: 'margin',
}
const leader = a['w:leader']
if (
leader === 'dot' ||
leader === 'hyphen' ||
leader === 'underscore' ||
leader === 'middleDot'
) {
stop.leader = leader
}
out.push(stop)
} else walk(c)
}
}
walk(pNode)
return out
}
/**
* True when every field in the paragraph is an XE (index entry) marker.
* Multi-fragment instructions or fldSimple fields fail the check, so anything
* unusual falls back to the protected-passthrough path.
*/
/** paragraphs whose only fields are XE / REF stay editable (extractRuns round-trips them) */
/** Simple instructions foldable into an editable inline-field run (the cached result is the display text) */
export const SIMPLE_INLINE_FIELD_RE =
/^\s*(DATE|TIME|CREATEDATE|SAVEDATE|NUMPAGES|FILENAME|AUTHOR|PAGE)\b/
/** HYPERLINK "url" (optional \o "tip"): the only field form folded into an editable link run;
* any other switch (\l bookmark, \t frame...) keeps the protected-passthrough path */
export function convertibleHyperlink(instr: string): { href: string; tooltip?: string } | null {
const m = /^\s*HYPERLINK\s+"([^"\\]+)"\s*(?:\\o\s+"([^"]*)"\s*)?$/.exec(
decodeNumericCharRefs(instr),
)
if (!m) return null
return { href: m[1], ...(m[2] ? { tooltip: m[2] } : {}) }
}
/** every field instruction is EMBED/LINK (the object-field forms of legacy OLE) */
export function onlyOleFields(xml: string): boolean {
if (xml.includes('<w:fldSimple')) return false
const instrs = xml.match(/<w:instrText[^>]*>[\s\S]*?<\/w:instrText>/g) ?? []
if (instrs.length === 0) return false
return instrs.every((fragment) =>
/^\s*(EMBED|LINK)\b/.test(decodeEntities(fragment.replace(/<[^>]+>/g, ''))),
)
}
export function onlyXeFields(xml: string): boolean {
if (xml.includes('<w:fldSimple')) return false
const instrs = xml.match(/<w:instrText[^>]*>[\s\S]*?<\/w:instrText>/g) ?? []
if (instrs.length === 0) return false
let checkboxInstrs = 0
const ok = instrs.every((fragment) => {
const text = decodeEntities(fragment.replace(/<[^>]+>/g, ''))
if (/^\s*FORMCHECKBOX\s*$/.test(text)) {
checkboxInstrs++
return true
}
return (
/^\s*XE[\s"]/.test(text) ||
/^\s*REF\s/.test(text) ||
SIMPLE_INLINE_FIELD_RE.test(text) ||
convertibleHyperlink(text) !== null
)
})
if (!ok) return false
// a FORMCHECKBOX without its w:checkBox definition can't fold into a glyph
// run; keep the paragraph on the byte-preserving passthrough path instead
// of silently dropping the field on save
const checkBoxDefs = (xml.match(/<w:checkBox[\s/>]/g) ?? []).length
return checkboxInstrs <= checkBoxDefs
}
/** Checked state of a FORMCHECKBOX begin run (w:fldChar/w:ffData/w:checkBox):
* w:checked wins over w:default; either element without w:val means true */
export function checkboxStateOf(beginRun: XNode | null): { checked: boolean } | null {
if (!beginRun) return null
const ffData = findChild(findChild(beginRun, 'w:fldChar') ?? {}, 'w:ffData')
const box = ffData ? findChild(ffData, 'w:checkBox') : undefined
if (!box) return null
const state = findChild(box, 'w:checked') ?? findChild(box, 'w:default')
if (!state) return { checked: false }
const val = attrsOf(state)['w:val']
return { checked: val === undefined || val === '1' || val === 'true' || val === 'on' }
}
/**
* Character-unit attributes a w:ind specifies. Zeros are kept: Word writes
* `w:firstLineChars="0"` next to an absolute `w:firstLine` to say the indent is
* NOT character-based, and such a zero also cancels a *Chars inherited from
* the style chain (probed) — see mergeCharIndents / activeCharIndents.
*/
export function charIndentsOf(ind: XNode | undefined): CharIndents | undefined {
if (!ind) return undefined
const a = attrsOf(ind)
const num = (v: string | undefined): number | undefined => {
const n = parseInt(v ?? '', 10)
return Number.isFinite(n) ? n : undefined
}
const chars: CharIndents = {}
const left = num(a['w:leftChars'] ?? a['w:startChars'])
if (left !== undefined) chars.left = left
const right = num(a['w:rightChars'] ?? a['w:endChars'])
if (right !== undefined) chars.right = right
const firstLine = num(a['w:firstLineChars'])
if (firstLine !== undefined && firstLine >= 0) chars.firstLine = firstLine
const hanging = num(a['w:hangingChars'])
if (hanging !== undefined && hanging >= 0) chars.hanging = hanging
return Object.keys(chars).length > 0 ? chars : undefined
}
/**
* Layer one w:ind's character-unit attributes over inherited ones the way Word
* resolves a style chain and direct formatting (Word for Mac probe, 2026-09-02):
* a *Chars attribute — zero included — replaces the inherited value of its
* component, a twips attribute never does (a child style's or paragraph's
* twips-only w:firstLine / w:left leaves an inherited firstLineChars /
* leftChars in force). firstLineChars and hangingChars are one component, the
* special indent: setting either replaces both.
*/
export function mergeCharIndents(
base: CharIndents | undefined,
over: CharIndents | undefined,
): CharIndents | undefined {
if (!base) return over
if (!over) return base
const merged: CharIndents = { ...base }
if (over.left !== undefined) merged.left = over.left
if (over.right !== undefined) merged.right = over.right
if (over.firstLine !== undefined || over.hanging !== undefined) {
delete merged.firstLine
delete merged.hanging
if (over.firstLine !== undefined) merged.firstLine = over.firstLine
if (over.hanging !== undefined) merged.hanging = over.hanging
}
return merged
}
/** the character indents that lay out: an explicit zero means "absolute" and drops out */
export function activeCharIndents(chars: CharIndents | undefined): CharIndents | undefined {
if (!chars) return undefined
const active: CharIndents = {}
if (chars.left) active.left = chars.left
if (chars.right) active.right = chars.right
if (chars.firstLine) active.firstLine = chars.firstLine
if (chars.hanging) active.hanging = chars.hanging
return Object.keys(active).length > 0 ? active : undefined
}
/** twips of one "character" for each family of character-unit indents */
export interface CharUnits {
/** w:firstLineChars / w:hangingChars: the paragraph's first text run — its font
* size plus its letter spacing (plus the section's character-grid pitch delta) */
run: number
/** w:leftChars / w:rightChars: the default paragraph style's (Normal) font size —
* whatever the paragraph's own style or runs say (plus the grid delta) */
normal: number
}
/**
* Fold character-unit indents into the twips fields of a paragraph format,
* the way Word lays them out (Word for Mac probe, 2026-09-02):
*
* - a nonzero *Chars attribute supersedes its twips twin (firstLineChars over
* firstLine, leftChars over left, rightChars over right), and a character
* special indent beats a twips one of the other kind (firstLineChars over
* w:hanging); between two character specials hanging wins, as with twips;
* - firstLineChars/hangingChars scale with the first text run's size (a 10pt
* first run in a 20pt paragraph gives a 10pt unit; the paragraph mark's size
* never counts), leftChars/rightChars with the Normal style's size;
* - once leftChars or hangingChars is present the left edge is in "character
* mode": leftChars is the position of the first line (Word's dialog "Left"),
* the body lines sit `hanging` further in — hangingChars, else the twips
* w:hanging — and a twips w:left is ignored even when leftChars is absent.
* firstLineChars alone keeps a twips w:left as the body indent.
*/
export function resolveCharIndents(
format: ParaFormat | undefined,
chars: CharIndents,
units: CharUnits,
): ParaFormat {
const f: ParaFormat = { ...(format ?? {}) }
const twips = (hundredths: number, unit: number) => Math.round((hundredths / 100) * unit)
const twipsHanging =
f.indentFirstLine !== undefined && f.indentFirstLine < 0 ? -f.indentFirstLine : 0
const twipsFirst =
f.indentFirstLine !== undefined && f.indentFirstLine > 0 ? f.indentFirstLine : 0
const hanging =
chars.hanging !== undefined
? twips(chars.hanging, units.run)
: chars.firstLine !== undefined
? 0
: twipsHanging
const firstLine =
hanging > 0 ? 0 : chars.firstLine !== undefined ? twips(chars.firstLine, units.run) : twipsFirst
if (chars.left !== undefined || chars.hanging !== undefined) {
const uiLeft = chars.left !== undefined ? twips(chars.left, units.normal) : 0
f.indentLeft = uiLeft + hanging
}
if (hanging > 0) f.indentFirstLine = -hanging
else if (firstLine > 0) f.indentFirstLine = firstLine
else delete f.indentFirstLine
if (chars.right !== undefined) {
const right = twips(chars.right, units.normal)
if (right !== 0) f.indentRight = right
else delete f.indentRight
}
return f
}
/**
* w:sz governing a run-less paragraph's line height: the paragraph-mark rPr
* (pPr/w:rPr), else the last run's rPr — those runs are all empty and get
* dropped, but Word still sizes the empty line by them (1pt spacer lines).
*/
export function emptyParaSizeHalfPoints(pNode: XNode, pPr: XNode | undefined): number | undefined {
let sz = pPr
? attrsOf(findChild(findChild(pPr, 'w:rPr') ?? {}, 'w:sz') ?? {})['w:val']
: undefined
if (!sz) {
for (const r of findChildren(pNode, 'w:r')) {
const v = attrsOf(findChild(findChild(r, 'w:rPr') ?? {}, 'w:sz') ?? {})['w:val']
if (v) sz = v
}
}
const n = sz ? parseInt(sz, 10) : NaN
return Number.isFinite(n) && n > 0 ? n : undefined
}
/**
* w:rFonts governing a run-less paragraph's line height: same sources as
* emptyParaSizeHalfPoints — Word lays the empty line with the mark's face
* metrics, not the document default face.
*/
export function emptyParaMarkFont(pNode: XNode, pPr: XNode | undefined): string | undefined {
const pick = (rPr: XNode | undefined): string | undefined => {
const a = attrsOf(findChild(rPr ?? {}, 'w:rFonts') ?? {})
return a['w:ascii'] ?? a['w:hAnsi'] ?? a['w:eastAsia']
}
let font = pPr ? pick(findChild(pPr, 'w:rPr')) : undefined
if (!font) {
for (const r of findChildren(pNode, 'w:r')) {
const v = pick(findChild(r, 'w:rPr'))
if (v) font = v
}
}
return font
}
export const IMAGE_RUN_CHILDREN = new Set([
'w:drawing',
'w:pict',
'w:object',
'mc:AlternateContent',
])
/** synthetic single-picture runs (rPr copied into each) in document order */
export function splitImageRun(rNode: XNode): XNode[] {
const attrs = rNode[':@']
const rPr = findChild(rNode, 'w:rPr')
const parts: XNode[][] = []
let current: XNode[] = rPr ? [rPr] : []
for (const child of childrenOf(rNode)) {
if (nameOf(child) === 'w:rPr') continue
current.push(child)
if (IMAGE_RUN_CHILDREN.has(nameOf(child) ?? '')) {
parts.push(current)
current = rPr ? [rPr] : []
}
}
if (current.length > (rPr ? 1 : 0)) parts.push(current)
return parts.map((children) => ({ 'w:r': children, ...(attrs ? { ':@': attrs } : {}) }))
}
/** exact <w:ruby> fragments in document order (w:ruby has no attributes and cannot nest) */
export function rubyFragmentsOf(xml: string): string[] {
return xml.match(/<w:ruby>[\s\S]*?<\/w:ruby>/g) ?? []
}
/** concatenated w:t text of the runs inside a ruby part (w:rubyBase / w:rt) */
export function rubyPartText(rubyNode: XNode, part: 'w:rubyBase' | 'w:rt'): string {
const partNode = findChild(rubyNode, part)
if (!partNode) return ''
let text = ''
for (const r of childrenOf(partNode)) {
if (nameOf(r) !== 'w:r') continue
for (const c of childrenOf(r)) {
if (nameOf(c) === 'w:t') text += decodeNumericCharRefs(textOf(c))
}
}
return text
}
/** Word's face for an East Asian theme slot whose typeface is empty (<a:ea typeface=""/>) */
const EMPTY_EA_THEME_FONT = 'DengXian'
/** empty EA slot faces by settings.xml w:themeFontLang w:eastAsia (zh-CN / missing → DengXian) */
const EMPTY_EA_SLOT_BY_LANG: Record<string, { major: string; minor: string }> = {
ja: { major: 'Yu Gothic', minor: 'Yu Mincho' },
// Word probe + fontTable: ko-KR empty EA slot substitutes Malgun Gothic
ko: { major: 'Malgun Gothic', minor: 'Malgun Gothic' },
}
/** themeFontLang w:eastAsia → theme script-table tag (<a:font script=…>) */
const EA_LANG_SCRIPT: Record<string, string> = {
ko: 'Hang',
ja: 'Jpan',
zh: 'Hans',
'zh-cn': 'Hans',
'zh-sg': 'Hans',
'zh-tw': 'Hant',
'zh-hk': 'Hant',
'zh-mo': 'Hant',
}
function emptyEaSlotFont(fonts: ThemeFonts, eaRef: string | undefined): string {
return themeLangEaSlotFont(fonts, eaRef) ?? EMPTY_EA_THEME_FONT
}
/** empty-EA-slot face themeFontLang specifically resolves (theme script table first,
* then the probed per-language defaults); undefined = only the generic DengXian applies */
export function themeLangEaSlotFont(
fonts: ThemeFonts,
eaRef: string | undefined,
): string | undefined {
const full = fonts.eaLang?.toLowerCase()
if (!full) return undefined
const lang = full.split('-')[0]
const script = EA_LANG_SCRIPT[full] ?? EA_LANG_SCRIPT[lang]
const table = eaRef === 'majorEastAsia' ? fonts.majorScripts : fonts.minorScripts
const fromScript = script ? table?.[script] : undefined
if (fromScript) return fromScript
const byLang = EMPTY_EA_SLOT_BY_LANG[lang]
return byLang ? (eaRef === 'majorEastAsia' ? byLang.major : byLang.minor) : undefined
}
/** w:rFonts with theme references resolved: theme attrs supersede same-slot literal
* values (ECMA-376 §17.3.2.26). Unresolvable references fall back to the literal,
* except an empty eastAsia theme slot: Word keeps the theme's authority and renders
* the theme language's default face, never the leftover literal name (eaSlotEmpty marks this). */
export function themedRFonts(
attrs: Record<string, string | undefined>,
fonts: ThemeFonts | null | undefined,
): {
ascii?: string
hAnsi?: string
eastAsia?: string
cs?: string
eaSlotEmpty?: boolean
themed?: { ascii?: boolean; hAnsi?: boolean; eastAsia?: boolean }
} {
const themeVal = (ref: string | undefined): string | undefined => {
if (!ref || !fonts) return undefined
switch (ref) {
case 'majorAscii':
case 'majorHAnsi':
return fonts.major || undefined
case 'minorAscii':
case 'minorHAnsi':
return fonts.minor || undefined
case 'majorEastAsia':
return fonts.majorEastAsia || undefined
case 'minorEastAsia':
return fonts.eastAsia || undefined
case 'majorBidi':
return fonts.majorCs || undefined
case 'minorBidi':
return fonts.minorCs || undefined
default:
return undefined
}
}
const eaRef = attrs['w:eastAsiaTheme']
const themedEa = themeVal(eaRef)
const eaSlotEmpty =
!themedEa && !!fonts && (eaRef === 'majorEastAsia' || eaRef === 'minorEastAsia')
const themedAscii = themeVal(attrs['w:asciiTheme'])
const themedHAnsi = themeVal(attrs['w:hAnsiTheme'])
return {
ascii: themedAscii ?? attrs['w:ascii'],
hAnsi: themedHAnsi ?? attrs['w:hAnsi'],
eastAsia: themedEa ?? (eaSlotEmpty ? emptyEaSlotFont(fonts!, eaRef) : attrs['w:eastAsia']),
cs: themeVal(attrs['w:cstheme']) ?? attrs['w:cs'],
...(eaSlotEmpty ? { eaSlotEmpty } : {}),
themed: {
ascii: themedAscii !== undefined,
hAnsi: themedHAnsi !== undefined,
eastAsia: themedEa !== undefined || eaSlotEmpty,
},
}
}
/** xml:space="preserve" declared on the part's root element — an inherited XML
* scope covering every w:t below it (PDF-to-DOCX converters set it once on
* w:document/w:hdr instead of per element; Word honors the inheritance) */
export function partXmlSpacePreserve(partXml: string, rootTag: string): boolean {
const open = new RegExp(`<${rootTag}(\\s[^>]*)?>`).exec(partXml)?.[1] ?? ''
return /\sxml:space="preserve"/.test(open)
}
export function mergeRuns(runs: Run[]): Run[] {
const merged: Run[] = []
for (const run of runs) {
const prev = merged[merged.length - 1]
if (prev && sameStyle(prev, run)) prev.text += run.text
else merged.push({ ...run })
}
return merged
}
function sameStyle(a: Run, b: Run): boolean {
// reference markers, index entries, cross-references and inline math are atomic; never merge
if (a.noteRef || b.noteRef || a.xeTerm !== undefined || b.xeTerm !== undefined) return false
if (a.refField !== undefined || b.refField !== undefined) return false
if (a.instrField !== undefined || b.instrField !== undefined) return false
if (a.math || b.math) return false
if (a.ruby || b.ruby) return false
if (a.image || b.image) return false
return (
(a.rawRPr ?? '') === (b.rawRPr ?? '') &&
a.styleId === b.styleId &&
!!a.cs === !!b.cs &&
!!a.bold === !!b.bold &&
!!a.italic === !!b.italic &&
!!a.underline === !!b.underline &&
!!a.strike === !!b.strike &&
a.color === b.color &&
a.sizeHalfPoints === b.sizeHalfPoints &&
a.font === b.font &&
a.fontAscii === b.fontAscii &&
a.csFont === b.csFont &&
a.highlight === b.highlight &&
a.vertAlign === b.vertAlign &&
(a.link?.href ?? '') === (b.link?.href ?? '') &&
(a.link?.rId ?? '') === (b.link?.rId ?? '') &&
(a.commentIds ?? []).join(',') === (b.commentIds ?? []).join(',') &&
sameRevision(a.ins, b.ins) &&
sameRevision(a.del, b.del)
)
}
function sameRevision(a: RevisionInfo | undefined, b: RevisionInfo | undefined): boolean {
if (!a || !b) return !a === !b
return a.author === b.author && a.date === b.date && a.id === b.id
}
/** ST_Shd pct values that are not the literal digits in the name */
const SHD_PCT_EXACT: Record<string, number> = { pct12: 12.5, pct37: 37.5, pct62: 62.5, pct87: 87.5 }
function blendHex(fg: string, bg: string, ratio: number): string {
const ch = (hex: string, i: number) => parseInt(hex.slice(i, i + 2), 16)
const mix = (i: number) =>
Math.round(ch(fg, i) * ratio + ch(bg, i) * (1 - ratio))
.toString(16)
.padStart(2, '0')
return (mix(0) + mix(2) + mix(4)).toUpperCase()
}
/**
* w:shd → single display color. Patterns (pctNN, stripes, crosses) approximate
* as the pattern color blended over the fill at the pattern's ink coverage —
* Word's actual dot/stripe raster is out of scope for cell backgrounds.
*/
export function shdDisplayFill(shd: XNode | undefined): string | undefined {
if (!shd) return undefined
const a = attrsOf(shd)
const hex = (v: string | undefined) => {
const s = v ? stripHash(v) : undefined
return s && /^[0-9a-fA-F]{6}$/.test(s) ? s : undefined
}
const fill = a['w:fill'] === 'auto' ? undefined : hex(a['w:fill'])
const val = a['w:val'] ?? 'clear'
if (val === 'clear' || val === 'nil') return fill
const ink = a['w:color'] === 'auto' ? undefined : hex(a['w:color'])
if (val === 'solid') return ink ?? '000000'
let ratio: number | undefined
if (val.startsWith('pct')) {
ratio = (SHD_PCT_EXACT[val] ?? Number(val.slice(3))) / 100
if (!(ratio > 0 && ratio <= 1)) ratio = undefined
} else if (/stripe|cross/i.test(val)) {
ratio = val.startsWith('thin') ? 0.25 : 0.5
}
if (ratio === undefined) return fill
return blendHex(ink ?? '000000', fill ?? 'FFFFFF', ratio)
}
export function tableLookOf(tblPr: XNode | undefined): NonNullable<TableModel['tableLook']> {
const look = attrsOf(findChild(tblPr ?? {}, 'w:tblLook') ?? {})
const bits = parseInt(look['w:val'] ?? '', 16)
const flag = (attr: string, bit: number, dflt: boolean): boolean =>
look[attr] !== undefined
? look[attr] !== '0' && look[attr] !== 'false'
: Number.isFinite(bits)
? (bits & bit) !== 0
: dflt
return {
firstRow: flag('w:firstRow', 0x20, true),
lastRow: flag('w:lastRow', 0x40, false),
firstColumn: flag('w:firstColumn', 0x80, true),
lastColumn: flag('w:lastColumn', 0x100, false),
bandedRows: !flag('w:noHBand', 0x200, false),
bandedColumns: !flag('w:noVBand', 0x400, true),
}
}
function borderLinesOf(node: XNode | undefined, withInside: true): TableBorders | undefined
function borderLinesOf(node: XNode | undefined, withInside: false): CellBorders | undefined
function borderLinesOf(node: XNode | undefined, withInside: boolean): TableBorders | undefined {
if (!node) return undefined
const ALIAS: Record<string, keyof TableBorders> = {
'w:top': 'top',
'w:left': 'left',
'w:bottom': 'bottom',
'w:right': 'right',
'w:start': 'left',
'w:end': 'right',
...(withInside ? { 'w:insideH': 'insideH', 'w:insideV': 'insideV' } : {}),
}
const borders: TableBorders = {}
for (const [tag, side] of Object.entries(ALIAS)) {
const child = findChild(node, tag)
if (!child || borders[side]) continue
const a = attrsOf(child)
if (!a['w:val']) continue
borders[side] = {
style: a['w:val'],
...(a['w:sz'] ? { szEighths: Number(a['w:sz']) || undefined } : {}),
...(a['w:color'] ? { color: stripHash(a['w:color']) } : {}),
}
}
return Object.keys(borders).length > 0 ? borders : undefined
}
/** Duplicated border containers (two w:tcBorders in one tcPr etc.): Word merges per side, later wins */
export function mergedBorderLinesOf(
parent: XNode | undefined,
tag: string,
withInside: true,
): TableBorders | undefined
export function mergedBorderLinesOf(
parent: XNode | undefined,
tag: string,
withInside: false,
): CellBorders | undefined
export function mergedBorderLinesOf(
parent: XNode | undefined,
tag: string,
withInside: boolean,
): TableBorders | undefined {
if (!parent) return undefined
let merged: TableBorders | undefined
for (const node of findChildren(parent, tag)) {
const b = borderLinesOf(node, withInside as true)
if (b) merged = { ...merged, ...b }
}
return merged
}
export function cellMarginsOf(node: XNode | undefined): CellMargins | undefined {
if (!node) return undefined
const SIDES: Array<[string, keyof CellMargins]> = [
['w:top', 'top'],
['w:left', 'left'],
['w:bottom', 'bottom'],
['w:right', 'right'],
['w:start', 'left'],
['w:end', 'right'],
]
const m: CellMargins = {}
for (const [tag, side] of SIDES) {
const a = attrsOf(findChild(node, tag) ?? {})
if (a['w:type'] && a['w:type'] !== 'dxa') continue
const v = Number(a['w:w'])
if (Number.isFinite(v) && v >= 0 && m[side] === undefined) m[side] = v
}
return Object.keys(m).length > 0 ? m : undefined
}
/** Word's substitution face when the East Asian font slot is empty, by w:lang w:eastAsia */
export const EA_LANG_DEFAULT_FONT: Record<string, string> = {
// Word probe + fontTable: ko-KR empty EA slot substitutes Malgun Gothic, not Batang
ko: 'Malgun Gothic',
'ko-kr': 'Malgun Gothic',
ja: 'MS Mincho',
'ja-jp': 'MS Mincho',
'zh-cn': 'SimSun',
'zh-tw': 'PMingLiU',
'zh-hk': 'PMingLiU',
}
+158
View File
@@ -0,0 +1,158 @@
// Structured document tags (w:sdt): block-level SDT classification and the
// split of an SDT's run/table content.
import type { SdtShell } from './types'
/**
* Extract a SdtShell from a raw <w:sdt>…</w:sdt> XML string.
* Returns the shell metadata + the first <w:p> found in <w:sdtContent>,
* or null if no usable paragraph is found.
*/
export function parseSdtBlock(sdtXml: string): { shell: SdtShell; pXml: string } | null {
// --- find the sdtContent region ---
// sdtContent is a direct child of w:sdt; its content may be a w:p or w:tbl
const contentOpen = /<w:sdtContent(?:\s[^>]*)?>/.exec(sdtXml)
if (!contentOpen) return null
const contentTagEnd = contentOpen.index + contentOpen[0].length
// find the matching </w:sdtContent> — last one, so nested content controls
// don't truncate the region (same boundary rule as splitSdtParts/sdtTableXml)
const contentClose = sdtXml.lastIndexOf('</w:sdtContent>')
if (contentClose < contentTagEnd) return null
// extract the first w:p inside sdtContent
const innerContent = sdtXml.slice(contentTagEnd, contentClose)
const pStart = innerContent.search(/<w:p[\s/>]/)
if (pStart === -1) return null
// find matching closing </w:p>
let depth = 0
let pEnd = -1
const tagRe = /<\/?w:p(?=[\s/>])/g
let m: RegExpExecArray | null
while ((m = tagRe.exec(innerContent)) !== null) {
if (m[0].startsWith('</')) {
if (depth === 1) {
pEnd = m.index + m[0].length + 1 // include '>'
break
}
depth--
} else {
depth++
}
}
if (pEnd === -1) {
// self-closing <w:p/> or no </w:p> found — unlikely but safe
const selfClose = /<w:p\/>/.exec(innerContent)
pEnd = selfClose ? selfClose.index + selfClose[0].length : innerContent.length
}
const pXml = innerContent.slice(pStart, pEnd)
// openXml = everything from start of sdt to end of <w:sdtContent> open tag
const openXml = sdtXml.slice(0, contentTagEnd)
const closeXml = sdtXml.slice(contentClose) // "</w:sdtContent></w:sdt>"
return {
shell: { ...sdtMeta(sdtXml), openXml, closeXml },
pXml,
}
}
export function sdtMeta(sdtXml: string): Pick<SdtShell, 'alias' | 'tag' | 'controlType'> {
const sdtPrXml = /<w:sdtPr>([\s\S]*?)<\/w:sdtPr>/.exec(sdtXml)?.[1] ?? ''
const alias = /w:val="([^"]*)"/.exec(/<w:alias[^>]*>/.exec(sdtPrXml)?.[0] ?? '')?.[1] ?? ''
const tag = /w:val="([^"]*)"/.exec(/<w:tag[^>]*>/.exec(sdtPrXml)?.[0] ?? '')?.[1] ?? ''
let controlType: SdtShell['controlType'] = 'text'
if (/<w:date[\s/>]/.test(sdtPrXml)) controlType = 'date'
else if (/<w:dropDownList[\s/>]|<w:comboBox[\s/>]/.test(sdtPrXml)) controlType = 'dropdown'
else if (/<w:checkbox[\s/>]/.test(sdtPrXml)) controlType = 'checkbox'
else if (/<w:text[\s/>]|<w:richText[\s/>]/.test(sdtPrXml)) controlType = 'text'
return { alias, tag, controlType }
}
interface SdtPart {
name: string
/** slice of the whole <w:sdt> xml owned by this part (parts partition the sdt exactly) */
start: number
end: number
/** the w:p / w:tbl child inside [start, end) */
childStart: number
childEnd: number
}
/**
* When <w:sdtContent> holds several top-level w:p / w:tbl children (Word TOC,
* multi-paragraph rich-text controls), each child becomes its own block.
* Returns null for 0-1 children (single-block path keeps its behavior).
*/
export function splitSdtParts(sdtXml: string): SdtPart[] | null {
const contentOpen = /<w:sdtContent(?:\s[^>]*)?>/.exec(sdtXml)
if (!contentOpen) return null
const innerStart = contentOpen.index + contentOpen[0].length
const innerEnd = sdtXml.lastIndexOf('</w:sdtContent>')
if (innerEnd <= innerStart) return null
const children: Array<{ name: string; start: number; end: number }> = []
const tagRe = /<(\/?)([A-Za-z0-9:._-]+)((?:"[^"]*"|'[^']*'|[^"'>])*)>/g
tagRe.lastIndex = innerStart
let depth = 0
let start = -1
let name = ''
let m: RegExpExecArray | null
while ((m = tagRe.exec(sdtXml)) !== null && m.index < innerEnd) {
// nested content controls are transparent containers (Word cover-page
// building blocks wrap each field in its own sdt): descend instead of
// treating the inner sdt as one opaque child
if (m[2] === 'w:sdt' || m[2] === 'w:sdtContent') continue
if (m[1] === '/') {
depth--
if (depth === 0) children.push({ name, start, end: m.index + m[0].length })
} else if (m[3].endsWith('/')) {
if (depth === 0) children.push({ name: m[2], start: m.index, end: m.index + m[0].length })
} else {
if (depth === 0) {
start = m.index
name = m[2]
}
depth++
}
}
const parts = children.filter((c) => c.name === 'w:p' || c.name === 'w:tbl')
if (parts.length < 2) return null
return parts.map((c, k) => ({
name: c.name,
start: k === 0 ? 0 : c.start,
end: k === parts.length - 1 ? sdtXml.length : parts[k + 1].start,
childStart: c.start,
childEnd: c.end,
}))
}
/**
* When a top-level <w:sdt>'s content begins with a table (no paragraph before
* it), return the balanced <w:tbl>…</w:tbl> slice, else null.
*/
export function sdtTableXml(sdtXml: string): string | null {
const contentOpen = /<w:sdtContent(?:\s[^>]*)?>/.exec(sdtXml)
if (!contentOpen) return null
const contentTagEnd = contentOpen.index + contentOpen[0].length
const contentClose = sdtXml.lastIndexOf('</w:sdtContent>')
if (contentClose <= contentTagEnd) return null
const inner = sdtXml.slice(contentTagEnd, contentClose)
const tblStart = inner.search(/<w:tbl[\s>]/)
if (tblStart === -1) return null
const pStart = inner.search(/<w:p[\s/>]/)
if (pStart !== -1 && pStart < tblStart) return null
// balanced </w:tbl> for the opening tag (tables can nest)
let depth = 0
const tagRe = /<\/?w:tbl(?=[\s/>])/g
tagRe.lastIndex = tblStart
let m: RegExpExecArray | null
while ((m = tagRe.exec(inner)) !== null) {
if (m[0].startsWith('</')) {
depth--
if (depth === 0) return inner.slice(tblStart, m.index + '</w:tbl>'.length)
} else depth++
}
return null
}
+513
View File
@@ -0,0 +1,513 @@
// styles.xml: paragraph / character / table style resolution into the
// ParsedDoc style tables.
import JSZip from 'jszip'
import {
attrsOf,
boolProp,
findChild,
findChildren,
nameOf,
xmlParser,
type XNode,
} from './xml-utils'
import { colorFrom, lineTwipsOf, onOffOf, stripHash } from './parse-xml-text'
import {
EA_LANG_DEFAULT_FONT,
autoSpaceOf,
cellMarginsOf,
charIndentsOf,
mergeCharIndents,
mergedBorderLinesOf,
shdDisplayFill,
tabStopsOf,
themeLangEaSlotFont,
themedRFonts,
} from './parse-props'
import type {
DocDefaults,
StyleDisplay,
StyleInfo,
TableStyleDisplay,
ThemeColors,
ThemeFonts,
} from './types'
export async function parseStyles(
zip: JSZip,
theme?: ThemeColors | null,
themeFonts?: ThemeFonts | null,
): Promise<{ styles: Map<string, StyleInfo>; docDefaults?: DocDefaults }> {
const styles = new Map<string, StyleInfo>()
const file = zip.file('word/styles.xml')
if (!file) return { styles }
let parsed: XNode[]
try {
parsed = xmlParser.parse(await file.async('string')) as XNode[]
} catch (err) {
console.warn('styles.xml unparseable, styles degraded to empty:', err)
return { styles }
}
const root = parsed.find((n) => nameOf(n) === 'w:styles')
if (!root) return { styles }
let docDefaults: DocDefaults | undefined
const defaultsNode = findChild(root, 'w:docDefaults')
if (defaultsNode) {
const dd: DocDefaults = {}
const rPr = findChild(findChild(defaultsNode, 'w:rPrDefault') ?? {}, 'w:rPr')
const sz = rPr ? attrsOf(findChild(rPr, 'w:sz') ?? {})['w:val'] : undefined
if (sz) dd.sizeHalfPoints = parseInt(sz, 10) || undefined
const ddRf = themedRFonts(rPr ? attrsOf(findChild(rPr, 'w:rFonts') ?? {}) : {}, themeFonts)
if (ddRf.ascii ?? ddRf.hAnsi) dd.asciiFont = ddRf.ascii ?? ddRf.hAnsi
// docDefaults keeps the lang-based backfill below for the empty-slot case
if (ddRf.eastAsia && !ddRf.eaSlotEmpty) dd.eastAsiaFont = ddRf.eastAsia
// Empty EA slot + w:lang w:eastAsia backfill: when the backfill would fire,
// a face settings.xml themeFontLang resolves (script table / probed locale
// defaults) outranks the often-stale docDefaults w:lang. Without a firing
// backfill the slot stays empty — themeFontLang alone must not invent a
// doc-level EA face (it would reroute PUA/CJK fallback in Latin documents).
const eaLang = rPr ? attrsOf(findChild(rPr, 'w:lang') ?? {})['w:eastAsia'] : undefined
if (!dd.eastAsiaFont && eaLang) {
const eaDefault = EA_LANG_DEFAULT_FONT[eaLang.toLowerCase()]
if (eaDefault) {
const ddEaTheme =
ddRf.eaSlotEmpty && themeFonts
? themeLangEaSlotFont(
themeFonts,
rPr ? attrsOf(findChild(rPr, 'w:rFonts') ?? {})['w:eastAsiaTheme'] : undefined,
)
: undefined
dd.eastAsiaFont = ddEaTheme ?? eaDefault
dd.eaFromLang = true
if (ddRf.eaSlotEmpty) dd.eaSlotEmpty = true
}
}
if (rPr) {
const onFlag = (tag: string) => {
const node = findChild(rPr, tag)
if (!node) return undefined
const val = attrsOf(node)['w:val']
return val === '0' || val === 'false' ? undefined : true
}
if (onFlag('w:b')) dd.bold = true
if (onFlag('w:i')) dd.italic = true
const color = colorFrom(rPr, theme)
if (color) dd.color = color
const lang = attrsOf(findChild(rPr, 'w:lang') ?? {})['w:val']
if (lang) dd.lang = lang
}
const pPr = findChild(findChild(defaultsNode, 'w:pPrDefault') ?? {}, 'w:pPr')
const spacingAttrs = pPr ? attrsOf(findChild(pPr, 'w:spacing') ?? {}) : {}
if (spacingAttrs['w:line']) {
const line = lineTwipsOf(spacingAttrs['w:line'])
const rule = (spacingAttrs['w:lineRule'] ?? 'auto') as 'auto' | 'atLeast' | 'exact'
if (line > 0) {
dd.lineRawTwips = line
dd.lineRule = rule
if (rule === 'auto') dd.lineSpacing = line / 240
}
}
if (spacingAttrs['w:before'] !== undefined) {
dd.spaceBeforeTwips = parseInt(spacingAttrs['w:before'], 10) || 0
}
if (spacingAttrs['w:after'] !== undefined) {
dd.spaceAfterTwips = parseInt(spacingAttrs['w:after'], 10) || 0
}
if (spacingAttrs['w:beforeAutospacing'] !== undefined)
dd.spaceBeforeAuto =
spacingAttrs['w:beforeAutospacing'] === '1' ||
spacingAttrs['w:beforeAutospacing'] === 'true'
if (spacingAttrs['w:afterAutospacing'] !== undefined)
dd.spaceAfterAuto =
spacingAttrs['w:afterAutospacing'] === '1' || spacingAttrs['w:afterAutospacing'] === 'true'
if (pPr && onOffOf(pPr, 'w:suppressAutoHyphens')) dd.suppressAutoHyphens = true
if (Object.keys(dd).length > 0) docDefaults = dd
}
const basedOnIds = new Map<string, string>()
const linkedIds = new Map<string, string>()
// styles with an explicit w:outlineLvl 9 (body text, e.g. TOCHeading basedOn Heading1)
const outlineOffIds = new Set<string>()
for (const styleNode of findChildren(root, 'w:style')) {
const attrs = attrsOf(styleNode)
const type = attrs['w:type']
if (type !== 'paragraph' && type !== 'character' && type !== 'table') continue
const styleId = attrs['w:styleId']
if (!styleId) continue
const name = attrsOf(findChild(styleNode, 'w:name') ?? {})['w:val'] ?? styleId
let headingLevel: number | undefined
if (type === 'paragraph') {
const nameMatch = /^heading\s*([1-9])$/i.exec(name) ?? /^Heading([1-9])$/.exec(styleId)
if (nameMatch) headingLevel = parseInt(nameMatch[1], 10)
else {
const pPr = findChild(styleNode, 'w:pPr')
const outline = pPr ? attrsOf(findChild(pPr, 'w:outlineLvl') ?? {})['w:val'] : undefined
if (outline !== undefined) {
const lvl = parseInt(outline, 10)
if (lvl >= 0 && lvl <= 8) headingLevel = lvl + 1
else outlineOffIds.add(styleId)
}
}
}
const basedOn = attrsOf(findChild(styleNode, 'w:basedOn') ?? {})['w:val']
if (basedOn) basedOnIds.set(styleId, basedOn)
const link = attrsOf(findChild(styleNode, 'w:link') ?? {})['w:val']
if (link) linkedIds.set(styleId, link)
const onFlag = (tag: string): boolean | undefined => {
const node = findChild(styleNode, tag)
if (!node) return undefined
const val = attrsOf(node)['w:val']
return val === '0' || val === 'false' ? undefined : true
}
let numPr: StyleInfo['numPr']
if (type === 'paragraph') {
const styleNumPr = findChild(findChild(styleNode, 'w:pPr') ?? {}, 'w:numPr')
if (styleNumPr) {
const numId = attrsOf(findChild(styleNumPr, 'w:numId') ?? {})['w:val']
if (numId === '0') {
numPr = 'none'
} else if (numId) {
const ilvl = parseInt(attrsOf(findChild(styleNumPr, 'w:ilvl') ?? {})['w:val'] ?? '0', 10)
numPr = { numId, ilvl: ilvl || 0 }
}
}
}
styles.set(styleId, {
styleId,
name,
type,
headingLevel,
semiHidden: onFlag('w:semiHidden'),
qFormat: onFlag('w:qFormat'),
display: type === 'table' ? undefined : styleDisplayOf(styleNode, theme, themeFonts),
tableDisplay: type === 'table' ? tableStyleDisplayOf(styleNode, theme) : undefined,
numPr,
isDefault: attrs['w:default'] === '1' || attrs['w:default'] === 'true' ? true : undefined,
})
}
// Word's effective default per style type: the last w:default="1" wins. When a
// type declares none, Word does NOT use ECMA-376's first-of-type rule — it falls
// back to a style id/named "Normal", else to built-in defaults (docDefaults only).
{
const declared = new Map<string, StyleInfo>()
const normalOfType = new Map<string, StyleInfo>()
for (const info of styles.values()) {
if (info.isDefault) declared.set(info.type, info)
if (
!normalOfType.has(info.type) &&
(info.styleId.toLowerCase() === 'normal' || info.name.toLowerCase() === 'normal')
) {
normalOfType.set(info.type, info)
}
info.isDefault = undefined
}
for (const type of new Set([...declared.keys(), ...normalOfType.keys()])) {
const pick = declared.get(type) ?? normalOfType.get(type)
if (pick) pick.isDefault = true
}
}
// resolve basedOn chains: a style inherits every display prop it doesn't set itself
const resolved = new Set<string>()
const resolve = (styleId: string, seen: Set<string>): StyleInfo | undefined => {
const info = styles.get(styleId)
if (!info) return undefined
const parentId = basedOnIds.get(styleId)
if (resolved.has(styleId) || !parentId || seen.has(styleId)) return info
seen.add(styleId)
const parent = resolve(parentId, seen)
resolved.add(styleId)
if (parent?.display) {
const own = info.display
info.display = { ...parent.display, ...(own ?? {}) }
// w:ind character attributes layer per component: a child's twips-only
// w:ind keeps the parent's *Chars, a child's explicit zero cancels it
if (parent.display.indentChars && own?.indentChars) {
info.display.indentChars = mergeCharIndents(parent.display.indentChars, own.indentChars)
}
if (Object.keys(info.display).length === 0) info.display = undefined
}
if (parent?.tableDisplay) {
info.tableDisplay = mergeTableDisplay(parent.tableDisplay, info.tableDisplay)
}
if (
info.type === 'paragraph' &&
info.headingLevel === undefined &&
!outlineOffIds.has(styleId) &&
parent?.headingLevel
) {
info.headingLevel = parent.headingLevel
}
if (info.type === 'paragraph' && !info.numPr && parent?.numPr) info.numPr = parent.numPr
return info
}
for (const styleId of styles.keys()) resolve(styleId, new Set())
// linkedStyle (w:link): a paragraph style and a character style form one unit (Word
// "linked styles"). Fill in run-level display properties in both directions (never
// overriding a style's own) — the common gap is a character-style shell with no rPr,
// where all run properties live on the linked paragraph style.
const RUN_KEYS = [
'sizeHalfPoints',
'color',
'bold',
'italic',
'boldCs',
'italicCs',
'sizeCsHalfPoints',
'rtl',
'underline',
'strike',
'font',
'fontAscii',
'csFont',
'caps',
] as const
for (const [fromId, toId] of linkedIds) {
const a = styles.get(fromId)
const b = styles.get(toId)
if (!a || !b) continue
for (const [self, other] of [
[a, b],
[b, a],
] as const) {
if (self.type !== 'character' && self.type !== 'paragraph') continue
const fill: Partial<StyleDisplay> = {}
for (const key of RUN_KEYS) {
if (self.display?.[key] === undefined && other.display?.[key] !== undefined) {
;(fill as Record<string, unknown>)[key] = other.display[key]
}
}
if (Object.keys(fill).length > 0) self.display = { ...fill, ...(self.display ?? {}) }
}
if (a.type === 'character' && b.type === 'paragraph') a.linkedCharShell = true
if (b.type === 'character' && a.type === 'paragraph') b.linkedCharShell = true
}
return { styles, docDefaults }
}
function mergeTableDisplay(
parent: TableStyleDisplay,
child: TableStyleDisplay | undefined,
): TableStyleDisplay | undefined {
const merged: TableStyleDisplay = { ...parent, ...(child ?? {}) }
const DEEP = ['wholeTable', 'firstRow', 'firstCol', 'lastCol', 'lastRow', 'paraSpacing'] as const
for (const key of DEEP) {
if (parent[key] || child?.[key]) {
merged[key] = { ...(parent[key] ?? {}), ...(child?.[key] ?? {}) } as never
}
}
return Object.keys(merged).length > 0 ? merged : undefined
}
/** fills / first-row formatting a table style contributes on screen */
function tableStyleDisplayOf(
styleNode: XNode,
theme?: ThemeColors | null,
): TableStyleDisplay | undefined {
const display: TableStyleDisplay = {}
const shdFill = (node: XNode | undefined): string | undefined => {
const fill = node ? attrsOf(findChild(node, 'w:shd') ?? {})['w:fill'] : undefined
return fill && fill !== 'auto' ? stripHash(fill) : undefined
}
const baseFill = shdFill(findChild(styleNode, 'w:tcPr'))
if (baseFill) display.fill = baseFill
const szHalfOf = (rPr: XNode | undefined): number | undefined => {
const val = parseInt(attrsOf(findChild(rPr ?? {}, 'w:sz') ?? {})['w:val'] ?? '', 10)
return val > 0 ? val : undefined
}
const styleRPr = findChild(styleNode, 'w:rPr')
if (styleRPr) {
const wholeTable: NonNullable<TableStyleDisplay['wholeTable']> = {}
const color = colorFrom(styleRPr, theme)
if (color) wholeTable.color = color
if (boolProp(styleRPr, 'w:b')) wholeTable.bold = true
if (boolProp(styleRPr, 'w:i')) wholeTable.italic = true
const sz = szHalfOf(styleRPr)
if (sz) wholeTable.sizeHalfPoints = sz
if (Object.keys(wholeTable).length > 0) display.wholeTable = wholeTable
}
for (const cond of findChildren(styleNode, 'w:tblStylePr')) {
const type = attrsOf(cond)['w:type']
const tcPr = findChild(cond, 'w:tcPr')
const fill = shdFill(tcPr)
if (type === 'firstRow' || type === 'firstCol' || type === 'lastCol' || type === 'lastRow') {
const rPr = findChild(cond, 'w:rPr')
const fmt: NonNullable<TableStyleDisplay['firstRow']> = {}
if (fill) fmt.fill = fill
if (rPr && boolProp(rPr, 'w:b')) fmt.bold = true
const color = colorFrom(rPr, theme)
if (color) fmt.color = color
const sz = szHalfOf(rPr)
if (sz) fmt.sizeHalfPoints = sz
if (Object.keys(fmt).length > 0) display[type] = fmt
} else if (type === 'band1Horz' && fill) {
display.band1Fill = fill
} else if (type === 'band2Horz' && fill) {
display.band2Fill = fill
}
}
const styleTblPr = findChild(styleNode, 'w:tblPr')
const borders = mergedBorderLinesOf(styleTblPr, 'w:tblBorders', true)
if (borders) display.borders = borders
const cellMar = cellMarginsOf(findChild(styleTblPr ?? {}, 'w:tblCellMar'))
if (cellMar) display.cellMarTwips = cellMar
const stylePPr = findChild(styleNode, 'w:pPr')
const jc = attrsOf(findChild(stylePPr ?? {}, 'w:jc') ?? {})['w:val']
if (jc) display.paraJc = jc
const stylePPrSpacing = findChild(stylePPr ?? {}, 'w:spacing')
if (stylePPrSpacing) {
const a = attrsOf(stylePPrSpacing)
const ps: NonNullable<TableStyleDisplay['paraSpacing']> = {}
const before = parseInt(a['w:before'] ?? '', 10)
if (before >= 0 && a['w:before'] !== undefined) ps.beforeTwips = before
const after = parseInt(a['w:after'] ?? '', 10)
if (after >= 0 && a['w:after'] !== undefined) ps.afterTwips = after
const line = lineTwipsOf(a['w:line'])
if (line > 0) {
ps.lineRawTwips = line
const rule = (a['w:lineRule'] ?? 'auto') as 'auto' | 'atLeast' | 'exact'
ps.lineRule = rule
if (rule === 'auto') ps.lineSpacing = Math.round((line / 240) * 100) / 100
}
if (Object.keys(ps).length > 0) display.paraSpacing = ps
}
return Object.keys(display).length > 0 ? display : undefined
}
/**
* Style-chain run props under Word's rtl selection (probed, Word for Mac 2026-08):
* rtl runs read only the Cs twins (w:bCs/w:iCs/w:szCs), non-rtl runs read only the
* base props — no cross-fallback. Pass the run's cs flag; callers without run
* context (style gallery previews, caret defaults) pass false (= non-rtl).
*/
export function styleRunFormat(
display: StyleDisplay | undefined,
cs: boolean,
): Pick<StyleDisplay, 'bold' | 'italic' | 'sizeHalfPoints'> {
if (!display) return {}
return cs
? { bold: display.boldCs, italic: display.italicCs, sizeHalfPoints: display.sizeCsHalfPoints }
: { bold: display.bold, italic: display.italic, sizeHalfPoints: display.sizeHalfPoints }
}
/** display-only formatting the style contributes on screen (Word renders these from styles.xml) */
function styleDisplayOf(
styleNode: XNode,
theme?: ThemeColors | null,
themeFonts?: ThemeFonts | null,
): StyleDisplay | undefined {
const display: StyleDisplay = {}
const rPr = findChild(styleNode, 'w:rPr')
if (rPr) {
const sz = attrsOf(findChild(rPr, 'w:sz') ?? {})['w:val']
if (sz) display.sizeHalfPoints = parseInt(sz, 10) || undefined
const color = colorFrom(rPr, theme)
if (color) display.color = color
const bold = onOffOf(rPr, 'w:b')
if (bold !== undefined) display.bold = bold
const italic = onOffOf(rPr, 'w:i')
if (italic !== undefined) display.italic = italic
// Cs twins carried separately: the consuming run picks the set by its rtl flag
// (styleRunFormat); consumers without run context read the base props (= non-rtl)
const boldCs = onOffOf(rPr, 'w:bCs')
if (boldCs !== undefined) display.boldCs = boldCs
const italicCs = onOffOf(rPr, 'w:iCs')
if (italicCs !== undefined) display.italicCs = italicCs
const szCs = attrsOf(findChild(rPr, 'w:szCs') ?? {})['w:val']
if (szCs) display.sizeCsHalfPoints = parseInt(szCs, 10) || undefined
const rtl = onOffOf(rPr, 'w:rtl')
if (rtl !== undefined) display.rtl = rtl
const u = attrsOf(findChild(rPr, 'w:u') ?? {})['w:val']
if (u) display.underline = u !== 'none'
const strike = onOffOf(rPr, 'w:strike')
if (strike !== undefined) display.strike = strike
const rf = themedRFonts(attrsOf(findChild(rPr, 'w:rFonts') ?? {}), themeFonts)
const font = rf.eastAsia ?? rf.ascii ?? rf.hAnsi
const fontAscii = rf.ascii ?? rf.hAnsi
if (fontAscii) display.fontAscii = fontAscii
if (rf.cs) display.csFont = rf.cs
if (font) display.font = font
if (rf.eaSlotEmpty && font && font === rf.eastAsia) display.eaSlotEmpty = true
const spc = parseInt(attrsOf(findChild(rPr, 'w:spacing') ?? {})['w:val'] ?? '', 10)
if (spc) display.charSpacingTwips = spc
const capsOn = onOffOf(rPr, 'w:caps')
const smallCapsOn = onOffOf(rPr, 'w:smallCaps')
if (capsOn) display.caps = 'all'
else if (smallCapsOn) display.caps = 'small'
else if (capsOn === false || smallCapsOn === false) display.caps = 'none'
// w:specVanish marks a style separator, not hidden text
const vanish = onOffOf(rPr, 'w:vanish')
if (vanish !== undefined && onOffOf(rPr, 'w:specVanish') !== true) display.vanish = vanish
}
const pPr = findChild(styleNode, 'w:pPr')
if (pPr) {
const spacing = attrsOf(findChild(pPr, 'w:spacing') ?? {})
const line = lineTwipsOf(spacing['w:line'])
if (line > 0) {
const rule = (spacing['w:lineRule'] ?? 'auto') as 'auto' | 'atLeast' | 'exact'
display.lineRule = rule
display.lineRawTwips = line
if (rule === 'auto') {
display.lineSpacing = line / 240
}
}
if (spacing['w:before'] !== undefined) {
display.spaceBeforeTwips = parseInt(spacing['w:before'], 10) || 0
}
if (spacing['w:after'] !== undefined) {
display.spaceAfterTwips = parseInt(spacing['w:after'], 10) || 0
}
// tri-state so a child style's explicit "0" overrides the basedOn chain's auto
if (spacing['w:beforeAutospacing'] !== undefined)
display.spaceBeforeAuto =
spacing['w:beforeAutospacing'] === '1' || spacing['w:beforeAutospacing'] === 'true'
if (spacing['w:afterAutospacing'] !== undefined)
display.spaceAfterAuto =
spacing['w:afterAutospacing'] === '1' || spacing['w:afterAutospacing'] === 'true'
if (boolProp(pPr, 'w:keepNext')) display.keepNext = true
if (boolProp(pPr, 'w:keepLines')) display.keepLines = true
{
const pbb = onOffOf(pPr, 'w:pageBreakBefore')
if (pbb !== undefined) display.pageBreakBefore = pbb
}
{
const sah = onOffOf(pPr, 'w:suppressAutoHyphens')
if (sah !== undefined) display.suppressAutoHyphens = sah
}
{
// tri-state so a child style's explicit off survives the basedOn merge
const ctx = onOffOf(pPr, 'w:contextualSpacing')
if (ctx !== undefined) display.contextualSpacing = ctx
}
const autoSpace = autoSpaceOf(pPr)
if (autoSpace !== undefined) display.autoSpace = autoSpace
const jc = attrsOf(findChild(pPr, 'w:jc') ?? {})['w:val']
if (jc === 'center' || jc === 'right' || jc === 'left' || jc === 'justify') display.align = jc
else if (jc === 'both' || jc === 'distribute') display.align = 'justify'
const shdDisp = shdDisplayFill(findChild(pPr, 'w:shd'))
if (shdDisp) display.shadingFill = shdDisp
const stops = tabStopsOf(pPr)
if (stops) display.tabStops = stops
const ind = findChild(pPr, 'w:ind')
if (ind) {
const a = attrsOf(ind)
const left = parseInt(a['w:left'] ?? a['w:start'] ?? '', 10)
if (Number.isFinite(left) && left !== 0) display.indentLeftTwips = left
const right = parseInt(a['w:right'] ?? a['w:end'] ?? '', 10)
if (Number.isFinite(right) && right !== 0) display.indentRightTwips = right
const firstLine = parseInt(a['w:firstLine'] ?? '', 10)
const hanging = parseInt(a['w:hanging'] ?? '', 10)
if (hanging > 0) display.indentFirstLineTwips = -hanging
else if (firstLine > 0) display.indentFirstLineTwips = firstLine
// character-unit indents depend on each paragraph's text; kept raw (explicit
// zeros included, they cancel an inherited value) for the parser
const chars = charIndentsOf(ind)
if (chars) display.indentChars = chars
}
}
return Object.keys(display).length > 0 ? display : undefined
}
+286
View File
@@ -0,0 +1,286 @@
// Legacy VML (v:shape / v:group) geometry and color readers.
import { attrsOf, findChild, type XNode } from './xml-utils'
import { EMU_PER_PX } from './parse-xml-text'
import type { Run, TextboxDisplay } from './types'
/** VML style="width:189.9pt;height:626pt" dimension → CSS px */
function vmlStyleDimPx(style: string, key: 'width' | 'height'): number | undefined {
const m = new RegExp(`(?:^|;)\\s*${key}:([0-9.]+)(pt|px|in|mm|cm)?`).exec(style)
if (!m) return undefined
const v = parseFloat(m[1]!)
if (!Number.isFinite(v) || v <= 0) return undefined
const unit = m[2] ?? 'pt'
const px =
unit === 'px'
? v
: unit === 'in'
? v * 96
: unit === 'mm'
? (v / 25.4) * 96
: unit === 'cm'
? (v / 2.54) * 96
: (v * 96) / 72
return Math.round(px)
}
/** HTML color names VML attributes use ("silver", "blue"…) */
const VML_NAMED_COLORS: Record<string, string> = {
black: '000000',
white: 'FFFFFF',
red: 'FF0000',
green: '008000',
blue: '0000FF',
yellow: 'FFFF00',
silver: 'C0C0C0',
gray: '808080',
grey: '808080',
maroon: '800000',
olive: '808000',
navy: '000080',
purple: '800080',
teal: '008080',
fuchsia: 'FF00FF',
lime: '00FF00',
aqua: '00FFFF',
cyan: '00FFFF',
orange: 'FFA500',
}
/** VML color attr ("#dbe5f1", "#aaa", "#dbe5f1 [3204]", "silver") → hex without '#' */
export function vmlColorHex(value: string | undefined): string | undefined {
if (!value) return undefined
const v = value.trim()
const m6 = /^#?([0-9a-fA-F]{6})/.exec(v)
if (m6) return m6[1]
const m3 = /^#([0-9a-fA-F]{3})(?![0-9a-fA-F])/.exec(v)
if (m3) {
return m3[1]
.split('')
.map((c) => c + c)
.join('')
}
return VML_NAMED_COLORS[v.split(/[\s[]/, 1)[0]!.toLowerCase()]
}
/** VML WordArt: a shape carrying its text in a v:textpath string attribute */
export const VML_WORDART_RE = /<v:textpath[^>]*\bstring="/
/**
* A v:imagedata that actually references a picture. WPS writes a bare
* <v:imagedata o:title=""/> on ordinary textbox/geometry shapes; only an
* r:id makes the pict a picture.
*/
export const VML_PICT_RID_RE = /<v:imagedata[^>]*\br:id="/
/** px per group-coordinate unit for children of a v:group (drawing canvas) */
export interface VmlGroupScale {
sx: number
sy: number
}
/** a group-child origin, px from the host paragraph */
export interface VmlOrigin {
x: number
y: number
}
export function vmlGroupScale(
group: XNode,
parentScale: VmlGroupScale | null = null,
): VmlGroupScale | null {
const a = attrsOf(group)
const style = a['style'] ?? ''
// a nested group sizes in its parent's unitless coordinates
const wPx = vmlShapeDimPx(style, 'width', parentScale)
const hPx = vmlShapeDimPx(style, 'height', parentScale)
const cs = /^\s*(-?\d+)[,\s]+(-?\d+)/.exec(a['coordsize'] ?? '')
const cw = cs ? parseInt(cs[1]!, 10) : NaN
const ch = cs ? parseInt(cs[2]!, 10) : NaN
if (!wPx || !hPx || !(cw > 0) || !(ch > 0)) return null
return { sx: wPx / cw, sy: hPx / ch }
}
/** style left/top of a group child → px from the paragraph (group origin + scaled coordinate) */
export function vmlCoordPx(
style: string,
key: 'left' | 'top',
scale: VmlGroupScale,
origin: VmlOrigin,
): number {
const m = new RegExp(`(?:^|;)\\s*${key}:(-?[\\d.]+)(pt|px|in|mm|cm)?(?=;|$)`).exec(style)
const base = key === 'left' ? origin.x : origin.y
if (!m) return base
const v = parseFloat(m[1]!)
if (!Number.isFinite(v)) return base
if (m[2]) {
const px =
m[2] === 'px'
? v
: m[2] === 'in'
? v * 96
: m[2] === 'mm'
? (v / 25.4) * 96
: m[2] === 'cm'
? (v / 2.54) * 96
: (v * 96) / 72
return base + px
}
return base + v * (key === 'left' ? scale.sx : scale.sy)
}
/**
* VML path attribute → normalized (0..1) SVG path. Straight-edge subset only
* (m/l absolute, t/r relative, x close, e end) — curve or arc commands bail so
* the caller draws nothing instead of a wrong solid box.
*/
export function vmlPathToNormD(path: string, cw: number, ch: number): string | undefined {
if (!(cw > 0) || !(ch > 0)) return undefined
const norm = (v: number, c: number): number => Math.round((v / c) * 10000) / 10000
const parts: string[] = []
let i = 0
let cx = 0
let cy = 0
const readPairs = (): number[] | null => {
// an omitted coordinate between separators means 0 ("m,l,21600...")
const m = /^[-\d.,\s]+/.exec(path.slice(i))
if (!m) return null
i += m[0].length
const nums = m[0]
.trim()
.split(/[,\s]/)
.map((tok) => (tok === '' ? 0 : parseFloat(tok)))
if (nums.some((v) => !Number.isFinite(v))) return null
return nums.length > 0 && nums.length % 2 === 0 ? nums : null
}
while (i < path.length) {
const c = path[i]!
if (c === ' ' || c === ',') {
i++
continue
}
// nf/ns are fill/stroke hints, not geometry — before the 'e' check, or
// an 'nf' would read as fatal
if (path.startsWith('nf', i) || path.startsWith('ns', i)) {
i += 2
continue
}
if (c === 'e') {
i++
continue
}
if (c === 'x') {
parts.push('Z')
i++
continue
}
if (c === 'm' || c === 'l' || c === 't' || c === 'r') {
i++
const nums = readPairs()
if (!nums) return undefined
const rel = c === 't' || c === 'r'
const move = c === 'm' || c === 't'
for (let k = 0; k < nums.length; k += 2) {
cx = rel ? cx + nums[k]! : nums[k]!
cy = rel ? cy + nums[k + 1]! : nums[k + 1]!
parts.push(`${k === 0 && move ? 'M' : 'L'} ${norm(cx, cw)} ${norm(cy, ch)}`)
}
continue
}
return undefined
}
return parts.length > 1 ? parts.join(' ') : undefined
}
/** shape dimension → px: explicit units directly, unitless via the group scale */
export function vmlShapeDimPx(
style: string,
key: 'width' | 'height',
scale: VmlGroupScale | null,
): number | undefined {
const m = new RegExp(`(?:^|;)\\s*${key}:([0-9.]+)(pt|px|in|mm|cm)?`).exec(style)
if (!m) return undefined
if (m[2] || !scale) return vmlStyleDimPx(style, key)
const v = parseFloat(m[1]!)
if (!Number.isFinite(v) || v <= 0) return undefined
return Math.round(v * (key === 'width' ? scale.sx : scale.sy))
}
/**
* WordArt degrade: v:textpath shapes (shapetype 136 family) render their
* string as plain styled text — no path warp / 3D, but the text is visible at
* roughly the declared size and position instead of an opaque chip.
*/
export function vmlWordArtBox(shape: XNode): TextboxDisplay | null {
const tp = findChild(shape, 'v:textpath')
if (!tp) return null
const text = attrsOf(tp)['string']
if (!text || text.trim() === '') return null
const shapeAttrs = attrsOf(shape)
const style = shapeAttrs['style'] ?? ''
const box: TextboxDisplay = {
paras: [],
readOnly: true,
insetTopPx: 0,
insetRightPx: 0,
insetBottomPx: 0,
insetLeftPx: 0,
}
const w = vmlStyleDimPx(style, 'width')
if (w) box.widthPx = w
const h = vmlStyleDimPx(style, 'height')
if (h) box.heightPx = h
// floating WordArt keeps the flow like other absolute shapes
if (/position:\s*absolute/.test(style)) {
box.floating = true
const marginPx = (key: string): number => {
const pt = parseFloat(new RegExp(`(?:^|;)\\s*${key}:(-?[\\d.]+)pt`).exec(style)?.[1] ?? '')
return Number.isFinite(pt) ? (pt / 72) * 96 : 0
}
box.offsetXEmu = Math.round(marginPx('margin-left') * EMU_PER_PX)
box.offsetYEmu = Math.round(marginPx('margin-top') * EMU_PER_PX)
}
const tpStyle = attrsOf(tp)['style'] ?? ''
const family = /font-family:\s*"?([^;"]+)"?/.exec(tpStyle)?.[1]?.trim()
const sizePt = parseFloat(/font-size:\s*([\d.]+)pt/.exec(tpStyle)?.[1] ?? '')
// fill becomes the *text* color: fillcolor, else the v:fill color/color2
const fillNode = findChild(shape, 'v:fill')
const fillAttrs = fillNode ? attrsOf(fillNode) : {}
const fill =
shapeAttrs['filled'] === 'f'
? undefined
: (vmlColorHex(shapeAttrs['fillcolor']) ??
vmlColorHex(fillAttrs['color']) ??
vmlColorHex(fillAttrs['color2']))
if (shapeAttrs['stroked'] !== 'f') {
const strokeColor = vmlColorHex(shapeAttrs['strokecolor']) ?? '000000'
const weightPt = parseFloat(
/^([\d.]+)(?:pt)?$/.exec(shapeAttrs['strokeweight'] ?? '')?.[1] ?? '',
)
box.textOutline = {
colorHex: strokeColor,
widthPx:
Number.isFinite(weightPt) && weightPt > 0
? Math.round((weightPt / 72) * 96 * 100) / 100
: 1,
}
}
const heightPt = h ? (h / 96) * 72 : NaN
const run: Run = { text }
// fitshape sizes the glyphs to the box; the declared font-size matches it in
// practice (box height ≈ font-size × line factor), so prefer the declared pt
let pt = Number.isFinite(sizePt) && sizePt > 0 ? sizePt : heightPt > 0 ? heightPt / 1.4 : NaN
// fitpath compresses long strings into the box; approximate by shrinking the
// font until the single line fits the declared width (~0.62 em per glyph)
const widthPt = w ? (w / 96) * 72 : NaN
if (Number.isFinite(pt) && widthPt > 0 && text.length > 0) {
pt = Math.max(6, Math.min(pt, widthPt / (0.62 * text.length)))
}
if (Number.isFinite(pt) && pt > 0) run.sizeHalfPoints = Math.round(pt * 2)
box.nowrap = true
if (family) run.fontAscii = family
if (fill) run.color = fill
if (/font-weight:\s*bold/.test(tpStyle)) run.bold = true
if (/font-style:\s*italic/.test(tpStyle)) run.italic = true
box.paras.push({ runs: [run], align: 'center' })
return box
}
+115
View File
@@ -0,0 +1,115 @@
// Text and unit primitives shared by every parse-* module: entity decoding,
// plain-text extraction, on/off and measurement attribute readers.
import { attrsOf, findChild, type XNode } from './xml-utils'
import { resolveThemeColor } from './theme'
import type { ThemeColors } from './types'
export interface RelInfo {
target: string
type: string
targetMode?: string
}
/** hex color value tolerance: Word/LO accept a leading '#' (tdf#57589) */
export function stripHash(v: string): string {
return v.startsWith('#') ? v.slice(1) : v
}
/** Word drops schema-invalid w:line values (e.g. floats from Google Docs) wholesale */
export function lineTwipsOf(v: string | undefined): number {
return v !== undefined && /^-?\d+$/.test(v) ? parseInt(v, 10) : NaN
}
/** w:color -> display hex; w:themeColor resolves against the live palette (beats stale w:val) */
export function colorFrom(
container: XNode | undefined,
theme?: ThemeColors | null,
): string | undefined {
if (!container) return undefined
const a = attrsOf(findChild(container, 'w:color') ?? {})
if (a['w:themeColor'] && theme) {
const resolved = resolveThemeColor(
a['w:themeColor'],
theme,
a['w:themeTint'],
a['w:themeShade'],
)
if (resolved) return resolved
}
const val = a['w:val']
return val && val !== 'auto' ? stripHash(val) : undefined
}
/** OOXML on/off toggle, three-state: absent → undefined, explicit off → false */
export function onOffOf(parent: XNode, name: string): boolean | undefined {
const child = findChild(parent, name)
if (!child) return undefined
const val = attrsOf(child)['w:val']
if (val === undefined) return true
return !['0', 'false', 'none', 'off'].includes(val.toLowerCase())
}
export function plainText(xml: string): string {
const texts: string[] = []
// a space at cell boundaries keeps table text from gluing together
const re = /<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>|<\/w:tc>/g
let m: RegExpExecArray | null
let pendingGap = false
while ((m = re.exec(xml)) !== null) {
if (m[0] === '</w:tc>') {
pendingGap = texts.length > 0
continue
}
if (pendingGap) {
texts.push(' ')
pendingGap = false
}
texts.push(m[1])
}
return decodeEntities(texts.join(''))
}
/** Visible OMML leaf tokens; editing these preserves the surrounding formula tree. */
export function mathTokens(xml: string): string[] {
const tokens: string[] = []
const re = /<m:t(?:\s[^>]*)?>([\s\S]*?)<\/m:t>/g
let m: RegExpExecArray | null
while ((m = re.exec(xml)) !== null) tokens.push(decodeEntities(m[1]))
return tokens
}
/**
* Numeric character references only (`&#65;` / `&#xF0B7;`), which fast-xml-parser
* leaves alone. Text and attribute values read off the parse tree have already had
* the five named entities resolved, so they must NOT be run through the named-entity
* replacements again: a document whose visible text is literally `&lt;` is stored as
* `&amp;lt;`, and a second decode would turn it into `<`.
*/
export function decodeNumericCharRefs(text: string): string {
return text.replace(
/&#(?:x([0-9a-f]+)|([0-9]+));/gi,
(entity, hex: string | undefined, decimal: string | undefined) => {
const codePoint = parseInt(hex ?? decimal ?? '', hex ? 16 : 10)
return Number.isFinite(codePoint) &&
codePoint >= 0 &&
codePoint <= 0x10ffff &&
!(codePoint >= 0xd800 && codePoint <= 0xdfff)
? String.fromCodePoint(codePoint)
: entity
},
)
}
/** Full decode, for raw XML slices that never passed through the parser. */
export function decodeEntities(text: string): string {
return decodeNumericCharRefs(text)
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&amp;/g, '&')
}
export const EMU_PER_PX = 9525
export const EMU_PER_PT = 12700
File diff suppressed because it is too large Load Diff
+11 -1
View File
@@ -53,12 +53,21 @@ function pageBorderPropsOf(xml: string): SectionSettings['pageBorderProps'] {
let spacePt = 0
let szEighths = 0
let color: string | undefined
const sides: NonNullable<SectionSettings['pageBorderProps']>['sides'] = {}
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
const name = /<w:(top|left|bottom|right)\b/.exec(side)![1] as keyof typeof sides
const sideColor = /w:color="([0-9A-Fa-f]{6})"/.exec(side)?.[1]
sides[name] = {
val,
widthPt: intAttr(side, 'w:sz', 0) / 8,
spacePt: intAttr(side, 'w:space', 0),
...(sideColor ? { color: sideColor } : {}),
}
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]
color ??= sideColor
}
return {
...(display ? { display } : {}),
@@ -66,6 +75,7 @@ function pageBorderPropsOf(xml: string): SectionSettings['pageBorderProps'] {
spacePt,
widthPt: szEighths / 8,
...(color ? { color } : {}),
sides,
}
}
+73 -1
View File
@@ -265,6 +265,20 @@ export interface ParaFrame {
wrap?: 'none' | 'around' | 'through' | 'notBeside' | 'auto'
}
/**
* Character-unit indents a w:ind specifies (w:leftChars / w:rightChars /
* w:firstLineChars / w:hangingChars), in hundredths of a character — the way
* CJK documents express "first-line indent: 2 characters". An explicit 0 is
* recorded as such: Word writes it to mean "this indent is absolute", and it
* cancels the value inherited from a parent style.
*/
export interface CharIndents {
left?: number
right?: number
firstLine?: number
hanging?: number
}
export interface ParaFormat {
/** w:jc */
align?: ParaAlign
@@ -284,8 +298,15 @@ export interface ParaFormat {
indentLeft?: number
/** right indent in twips (w:ind w:right) */
indentRight?: number
/** first-line indent in twips; positive = w:firstLine, negative = w:hanging */
/** first-line indent in twips; positive = w:firstLine, negative = w:hanging.
* Character-unit indents (w:firstLineChars…) are already resolved into these
* twips fields at parse time — see resolveCharIndents. */
indentFirstLine?: number
/** the active character-unit indents (direct w:ind or style chain) the twips
* fields above were resolved from. Parse-side only: a save that rebuilds w:ind
* writes the matching `*Chars="0"` for them (mergePPrFormat), or Word keeps
* preferring the character indent over the new twips value on reload. */
charIndents?: CharIndents
/** space above the paragraph in twips (w:spacing w:before) */
spaceBefore?: number
/** space below the paragraph in twips (w:spacing w:after) */
@@ -390,6 +411,22 @@ export interface SectionSettings {
widthPt: number
/** hex without '#', first side declaring a literal color */
color?: string
/** per-side lines; a missing side draws no border */
sides?: Partial<
Record<
'top' | 'right' | 'bottom' | 'left',
{
/** OOXML line style (w:val: single, double, thinThickSmallGap, …) */
val: string
/** line width in points (w:sz eighth-points / 8) */
widthPt: number
/** border distance in points (w:space) */
spacePt: number
/** hex without '#' */
color?: string
}
>
>
}
/** number of text columns (w:cols w:num), 1 = normal */
columns: number
@@ -444,6 +481,9 @@ export interface HfParagraph extends ParaFormat {
/** w:framePr w:xAlign — text frame floated at the margin edge; the line
* overlays the following paragraph's flow line instead of stacking (Word) */
frameXAlign?: 'left' | 'center' | 'right'
/** surfaced content of a floating textbox (wp:anchor / absolute VML shape):
* drawn at the anchor in Word, so it adds no strip flow height */
boxAnchored?: boolean
/** w:ptab alignments indexed by overall tab order (regular w:tab slots are undefined); margin-relative, ignores tab stops */
ptabAligns?: Array<'left' | 'center' | 'right' | undefined>
runs: Run[]
@@ -584,6 +624,8 @@ export interface NoteInfo {
text: string
/** rich display runs (one group per paragraph); gone when an edit rebuilds the note as plain text */
richParas?: NoteRun[][]
/** no w:footnoteRef/w:endnoteRef run in the note body: Word renders the entry without a number mark */
noRefMark?: true
/** w:pStyle of the first note paragraph (notes without one render with Normal metrics) */
styleId?: string
/** direct w:spacing of the first note paragraph (overrides the style chain) */
@@ -668,6 +710,10 @@ export interface ChartDisplay {
grouping?: 'stacked' | 'percentStacked'
/** line charts: draw point markers (c:marker) */
markers?: boolean
/** doughnut hole as % of the radius (c:holeSize); absent = solid pie */
holePct?: number
/** legend position (c:legend/c:legendPos); absent = no c:legend element */
legendPos?: 'b' | 'l' | 'r' | 't' | 'tr'
/** chart title; undefined when the chart has no title part (then not editable) */
title?: string
categories: string[]
@@ -834,6 +880,9 @@ export interface TableModel {
autoLayout?: boolean
/** editable Word AutoFit mode (w:tblLayout + w:tblW) */
autoFit?: TableAutoFitMode
/** literal w:tblLayout type="fixed": Word keeps the declared column widths even when the
* table runs past the paper edge (content clips there), so display must never narrow them */
fixedLayout?: boolean
/** table-level default cell margins (w:tblCellMar) */
cellMarTwips?: CellMargins
/** w:tblCellSpacing (twips, half the gap between adjacent cells); cells render boxed with gaps */
@@ -979,6 +1028,13 @@ export interface NewImage {
export type BlockType = 'paragraph' | 'heading' | 'listItem' | 'table' | 'image' | 'passthrough'
/** direct w:ind of a textbox anchor paragraph (twips; negative firstLine = hanging) */
export interface StrayIndent {
leftTwips?: number
rightTwips?: number
firstLineTwips?: number
}
export interface Block {
/** stable id for editor bookkeeping */
id: string
@@ -1109,6 +1165,8 @@ export interface Block {
strayRuns?: Run[]
/** w:pStyle of the anchor paragraph; styles strayRuns via data-style */
strayStyleId?: string
/** the anchor paragraph's direct w:ind (display-only, lays out the stray line) */
strayIndent?: StrayIndent
/** text tokens of an OMML formula, in document order */
formulaDisplay?: FormulaDisplay
/** display/edit model of an embedded chart (set on chart-labeled blocks) */
@@ -1236,6 +1294,8 @@ export interface TextboxDisplay {
floating?: boolean
/** behindDoc="1" anchor: this box paints under the body text */
behind?: boolean
/** wp:anchor relativeHeight rank (display-only): paint order among overlapping floats */
z?: number
/** 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
@@ -1252,6 +1312,9 @@ export interface TextboxDisplay {
/** the band's top edge (px, offset component of bandBottomPx); the renderer
* adds the live box height so in-editor autogrow moves the band with it */
bandTopPx?: number
/** column-spanning wrapSquare band: Word keeps the box on its anchor's page
* and lets it overflow the bottom margin instead of pushing it whole */
bandOverflow?: boolean
/** rotation in degrees clockwise (a:xfrm rot / 60000) */
rotDeg?: number
/** border width in CSS px (a:ln w) */
@@ -1352,6 +1415,9 @@ export interface StyleDisplay {
indentLeftTwips?: number
indentRightTwips?: number
indentFirstLineTwips?: number
/** character-unit indents from the style definition; their twips value depends
* on each paragraph's text, so the parser resolves them per paragraph */
indentChars?: CharIndents
/** F1: keepNext from style definition */
keepNext?: boolean
/** keepLines from style definition */
@@ -1436,6 +1502,8 @@ export interface DocDefaults {
eastAsiaFont?: string
/** eastAsiaFont is a lang-based backfill for an empty theme slot, not a document choice */
eaSlotEmpty?: boolean
/** eastAsiaFont was backfilled from w:lang w:eastAsia, not declared */
eaFromLang?: boolean
/** bold/italic/color from rPrDefault (display-layer defaults, used by canvas CSS) */
bold?: boolean
italic?: boolean
@@ -1607,6 +1675,10 @@ export interface ParsedDoc {
autoHyphenation?: boolean
/** settings.xml <w:balanceSingleByteDoubleByteWidth/> — rPr w:spacing counts double on double-byte characters */
balanceDbcsSpacing?: boolean
/** settings.xml w:characterSpacingControl compressPunctuation* — justified CJK lines compress trailing-blank punctuation */
compressPunctuation?: boolean
/** settings.xml w:compat <w:adjustLineHeightInTable/> — table-cell lines snap to the typed docGrid like body lines */
adjustLineHeightInTable?: boolean
/** settings.xml w:defaultTabStop in twips (absent = Word's 720); 0 = zero-width default tabs */
defaultTabStopTwips?: number
/** first-page header/footer parts (w:type="first"), null when absent */
@@ -37,3 +37,9 @@ Local modifications to `index.mjs` (2026-08, GenOffice):
bounds-tight canvas got stretched to the frame's aspect by the display box
(e.g. OLE preview text filling a third of a page-wide frame drew giant and
deformed); matching frames keep the established bounds mapping
- LOGFONTW FaceName read at offset +32 (upstream read +28, landing in the
OutPrecision/ClipPrecision/Quality/PitchAndFamily bytes — GDI+-generated EMFs
set those non-zero, prefixing the family with control chars; the invalid CSS
ident made `ctx.font` assignment fail silently and text drew at the default
10px); mapFontFamily now also strips control chars and quotes non-generic
families so a corrupt facename can never drop the font size again
+22 -5
View File
@@ -424,12 +424,26 @@ function cssFontWeight(weight) {
}
return weight >= 700 ? "bold" : "";
}
var GENERIC_CSS_FAMILIES = /* @__PURE__ */ new Set([
"serif",
"sans-serif",
"monospace",
"cursive",
"fantasy",
"system-ui"
]);
function mapFontFamily(face, map) {
const resolved = map?.[face.toLowerCase().trim()] ?? face;
if (/[\s,]/.test(resolved) && !/^["']/.test(resolved)) {
return `"${resolved}"`;
// Strip control chars (corrupt facenames): an invalid family makes the
// whole ctx.font assignment fail silently, dropping the size too
const cleaned = (face || "").replace(/[\u0000-\u001F\u007F]/g, "").trim();
const resolved = map?.[cleaned.toLowerCase()] ?? cleaned;
if (!resolved) {
return "sans-serif";
}
return resolved;
if (GENERIC_CSS_FAMILIES.has(resolved) || /^["']/.test(resolved)) {
return resolved;
}
return `"${resolved.replace(/["\\]/g, "")}"`;
}
function fontSizePx(state, scale = 1) {
return Math.max(Math.abs(state.fontHeight) * Math.abs(scale || 1), 8);
@@ -2339,7 +2353,10 @@ function handleEmfObjectRecord(rCtx, recType, dataOff, recSize) {
const italic = view.getUint8(dataOff + 24);
const underline = view.getUint8(dataOff + 25);
const strikeOut = view.getUint8(dataOff + 26);
const family = readUtf16LE(view, dataOff + 28, 32) || "sans-serif";
// LOGFONTW FaceName at +32: ihFont(4) Height..Weight(20)
// Italic/Underline/StrikeOut/CharSet(1 each) OutPrec/ClipPrec/Quality/
// PitchAndFamily(1 each) — +28 lands in the precision/quality bytes
const family = readUtf16LE(view, dataOff + 32, 32) || "sans-serif";
rCtx.objectTable.set(ihFont, {
kind: "font",
height: Math.abs(height),
@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest'
import { buildAnchoredTextboxParagraphXml } from '../src/generate'
import { parseDocx } from '../src/parse'
import { buildDocx } from './helpers/build-docx'
const boxPara = (zOrder: number, text: string, behindDoc = false): string =>
buildAnchoredTextboxParagraphXml({
anchor: 'paragraph',
xEmu: 91440,
yEmu: 12700,
widthEmu: 914400,
heightEmu: 914400,
fillHex: '1A1A2E',
zOrder,
behindDoc,
id: 10 + zOrder,
paragraphs: [{ runs: [{ text }] }],
})
const parseBoxes = async (bodyXml: string) => {
const parsed = await parseDocx(await buildDocx({ bodyXml }))
return parsed.blocks.flatMap((b) => b.textboxes ?? [])
}
describe('floating shape z-order (wp:anchor relativeHeight)', () => {
it('keeps Word-style compact ranks raw', async () => {
const boxes = await parseBoxes(boxPara(3, 'front') + boxPara(1, 'back'))
expect(boxes.map((b) => b.z)).toEqual([3, 1])
})
it('rank 0 (the base value) stays unset', async () => {
const boxes = await parseBoxes(boxPara(0, 'base'))
expect(boxes[0].z).toBeUndefined()
})
it('re-ranks wild producer values by document z, stable by order', async () => {
// LibreOffice-style raw relativeHeight (1, 3, 2) decodes to huge negatives
const xml = (boxPara(0, 'a') + boxPara(0, 'b') + boxPara(0, 'c'))
.replace('relativeHeight="251658240"', 'relativeHeight="3"')
.replace('relativeHeight="251658240"', 'relativeHeight="1"')
.replace('relativeHeight="251658240"', 'relativeHeight="2"')
const boxes = await parseBoxes(xml)
const [a, b, c] = boxes.map((x) => x.z!)
// compact ranks (the raw deltas are ~-251658237), ordered by decoded value
expect(boxes.every((x) => Math.abs(x.z!) < 10000)).toBe(true)
expect(b).toBeLessThan(c)
expect(c).toBeLessThan(a)
})
it('behind flag and z coexist', async () => {
const boxes = await parseBoxes(boxPara(5, 'bg', true))
expect(boxes[0].behind).toBe(true)
expect(boxes[0].z).toBe(5)
})
})
@@ -0,0 +1,511 @@
import { describe, expect, it } from 'vitest'
import { mergePPrFormat, parseDocx } from '../src/index'
import { buildDocx } from './helpers/build-docx'
/**
* Character-unit indents (w:firstLineChars / w:hangingChars / w:leftChars /
* w:rightChars). Every expectation below is a Word for Mac measurement
* (probe 2026-09-02, docs-fidelity word-truths.md): first-line/hanging
* units follow the first text run, left/right units follow the Normal style,
* the character form supersedes the twips twin, zero means "absolute".
*/
const NS = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
/** docDefaults 10.5pt (the usual Chinese Normal), plus styles carrying character indents */
function stylesXml(normalRPr = ''): string {
return (
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles ${NS}>` +
'<w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="21"/><w:szCs w:val="21"/></w:rPr></w:rPrDefault>' +
'<w:pPrDefault><w:pPr/></w:pPrDefault></w:docDefaults>' +
`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/>${normalRPr}</w:style>` +
'<w:style w:type="paragraph" w:styleId="Body16"><w:name w:val="Body16"/><w:basedOn w:val="Normal"/>' +
'<w:pPr><w:ind w:firstLineChars="200"/></w:pPr><w:rPr><w:sz w:val="32"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="Body16Left"><w:name w:val="Body16Left"/><w:basedOn w:val="Normal"/>' +
'<w:pPr><w:ind w:leftChars="200"/></w:pPr><w:rPr><w:sz w:val="32"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="BodyNoSz"><w:name w:val="BodyNoSz"/><w:basedOn w:val="Normal"/>' +
'<w:pPr><w:ind w:firstLineChars="200"/></w:pPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/></w:style>' +
'</w:styles>'
)
}
function run(text: string, sz?: number, extraRPr = ''): string {
const rPr = (sz ? `<w:sz w:val="${sz}"/><w:szCs w:val="${sz}"/>` : '') + extraRPr
return `<w:r>${rPr ? `<w:rPr>${rPr}</w:rPr>` : ''}<w:t xml:space="preserve">${text}</w:t></w:r>`
}
function para(pPr: string, runs: string): string {
return `<w:p><w:pPr>${pPr}</w:pPr>${runs}</w:p>`
}
/** parsed paragraph formats, without the `charIndents` marker (asserted separately) */
async function formats(bodyXml: string, styles = stylesXml()) {
const doc = await parseDocx(await buildDocx({ bodyXml, stylesXml: styles }))
return doc.blocks.map((b) => {
if (!b.format) return b.format
const { charIndents: _chars, ...rest } = b.format
return Object.keys(rest).length > 0 ? rest : undefined
})
}
describe('character-unit indents: first line and hanging follow the first text run', () => {
it('firstLineChars scales with the run size (2 chars of 16pt = 640 twips, of 12pt = 480)', async () => {
const f = await formats(
para('<w:ind w:firstLineChars="200"/>', run('body', 32)) +
para('<w:ind w:firstLineChars="200"/>', run('body', 24)) +
// Latin text: the unit is the font size, not a glyph width
para('<w:ind w:firstLineChars="200"/>', run('Latin text', 24)) +
// no run size: docDefaults 10.5pt
para('<w:ind w:firstLineChars="200"/>', run('body')),
)
expect(f[0]).toEqual({ indentFirstLine: 640 })
expect(f[1]).toEqual({ indentFirstLine: 480 })
expect(f[2]).toEqual({ indentFirstLine: 480 })
expect(f[3]).toEqual({ indentFirstLine: 420 })
})
it('the character form supersedes a stale twips twin', async () => {
const f = await formats(
para('<w:ind w:firstLineChars="200" w:firstLine="100"/>', run('body', 24)),
)
expect(f[0]).toEqual({ indentFirstLine: 480 })
})
it('uses the first text run, not the largest run or the paragraph mark', async () => {
const f = await formats(
para('<w:ind w:firstLineChars="200"/>', run('small', 20) + run('LARGE TEXT', 40)) +
para('<w:ind w:firstLineChars="200"/>', run('LARGE', 40) + run('small text', 20)) +
// 20pt paragraph mark, 10pt runs: the mark does not count
para('<w:ind w:firstLineChars="200"/><w:rPr><w:sz w:val="40"/></w:rPr>', run('body', 20)) +
// an empty first run does not count either
para('<w:ind w:firstLineChars="200"/>', run('', 20) + run('body', 40)),
)
expect(f[0]).toEqual({ indentFirstLine: 400 })
expect(f[1]).toEqual({ indentFirstLine: 800 })
expect(f[2]).toEqual({ indentFirstLine: 400 })
expect(f[3]).toEqual({ indentFirstLine: 800 })
})
it('adds the first run letter spacing to the unit (12pt + 5pt spacing -> 17pt characters)', async () => {
const f = await formats(
para('<w:ind w:firstLineChars="200"/>', run('body', 24, '<w:spacing w:val="100"/>')),
)
expect(f[0]).toEqual({ indentFirstLine: 680 })
})
it('a run-less paragraph sizes the unit by its paragraph mark', async () => {
const f = await formats(
para('<w:ind w:firstLineChars="200"/><w:rPr><w:sz w:val="32"/></w:rPr>', ''),
)
expect(f[0]).toMatchObject({ indentFirstLine: 640 })
})
})
describe('character-unit indents: left and right follow the Normal style', () => {
it('leftChars uses the default paragraph size even for 12pt text (2 chars = 420 twips)', async () => {
const f = await formats(
para('<w:ind w:leftChars="200"/>', run('body', 24)) +
// the twips twin is ignored
para('<w:ind w:leftChars="200" w:left="1440"/>', run('body', 24)) +
// strict attribute names
para('<w:ind w:startChars="200"/>', run('body', 24)) +
// negative left is legal
para('<w:ind w:leftChars="-200"/>', run('body', 24)) +
// run letter spacing does not affect the Normal unit
para('<w:ind w:leftChars="200"/>', run('body', 24, '<w:spacing w:val="100"/>')),
)
expect(f[0]).toEqual({ indentLeft: 420 })
expect(f[1]).toEqual({ indentLeft: 420 })
expect(f[2]).toEqual({ indentLeft: 420 })
expect(f[3]).toEqual({ indentLeft: -420 })
expect(f[4]).toEqual({ indentLeft: 420 })
})
it('a Normal style size outranks docDefaults for the left unit (14pt Normal -> 560)', async () => {
const f = await formats(
para('<w:ind w:leftChars="200"/>', run('body', 24)) +
para('<w:ind w:firstLineChars="200"/>', run('body')),
stylesXml('<w:rPr><w:sz w:val="28"/></w:rPr>'),
)
expect(f[0]).toEqual({ indentLeft: 560 })
// a run without its own size inherits Normal's 14pt for the first-line unit too
expect(f[1]).toEqual({ indentFirstLine: 560 })
})
it('rightChars follows Normal and beats the twips twin', async () => {
const f = await formats(
para('<w:jc w:val="right"/><w:ind w:rightChars="200" w:right="1440"/>', run('body', 24)),
)
expect(f[0]).toEqual({ align: 'right', indentRight: 420 })
})
})
describe('character-unit indents: hanging semantics and mixed units', () => {
it('leftChars is the first-line position; body lines sit the hanging further in', async () => {
const f = await formats(
// leftChars=4 (Normal 10.5pt -> 840) + hangingChars=2 (12pt -> 480): first 840, body 1320
para('<w:ind w:leftChars="400" w:hangingChars="200"/>', run('body', 24)) +
// hangingChars beats a firstLineChars next to it
para(
'<w:ind w:leftChars="400" w:hangingChars="200" w:firstLineChars="300"/>',
run('body', 24),
) +
// twips hanging next to leftChars: same character-mode semantics
para('<w:ind w:leftChars="400" w:hanging="240"/>', run('body', 24)) +
// hangingChars alone: first line at the margin, body 2 chars in
para('<w:ind w:hangingChars="200"/>', run('body', 24)) +
// hangingChars drops a twips w:left (Word ignores it)
para('<w:ind w:left="720" w:hangingChars="200"/>', run('body', 24)) +
// ... even next to an explicit leftChars="0"
para('<w:ind w:left="720" w:leftChars="0" w:hangingChars="200"/>', run('body', 24)) +
// leftChars + firstLineChars: plain first-line indent from the character left
para('<w:ind w:leftChars="400" w:firstLineChars="200"/>', run('body', 24)),
)
expect(f[0]).toEqual({ indentLeft: 1320, indentFirstLine: -480 })
expect(f[1]).toEqual({ indentLeft: 1320, indentFirstLine: -480 })
expect(f[2]).toEqual({ indentLeft: 1080, indentFirstLine: -240 })
expect(f[3]).toEqual({ indentLeft: 480, indentFirstLine: -480 })
expect(f[4]).toEqual({ indentLeft: 480, indentFirstLine: -480 })
expect(f[5]).toEqual({ indentLeft: 480, indentFirstLine: -480 })
expect(f[6]).toEqual({ indentLeft: 840, indentFirstLine: 480 })
})
it('firstLineChars alone keeps a twips w:left as the body indent and beats a twips hanging', async () => {
const f = await formats(
para('<w:ind w:left="720" w:firstLineChars="200"/>', run('body', 24)) +
para('<w:ind w:left="720" w:firstLineChars="200" w:firstLine="480"/>', run('body', 24)) +
para('<w:ind w:left="720" w:hanging="240" w:firstLineChars="200"/>', run('body', 24)),
)
expect(f[0]).toEqual({ indentLeft: 720, indentFirstLine: 480 })
expect(f[1]).toEqual({ indentLeft: 720, indentFirstLine: 480 })
expect(f[2]).toEqual({ indentLeft: 720, indentFirstLine: 480 })
})
it('a zero character value means "absolute": the twips attribute stays in force', async () => {
const f = await formats(
para('<w:ind w:firstLineChars="0" w:firstLine="480"/>', run('body', 24)) +
para('<w:ind w:leftChars="0" w:left="720"/>', run('body', 24)) +
para('<w:ind w:left="720" w:hanging="240" w:hangingChars="0"/>', run('body', 24)) +
// twips-only paragraphs are untouched
para('<w:ind w:hanging="240"/>', run('body', 24)),
)
expect(f[0]).toEqual({ indentFirstLine: 480 })
expect(f[1]).toEqual({ indentLeft: 720 })
expect(f[2]).toEqual({ indentLeft: 720, indentFirstLine: -240 })
expect(f[3]).toEqual({ indentFirstLine: -240 })
})
})
describe('character-unit indents: document grid and styles', () => {
it('a linesAndChars grid widens both units by charSpace/4096 pt (snapToGrid off included)', async () => {
const grid = '<w:docGrid w:type="linesAndChars" w:linePitch="312" w:charSpace="16384"/>'
const f = await formats(
para('<w:ind w:firstLineChars="200"/>', run('body', 24)) +
para('<w:ind w:leftChars="200"/>', run('body', 24)) +
para('<w:snapToGrid w:val="0"/><w:ind w:firstLineChars="200"/>', run('body', 24)) +
`<w:p><w:pPr><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>${grid}</w:sectPr></w:pPr></w:p>` +
// second section, plain lines grid: no delta
para('<w:ind w:firstLineChars="200"/>', run('body', 24)),
)
// 12pt + 4pt = 16pt characters -> 640; Normal 10.5 + 4 = 14.5pt -> 580
expect(f[0]).toEqual({ indentFirstLine: 640 })
expect(f[1]).toEqual({ indentLeft: 580 })
expect(f[2]).toMatchObject({ indentFirstLine: 640 })
expect(f[4]).toEqual({ indentFirstLine: 480 })
})
it('a style firstLineChars resolves per paragraph against the paragraph text', async () => {
const f = await formats(
// style size 16pt, runs unsized: 640
para('<w:pStyle w:val="Body16"/>', run('body')) +
// runs 12pt directly: 480
para('<w:pStyle w:val="Body16"/>', run('body', 24)) +
// no size anywhere: docDefaults 10.5pt -> 420
para('<w:pStyle w:val="BodyNoSz"/>', run('body')) +
// a style leftChars still follows Normal, not the style's own 16pt
para('<w:pStyle w:val="Body16Left"/>', run('body')) +
// style firstLineChars + direct leftChars combine
para('<w:pStyle w:val="Body16"/><w:ind w:leftChars="200"/>', run('body')) +
// a direct twips special indent does NOT cancel the style's character one
// (Word: separate properties; the character form keeps superseding)
para('<w:pStyle w:val="Body16"/><w:ind w:firstLine="0"/>', run('body')) +
para('<w:pStyle w:val="Body16"/><w:ind w:hanging="240"/>', run('body')) +
// only a *Chars attribute does — the explicit zero Word writes for pt indents
para(
'<w:pStyle w:val="Body16"/><w:ind w:firstLineChars="0" w:firstLine="420"/>',
run('body'),
) +
para('<w:pStyle w:val="Body16"/><w:ind w:hangingChars="100"/>', run('body', 24)),
)
expect(f[0]).toEqual({ indentFirstLine: 640 })
expect(f[1]).toEqual({ indentFirstLine: 480 })
expect(f[2]).toEqual({ indentFirstLine: 420 })
expect(f[3]).toEqual({ indentLeft: 420 })
expect(f[4]).toEqual({ indentLeft: 420, indentFirstLine: 640 })
expect(f[5]).toEqual({ indentFirstLine: 640 })
expect(f[6]).toEqual({ indentFirstLine: 640 })
expect(f[7]).toEqual({ indentFirstLine: 420 })
expect(f[8]).toEqual({ indentLeft: 240, indentFirstLine: -240 })
})
it('a direct twips w:left / w:hanging leaves a style character indent in force', async () => {
// Word for Mac probe 2026-09-02: PC = firstLineChars 200, PL = leftChars 200
const f = await formats(
// 12pt text: chars 24pt first line; twips left 36pt body -> 60 / 36
para('<w:pStyle w:val="Body16"/><w:ind w:left="720" w:hanging="240"/>', run('body', 24)) +
para('<w:pStyle w:val="Body16"/><w:ind w:left="720"/>', run('body', 24)) +
// style leftChars: direct twips w:left is ignored (character-mode left edge)
para('<w:pStyle w:val="Body16Left"/><w:ind w:left="1440"/>', run('body', 24)) +
para(
'<w:pStyle w:val="Body16Left"/><w:ind w:leftChars="0" w:left="1440"/>',
run('body', 24),
),
)
expect(f[0]).toEqual({ indentLeft: 720, indentFirstLine: 480 })
expect(f[1]).toEqual({ indentLeft: 720, indentFirstLine: 480 })
expect(f[2]).toEqual({ indentLeft: 420 })
expect(f[3]).toEqual({ indentLeft: 1440 })
})
it('a derived style keeps the parent character indent unless it sets the *Chars attribute', async () => {
// Word for Mac probe 2026-09-02, 12pt text, Normal 10.5pt
const chain =
'<w:style w:type="paragraph" w:styleId="PC"><w:name w:val="PC"/><w:basedOn w:val="Normal"/><w:pPr><w:ind w:firstLineChars="200"/></w:pPr></w:style>' +
// twips-only child: parent chars survive (24pt, not 21)
'<w:style w:type="paragraph" w:styleId="CT"><w:name w:val="CT"/><w:basedOn w:val="PC"/><w:pPr><w:ind w:firstLine="420"/></w:pPr></w:style>' +
// explicit zero (what Word writes for a pt indent): absolute, 21pt
'<w:style w:type="paragraph" w:styleId="CZ"><w:name w:val="CZ"/><w:basedOn w:val="PC"/><w:pPr><w:ind w:firstLineChars="0" w:firstLine="420"/></w:pPr></w:style>' +
// twips hanging child: the parent's firstLineChars still wins (60 / 36)
'<w:style w:type="paragraph" w:styleId="CH"><w:name w:val="CH"/><w:basedOn w:val="PC"/><w:pPr><w:ind w:left="720" w:hanging="240"/></w:pPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="CC"><w:name w:val="CC"/><w:basedOn w:val="PC"/><w:pPr><w:ind w:firstLineChars="300"/></w:pPr></w:style>' +
// two levels down, through a twips-only intermediate style
'<w:style w:type="paragraph" w:styleId="GC"><w:name w:val="GC"/><w:basedOn w:val="CT"/><w:pPr><w:ind w:left="720"/></w:pPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="PL"><w:name w:val="PL"/><w:basedOn w:val="Normal"/><w:pPr><w:ind w:leftChars="200"/></w:pPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="CL"><w:name w:val="CL"/><w:basedOn w:val="PL"/><w:pPr><w:ind w:left="1440"/></w:pPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="CLZ"><w:name w:val="CLZ"/><w:basedOn w:val="PL"/><w:pPr><w:ind w:leftChars="0" w:left="1440"/></w:pPr></w:style>'
const f = await formats(
para('<w:pStyle w:val="CT"/>', run('body', 24)) +
para('<w:pStyle w:val="CZ"/>', run('body', 24)) +
para('<w:pStyle w:val="CH"/>', run('body', 24)) +
para('<w:pStyle w:val="CC"/>', run('body', 24)) +
para('<w:pStyle w:val="GC"/>', run('body', 24)) +
para('<w:pStyle w:val="CL"/>', run('body', 24)) +
para('<w:pStyle w:val="CLZ"/>', run('body', 24)),
stylesXml().replace('</w:styles>', chain + '</w:styles>'),
)
expect(f[0]).toEqual({ indentFirstLine: 480 })
// the style's twips indent renders through the style CSS, nothing to fold
expect(f[1]).toBeUndefined()
expect(f[2]).toEqual({ indentFirstLine: 480 })
expect(f[3]).toEqual({ indentFirstLine: 720 })
expect(f[4]).toEqual({ indentFirstLine: 480 })
expect(f[5]).toEqual({ indentLeft: 420 })
expect(f[6]).toBeUndefined()
})
it('a Normal-style firstLineChars reaches unstyled paragraphs but not list items', async () => {
const styles = stylesXml().replace(
'<w:name w:val="Normal"/>',
'<w:name w:val="Normal"/><w:pPr><w:ind w:firstLineChars="200"/></w:pPr>',
)
const doc = await parseDocx(
await buildDocx({
bodyXml:
para('', run('body', 24)) +
para('<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>', run('item', 24)),
stylesXml: styles,
withNumbering: true,
}),
)
expect(doc.blocks[0].format).toEqual({
indentFirstLine: 480,
charIndents: { firstLine: 200 },
})
expect(doc.blocks[1].type).toBe('listItem')
expect(doc.blocks[1].format).toBeUndefined()
})
it('table cell paragraphs resolve their character indents too', async () => {
const doc = await parseDocx(
await buildDocx({
bodyXml:
'<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
para('<w:ind w:firstLineChars="200"/>', run('cell', 24)) +
'</w:tc></w:tr></w:tbl>',
stylesXml: stylesXml(),
}),
)
const table = doc.blocks[0]
expect(table.type).toBe('table')
expect(table.table!.rows[0][0].richParas![0].indentFirstLine).toBe(480)
})
it('the section grid pitch reaches table-cell and textbox paragraphs too', async () => {
// Word for Mac probe 2026-09-02: under linesAndChars charSpace=16384 a
// 12pt firstLineChars="200" lays at 32pt in the body, in a cell and in a textbox
const cellPara = para('<w:ind w:firstLineChars="200"/>', run('cell', 24))
const tbl =
'<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>' +
cellPara +
'</w:tc></w:tr></w:tbl>'
const txbx =
'<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="3000000" cy="600000"/><wp:wrapSquare wrapText="bothSides"/><wp:docPr id="1" name="Box 1"/>' +
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:cNvSpPr txBox="1"/>' +
'<wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="3000000" cy="600000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></wps:spPr>' +
'<wps:txbx><w:txbxContent>' +
para('<w:ind w:firstLineChars="200"/>', run('box', 24)) +
'</w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp>' +
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>'
const gridSect =
'<w:p><w:pPr><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>' +
'<w:docGrid w:type="linesAndChars" w:linePitch="312" w:charSpace="16384"/></w:sectPr></w:pPr></w:p>'
const doc = await parseDocx(
await buildDocx({
// section 1 carries the character grid, section 2 (the default sectPr) does not
bodyXml: tbl + txbx + gridSect + tbl + txbx,
stylesXml: stylesXml(),
}),
)
const cellIndent = (b: (typeof doc.blocks)[number]) =>
b.table!.rows[0][0].richParas![0].indentFirstLine
const boxIndent = (b: (typeof doc.blocks)[number]) => b.textboxes![0].paras[0].indentFirstLine
expect(cellIndent(doc.blocks[0])).toBe(640)
expect(boxIndent(doc.blocks[1])).toBe(640)
expect(cellIndent(doc.blocks[3])).toBe(480)
expect(boxIndent(doc.blocks[4])).toBe(480)
})
it('a Normal-style firstLineChars reaches pPr-less textbox paragraphs', async () => {
const styles = stylesXml().replace(
'<w:name w:val="Normal"/>',
'<w:name w:val="Normal"/><w:pPr><w:ind w:firstLineChars="200"/></w:pPr>',
)
const txbx =
'<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="3000000" cy="600000"/><wp:wrapSquare wrapText="bothSides"/><wp:docPr id="1" name="Box 1"/>' +
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:cNvSpPr txBox="1"/>' +
'<wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="3000000" cy="600000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></wps:spPr>' +
// no w:pPr at all on the box paragraph
`<wps:txbx><w:txbxContent><w:p>${run('box', 24)}</w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp>` +
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml: txbx, stylesXml: styles }))
expect(doc.blocks[0].textboxes![0].paras[0].indentFirstLine).toBe(480)
})
})
describe('character-unit indents: saving', () => {
it('an unrelated format edit keeps the raw w:ind bytes when the indent model is unchanged', async () => {
const bytes = await buildDocx({
bodyXml: para('<w:ind w:firstLineChars="200"/>', run('body', 24)),
stylesXml: stylesXml(),
})
const doc = await parseDocx(bytes)
const block = doc.blocks[0]
// the marker tells the save path which character indents an edit has to cancel
expect(block.format).toEqual({ indentFirstLine: 480, charIndents: { firstLine: 200 } })
// the editor centers the paragraph: only w:jc is rebuilt, w:ind stays character-based
const merged = mergePPrFormat(
block.rawPPr!,
{ indentFirstLine: 480, align: 'center' },
block.format,
)
expect(merged).toContain('<w:ind w:firstLineChars="200"/>')
expect(merged).toContain('<w:jc w:val="center"/>')
expect(merged).not.toContain('w:firstLine=')
// a real indent edit rebuilds w:ind in twips and cancels the character unit
// the way Word writes pt indents, so the user's value wins on reload
const edited = mergePPrFormat(block.rawPPr!, { indentFirstLine: 720 }, block.format)
expect(edited).toContain('<w:ind w:firstLine="720" w:firstLineChars="0"/>')
})
it('an indent edit under a style character indent writes the cancel Word writes', async () => {
// Word for Mac probe 2026-09-02: a direct twips w:firstLine does not beat a style
// firstLineChars; only `w:firstLineChars="0"` does. Without it the edit is
// superseded by the style on reload — in Word and in this parser.
const styles = stylesXml().replace(
'<w:name w:val="Normal"/>',
'<w:name w:val="Normal"/><w:pPr><w:ind w:firstLineChars="200"/></w:pPr>',
)
const bytes = await buildDocx({
bodyXml:
// style indent only, raw pPr without w:ind
para('<w:jc w:val="both"/>', run('body', 24)) +
// style indent, direct twips left
para('<w:ind w:left="720"/>', run('body', 24)) +
// direct character left + hanging
para('<w:ind w:leftChars="400" w:hangingChars="200"/>', run('body', 24)),
stylesXml: styles,
})
const doc = await parseDocx(bytes)
const [styled, withLeft, hanging] = doc.blocks
expect(styled.format).toEqual({
align: 'justify',
indentFirstLine: 480,
charIndents: { firstLine: 200 },
})
// first-line indent changed: w:ind is added with the cancel, the rest of the pPr kept
const changed = mergePPrFormat(
styled.rawPPr!,
{ align: 'justify', indentFirstLine: 720 },
styled.format,
)
expect(changed).toBe(
'<w:pPr><w:ind w:firstLine="720" w:firstLineChars="0"/><w:jc w:val="both"/></w:pPr>',
)
// first-line indent removed: nothing but the cancel is left to write
const removed = mergePPrFormat(styled.rawPPr!, { align: 'justify' }, styled.format)
expect(removed).toBe('<w:pPr><w:ind w:firstLineChars="0"/><w:jc w:val="both"/></w:pPr>')
// unrelated edit: no cancel, the paragraph stays character-indented
const centered = mergePPrFormat(
styled.rawPPr!,
{ indentFirstLine: 480, align: 'center' },
styled.format,
)
expect(centered).toBe('<w:pPr><w:jc w:val="center"/></w:pPr>')
// pPr-less paragraph (rawPPr ''): the rebuilt pPr carries the cancel too
expect(mergePPrFormat('', { indentFirstLine: 720 }, styled.format)).toBe(
'<w:pPr><w:ind w:firstLine="720" w:firstLineChars="0"/></w:pPr>',
)
expect(withLeft.format).toEqual({
indentLeft: 720,
indentFirstLine: 480,
charIndents: { firstLine: 200 },
})
expect(
mergePPrFormat(withLeft.rawPPr!, { indentLeft: 1440, indentFirstLine: 480 }, withLeft.format),
).toBe('<w:pPr><w:ind w:left="1440" w:firstLine="480" w:firstLineChars="0"/></w:pPr>')
expect(hanging.format).toEqual({
indentLeft: 1320,
indentFirstLine: -480,
charIndents: { left: 400, hanging: 200 },
})
expect(mergePPrFormat(hanging.rawPPr!, { indentLeft: 720 }, hanging.format)).toBe(
'<w:pPr><w:ind w:left="720" w:leftChars="0" w:hangingChars="0"/></w:pPr>',
)
// round trip: the saved paragraphs re-parse to the edited values, not the style's
const saved = await parseDocx(
await buildDocx({
bodyXml:
`<w:p>${changed}${run('body', 24)}</w:p>` +
`<w:p>${removed}${run('body', 24)}</w:p>` +
`<w:p>${mergePPrFormat(hanging.rawPPr!, { indentLeft: 720 }, hanging.format)}${run('body', 24)}</w:p>`,
stylesXml: styles,
}),
)
expect(saved.blocks[0].format).toEqual({ indentFirstLine: 720, align: 'justify' })
expect(saved.blocks[1].format).toEqual({ align: 'justify' })
expect(saved.blocks[2].format).toEqual({ indentLeft: 720 })
})
})
@@ -13,12 +13,12 @@ const THEME: ThemeColors = {
accent6: 'F79646',
}
const chartSpace = (inner: string, pre = '') =>
const chartSpace = (inner: string, pre = '', post = '') =>
'<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" ' +
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
`${pre}<c:chart><c:plotArea><c:layout/>${inner}</c:plotArea></c:chart></c:chartSpace>`
`${pre}<c:chart><c:plotArea><c:layout/>${inner}</c:plotArea>${post}</c:chart></c:chartSpace>`
const numCache = (tag: string, values: (number | string)[], fmt = 'General') =>
`<c:${tag}><c:numRef><c:f>S!$A$1</c:f><c:numCache><c:formatCode>${fmt}</c:formatCode>` +
@@ -166,6 +166,45 @@ describe('parseChartPartXml scatter and bubble', () => {
})
})
describe('parseChartPartXml doughnut hole and legend position', () => {
const pieSer =
`<c:ser><c:idx val="0"/><c:order val="0"/>${strCache('tx', ['S1'])}` +
`${strCache('cat', ['A', 'B'])}${numCache('val', [67, 33])}</c:ser>`
const doughnut = (hole: string) =>
chartSpace(`<c:doughnutChart><c:varyColors val="1"/>${pieSer}${hole}</c:doughnutChart>`)
it('reads doughnut charts as pie carrying the hole size', () => {
const display = parseChartPartXml(doughnut('<c:holeSize val="65"/>'), 'p')!
expect(display.kind).toBe('pie')
expect(display.holePct).toBe(65)
})
it('defaults the hole to 50% when c:holeSize is absent', () => {
expect(parseChartPartXml(doughnut(''), 'p')!.holePct).toBe(50)
})
it('leaves plain pies without a hole', () => {
const xml = chartSpace(`<c:pieChart><c:varyColors val="1"/>${pieSer}</c:pieChart>`)
expect(parseChartPartXml(xml, 'p')!.holePct).toBeUndefined()
})
it('reads the legend position, defaulting an empty c:legend to right', () => {
const pie = (legend: string) =>
chartSpace(`<c:pieChart><c:varyColors val="1"/>${pieSer}</c:pieChart>`, '', legend)
expect(
parseChartPartXml(
pie('<c:legend><c:legendPos val="r"/><c:overlay val="0"/></c:legend>'),
'p',
)!.legendPos,
).toBe('r')
expect(
parseChartPartXml(pie('<c:legend><c:legendPos val="b"/></c:legend>'), 'p')!.legendPos,
).toBe('b')
expect(parseChartPartXml(pie('<c:legend/>'), 'p')!.legendPos).toBe('r')
expect(parseChartPartXml(pie(''), 'p')!.legendPos).toBeUndefined()
})
})
describe('parseChartexPartXml leniency', () => {
it('parses a waterfall whose cx:chartData was renamed (unknown-element corpus)', () => {
const xml =
+8 -2
View File
@@ -35,7 +35,10 @@ describe('metafileToDataUrl routing', () => {
'data:image/png;base64,EMFPNG',
)
}
expect(convertEmfToDataUrl).toHaveBeenLastCalledWith(expect.any(ArrayBuffer), { dpiScale: 2 })
expect(convertEmfToDataUrl).toHaveBeenLastCalledWith(
expect.any(ArrayBuffer),
expect.objectContaining({ dpiScale: 2 }),
)
})
it('routes wmf mimes to convertWmfToDataUrl', async () => {
@@ -44,7 +47,10 @@ describe('metafileToDataUrl routing', () => {
'data:image/png;base64,WMFPNG',
)
}
expect(convertWmfToDataUrl).toHaveBeenLastCalledWith(expect.any(ArrayBuffer), { dpiScale: 2 })
expect(convertWmfToDataUrl).toHaveBeenLastCalledWith(
expect.any(ArrayBuffer),
expect.objectContaining({ dpiScale: 2 }),
)
})
it('routes by content signature when it contradicts the mime', async () => {
@@ -142,6 +142,13 @@ describe('empty EA slot resolution priority', () => {
themePart(HANG_SCRIPT),
])
expect(doc.docDefaults?.eastAsiaFont).toBe('SimSun')
expect(doc.docDefaults?.eaFromLang).toBe(true)
})
it('a literal declared EA face is not flagged as a lang backfill', async () => {
const doc = await withDocDefaults('<w:rFonts w:eastAsia="Noto Sans CJK KR"/>', [])
expect(doc.docDefaults?.eastAsiaFont).toBe('Noto Sans CJK KR')
expect(doc.docDefaults?.eaFromLang).toBeUndefined()
})
it('themeFontLang alone must not invent an EA face when w:lang would not backfill', async () => {
@@ -179,6 +179,113 @@ describe('header/footer images (display-only Logo)', () => {
expect(doc.headerImages).toHaveLength(1)
expect(doc.headerImages![0].dataUrl.startsWith('data:image/png;base64,')).toBe(true)
})
it('AlternateContent Fallback re-emitting the Choice picture parses once (prod_043)', async () => {
// anchored drawing in the Choice, inline copy of the same logo in the Fallback;
// the AC open tag carries attributes (the engine's own writer inlines xmlns:mc)
const drawingWith = (inner: string) =>
`<w:drawing>${inner}<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">` +
'<pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic>' +
`</a:graphicData></a:graphic>${inner.startsWith('<wp:anchor') ? '</wp:anchor>' : '</wp:inline>'}</w:drawing>`
const anchor =
'<wp:anchor behindDoc="0" distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" locked="0" layoutInCell="1" allowOverlap="1">' +
'<wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="margin"><wp:posOffset>0</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV>' +
'<wp:extent cx="381000" cy="190500"/><wp:wrapNone/><wp:docPr id="2" name="Logo"/>'
const inline =
'<wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="381000" cy="190500"/><wp:docPr id="3" name="Logo"/>'
const headerXml = HEADER_XML.replace(
/<w:p><w:r><w:drawing>[\s\S]*?<\/w:drawing><\/w:r><\/w:p>/,
'<w:p><w:r>' +
'<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">' +
`<mc:Choice Requires="wps">${drawingWith(anchor)}</mc:Choice>` +
`<mc:Fallback>${drawingWith(inline)}</mc:Fallback>` +
'</mc:AlternateContent>' +
'</w:r></w:p>',
)
const doc = await parseDocx(await buildHeaderLogoDocx(headerXml))
expect(doc.headerImages).toHaveLength(1)
// when the Choice yields nothing (unresolvable media), the Fallback still counts
const brokenChoice = headerXml.replace(
/<mc:Choice Requires="wps">[\s\S]*?<\/mc:Choice>/,
`<mc:Choice Requires="wps">${drawingWith(anchor).replace('rId1', 'rId9')}</mc:Choice>`,
)
const doc2 = await parseDocx(await buildHeaderLogoDocx(brokenChoice))
expect(doc2.headerImages).toHaveLength(1)
})
it('VML picture watermark parses when w:pict carries attributes (prod_091)', async () => {
const headerXml =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"' +
' xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"' +
' xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml">' +
'<w:p><w:r><w:pict w14:anchorId="7C49EC32">' +
'<v:shape id="WordPictureWatermark1" type="#_x0000_t75" style="position:absolute;' +
'margin-left:0;margin-top:0;width:480pt;height:360pt;z-index:-251655168;' +
'mso-position-horizontal:center;mso-position-vertical:center">' +
'<v:imagedata r:id="rId1" o:title="logo"/></v:shape>' +
'</w:pict></w:r></w:p></w:hdr>'
const doc = await parseDocx(await buildHeaderLogoDocx(headerXml))
expect(doc.headerImages).toHaveLength(1)
const img = doc.headerImages![0]
expect(img.dataUrl.startsWith('data:image/png;base64,')).toBe(true)
expect(img.floating).toBe(true)
expect(img.behind).toBe(true)
expect(img.posH).toBe('center')
expect(img.posV).toBe('center')
expect(img.widthPx).toBe(640)
expect(img.heightPx).toBe(480)
})
it('textless custGeom shape group renders as one SVG float image (prod_044 ornaments)', async () => {
const headerXml =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"' +
' xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"' +
' xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"' +
' xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"' +
' xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">' +
'<w:p><w:r><w:drawing><wp:anchor behindDoc="1">' +
'<wp:simplePos x="0" y="0"/>' +
'<wp:positionH relativeFrom="page"><wp:posOffset>952500</wp:posOffset></wp:positionH>' +
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>-190500</wp:posOffset></wp:positionV>' +
'<wp:extent cx="190500" cy="190500"/><wp:wrapNone/>' +
'<a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup">' +
'<wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr bwMode="auto"><a:xfrm>' +
'<a:off x="0" y="0"/><a:ext cx="190500" cy="190500"/>' +
'<a:chOff x="0" y="0"/><a:chExt cx="381000" cy="381000"/>' +
'</a:xfrm></wpg:grpSpPr>' +
'<wps:wsp><wps:cNvPr id="2" name="Graphic 1"/><wps:cNvSpPr/><wps:spPr>' +
'<a:xfrm><a:off x="0" y="0"/><a:ext cx="381000" cy="381000"/></a:xfrm>' +
'<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="381000" h="381000">' +
'<a:moveTo><a:pt x="0" y="0"/></a:moveTo>' +
'<a:lnTo><a:pt x="381000" y="0"/></a:lnTo>' +
'<a:lnTo><a:pt x="190500" y="381000"/></a:lnTo>' +
'<a:close/></a:path></a:pathLst></a:custGeom>' +
'<a:solidFill><a:srgbClr val="20093F"/></a:solidFill>' +
'</wps:spPr><wps:bodyPr/></wps:wsp>' +
'</wpg:wgp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p></w:hdr>'
const doc = await parseDocx(await buildHeaderLogoDocx(headerXml))
expect(doc.headerImages).toHaveLength(1)
const img = doc.headerImages![0]
expect(img.floating).toBe(true)
expect(img.behind).toBe(true)
expect(img.posXPx).toBe(100)
expect(img.posYPx).toBe(-20)
expect(img.posVRel).toBe('paragraph')
expect(img.widthPx).toBe(20)
expect(img.heightPx).toBe(20)
expect(img.dataUrl.startsWith('data:image/svg+xml,')).toBe(true)
const svg = decodeURIComponent(img.dataUrl.slice('data:image/svg+xml,'.length))
expect(svg).toContain('viewBox="0 0 20 20"')
expect(svg).toContain('fill="#20093F"')
expect(svg).toContain('d="M 0 0 L 20 0 L 10 20 Z"')
})
})
describe('layout-table cell images (header logo in a w:tbl cell)', () => {
@@ -49,6 +49,9 @@ function makeRecordingCtx(canvas: FakeOffscreenCanvas) {
if (prop === 'globalCompositeOperation') {
calls.push({ method: 'set:globalCompositeOperation', args: [value] })
}
if (prop === 'font') {
calls.push({ method: 'set:font', args: [value] })
}
return true
},
})
@@ -275,6 +278,112 @@ describe('EMR_ALPHABLEND (w-icon.emf)', () => {
})
})
/**
* Minimal EMF: header + EXTCREATEFONTINDIRECTW + SELECTOBJECT + EXTTEXTOUTW +
* EOF, with GDI+-style non-zero OutPrecision/Quality/PitchAndFamily bytes in
* the LOGFONTW (the facename-offset regression trigger).
*/
function buildEmfWithText(faceName: string, text: string): ArrayBuffer {
const header = new Uint8Array(88)
const hv = new DataView(header.buffer)
hv.setUint32(0, 1, true) // EMR_HEADER
hv.setUint32(4, 88, true)
hv.setInt32(16, 200, true) // rclBounds right
hv.setInt32(20, 100, true) // rclBounds bottom
hv.setInt32(32, 5292, true) // rclFrame right (.01 mm, matches bounds)
hv.setInt32(36, 2646, true)
hv.setUint32(40, 0x464d4520, true) // ' EMF'
hv.setUint32(44, 0x00010000, true)
hv.setUint32(52, 5, true) // nRecords
hv.setUint16(56, 2, true) // nHandles
hv.setInt32(72, 1920, true) // szlDevice
hv.setInt32(76, 1080, true)
hv.setInt32(80, 508, true) // szlMillimeters
hv.setInt32(84, 286, true)
const font = new Uint8Array(332)
const fv = new DataView(font.buffer)
fv.setUint32(0, 82, true) // EMR_EXTCREATEFONTINDIRECTW
fv.setUint32(4, 332, true)
fv.setUint32(8, 1, true) // ihFont
fv.setInt32(12, -15, true) // lfHeight
fv.setInt32(28, 400, true) // lfWeight
fv.setUint8(35, 0x80) // lfCharSet
fv.setUint8(36, 4) // lfOutPrecision
fv.setUint8(38, 5) // lfQuality
fv.setUint8(39, 0x32) // lfPitchAndFamily
for (let i = 0; i < faceName.length && i < 31; i++) {
fv.setUint16(40 + i * 2, faceName.charCodeAt(i), true)
}
const select = new Uint8Array(12)
const sv = new DataView(select.buffer)
sv.setUint32(0, 37, true) // EMR_SELECTOBJECT
sv.setUint32(4, 12, true)
sv.setUint32(8, 1, true)
const textRec = new Uint8Array(76 + text.length * 2)
const tv = new DataView(textRec.buffer)
tv.setUint32(0, 84, true) // EMR_EXTTEXTOUTW
tv.setUint32(4, textRec.length, true)
tv.setUint32(24, 1, true) // GM_COMPATIBLE
tv.setInt32(36, 10, true) // reference x
tv.setInt32(40, 20, true) // reference y
tv.setUint32(44, text.length, true)
tv.setUint32(48, 76, true) // offString
for (let i = 0; i < text.length; i++) {
tv.setUint16(76 + i * 2, text.charCodeAt(i), true)
}
const eof = new Uint8Array(20)
const ev = new DataView(eof.buffer)
ev.setUint32(0, 14, true) // EMR_EOF
ev.setUint32(4, 20, true)
const parts = [header, font, select, textRec, eof]
const total = parts.reduce((n, p) => n + p.length, 0)
hv.setUint32(48, total, true) // nBytes
const emf = new Uint8Array(total)
let at = 0
for (const p of parts) {
emf.set(p, at)
at += p.length
}
return emf.buffer
}
function fontSets(): string[] {
return calls.filter((c) => c.method === 'set:font').map((c) => c.args[0] as string)
}
describe('EMR_EXTCREATEFONTINDIRECTW facename', () => {
it('reads the LOGFONTW FaceName at +32, past the precision/quality bytes', async () => {
reset()
const result = await convertEmfToDataUrl(buildEmfWithText('Segoe UI', 'Test'), { dpiScale: 2 })
expect(result).toMatch(/^data:image\/png;base64,/)
expect(calls.filter((c) => c.method === 'fillText').map((c) => c.args[0])).toContain('Test')
// regression: read at +28 prefixed the family with the OutPrecision/
// Quality bytes; the invalid CSS ident made the ctx.font assignment fail
// silently in a real canvas, dropping the 30px size with it
expect(fontSets()).toContain('30px "Segoe UI"')
for (const font of fontSets()) {
expect([...font].some((c) => c.charCodeAt(0) < 0x20 || c.charCodeAt(0) === 0x7f)).toBe(false)
}
})
it('strips control chars from a corrupt facename instead of losing the size', async () => {
reset()
await convertEmfToDataUrl(buildEmfWithText('\u0004㈅Meiryo UI', 'Test'), { dpiScale: 2 })
expect(fontSets()).toContain('30px "㈅Meiryo UI"')
})
it('maps localized facenames through the wrapper fontFamilyMap', async () => {
reset()
await metafileToDataUrl(new Uint8Array(buildEmfWithText('游ゴシック', 'Test')), 'image/x-emf')
expect(fontSets()).toContain('30px "Yu Gothic"')
})
})
describe('gzipped metafiles (.emz/.wmz)', () => {
it('accepts emz/wmz mimes', () => {
for (const m of ['image/emz', 'image/x-emz', 'image/wmz', 'image/x-wmz']) {
+14
View File
@@ -284,6 +284,20 @@ describe('rich-text footnote display runs', () => {
expect(notes[1].text).toBe('纯文本')
})
it('flags notes without a self-reference mark run (Word renders those entries numberless)', async () => {
const endnotesXml =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:endnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:endnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:endnote>' +
'<w:endnote w:id="1"><w:p><w:pPr><w:pStyle w:val="ad"/></w:pPr></w:p></w:endnote>' +
'<w:endnote w:id="2"><w:p><w:r><w:t>text without ref mark</w:t></w:r></w:p></w:endnote>' +
'<w:endnote w:id="3"><w:p><w:r><w:endnoteRef/></w:r><w:r><w:t>normal</w:t></w:r></w:p></w:endnote>' +
'</w:endnotes>'
const { parseNotesXml } = await import('../src/notes')
const notes = parseNotesXml(endnotesXml, 'endnote')
expect(notes.map((n) => n.noRefMark)).toEqual([true, true, undefined])
})
it('serializes richParas runs with size/font formatting for fresh notes (P17)', async () => {
const { buildNotesXml, parseNotesXml } = await import('../src/notes')
const xml = buildNotesXml(
@@ -21,6 +21,7 @@ const MODEL: ParaFormat = {
shadingFill: 'EEEEEE',
spaceBefore: 240,
spaceAfter: 120,
indentLeft: 0,
indentFirstLine: 420,
align: 'justify',
}
@@ -31,8 +32,21 @@ describe('mergePPrFormat keeps unedited groups byte-identical', () => {
})
it('model straight from parseDocx round-trips the raw bytes', async () => {
const bytes = await buildDocx({ bodyXml: `<w:p>${RAW}<w:r><w:t>正文</w:t></w:r></w:p>` })
// firstLineChars="200" next to firstLine="420" is Word's output for a 10.5pt
// Normal: the parser resolves the character unit, so the document must carry
// the size the twips twin was computed from
const stylesXml =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="21"/></w:rPr></w:rPrDefault></w:docDefaults>' +
'<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>' +
'</w:styles>'
const bytes = await buildDocx({
bodyXml: `<w:p>${RAW}<w:r><w:t>正文</w:t></w:r></w:p>`,
stylesXml,
})
const doc = await parseDocx(bytes)
expect(doc.blocks[0].format).toMatchObject({ indentLeft: 0, indentFirstLine: 420 })
expect(mergePPrFormat(doc.blocks[0].rawPPr!, doc.blocks[0].format)).toBe(RAW)
})
@@ -88,7 +102,8 @@ describe('mergePPrFormat keeps unedited groups byte-identical', () => {
// Word prefers *Chars over the twips attrs, so a stale firstLineChars would
// override the user's new indent — the rebuilt w:ind must not carry them
const out = mergePPrFormat(RAW, { ...MODEL, indentFirstLine: 640 })
expect(out).toContain('<w:ind w:firstLine="640"/>')
// the explicit w:left="0" survives the rebuild (it cancels numbering/style indents)
expect(out).toContain('<w:ind w:left="0" w:firstLine="640"/>')
expect(out).not.toContain('firstLineChars')
expect(out).not.toContain('leftChars')
expect(out).toContain('w:afterLines="50"')
@@ -560,15 +560,32 @@ describe('pgBorders details', () => {
'</w:pgBorders></w:sectPr>',
)
expect(s.pageBorder).toBe(true)
const side = { val: 'single', widthPt: 2.25, spacePt: 24, color: '1F497D' }
expect(s.pageBorderProps).toEqual({
display: 'firstPage',
offsetFrom: 'page',
spacePt: 24,
widthPt: 2.25,
color: '1F497D',
sides: { top: side, left: side, bottom: side, right: side },
})
})
it('keeps per-side style/width for mixed compound borders', async () => {
const { sectionSettingsFromXml } = await import('../src/section')
const s = sectionSettingsFromXml(
'<w:sectPr><w:pgBorders w:offsetFrom="page">' +
'<w:top w:val="thinThickSmallGap" w:sz="24" w:space="24" w:color="auto"/>' +
'<w:bottom w:val="thickThinSmallGap" w:sz="24" w:space="24" w:color="auto"/>' +
'</w:pgBorders></w:sectPr>',
)
expect(s.pageBorderProps?.sides).toEqual({
top: { val: 'thinThickSmallGap', widthPt: 3, spacePt: 24 },
bottom: { val: 'thickThinSmallGap', widthPt: 3, spacePt: 24 },
})
expect(s.pageBorderProps?.color).toBeUndefined()
})
it('none-only sides leave pageBorderProps unset', async () => {
const { sectionSettingsFromXml } = await import('../src/section')
const s = sectionSettingsFromXml(
@@ -457,4 +457,45 @@ describe('textbox patch addressing', () => {
expect(out).toContain('second')
expect(out.indexOf('second')).toBeGreaterThan(out.indexOf('hello'))
})
const INLINE_PIC =
'<w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0">' +
'<wp:extent cx="259200" cy="244800"/><wp:docPr id="9" name="Checkbox"/>' +
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
'<pic:pic><pic:nvPicPr><pic:cNvPr id="9" name="Checkbox"/><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="0" y="0"/><a:ext cx="259200" cy="244800"/></a:xfrm>' +
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>' +
'</a:graphicData></a:graphic></wp:inline></w:drawing>'
const picParagraphXml = () =>
TEXTBOX_PARAGRAPH.replaceAll(
'<w:t>**Current date:** {Month}</w:t></w:r></w:p>',
`<w:t>**Current date:** {Month}</w:t></w:r><w:r>${INLINE_PIC}</w:r></w:p>`,
)
it('keeps inline pictures inside textbox paragraphs as run images', async () => {
const doc = await parseDocx(await buildDocx({ bodyXml: picParagraphXml(), withImage: true }))
const box = doc.blocks[0].textboxes?.[0]
const img = box?.paras[0].runs.find((r) => r.image)?.image
expect(img?.dataUrl.startsWith('data:image/png')).toBe(true)
expect(img?.xml).toContain('r:embed="rId10"')
expect(img?.widthPx).toBe(27) // 259200 EMU / 9525
})
it('round-trips an inline picture when its textbox paragraph is regenerated', async () => {
const xml = picParagraphXml()
const doc = await parseDocx(await buildDocx({ bodyXml: xml, withImage: true }))
const box = doc.blocks[0].textboxes?.[0]
expect(box?.txbxIndex).toBe(0)
// unchanged commit: paragraph rebuilt from the parsed runs keeps the drawing
const out = patchTextboxParas(xml, {
byIndex: [box!.paras.map((p) => para({ runs: p.runs, align: p.align ?? null }))],
})
expect(out).toContain(INLINE_PIC)
expect(out).toContain('**Current date:** {Month}')
expect(out).toContain('CRITICAL')
// untouched box: original bytes kept verbatim
expect(patchTextboxParas(xml, { byIndex: [undefined] })).toBe(xml)
})
})
+82 -4
View File
@@ -180,13 +180,22 @@ describe('VML drawing canvas (v:group) textboxes', () => {
const doc = await parseDocx(await buildDocx({ bodyXml: canvasParagraph() }))
const block = doc.blocks[0]
expect(block.label).toBe('Text box')
const box = block.textboxes?.[0]
// the canvas itself reserves its flow footprint (126×99pt)
const spacer = block.textboxes?.[0]
expect(spacer?.widthPx).toBe(168)
expect(spacer?.heightPx).toBe(132)
expect(spacer?.paras).toHaveLength(0)
const box = block.textboxes?.[1]
// 1130/1976 × 126pt = 72pt = 96px; 1115/1533 × 99pt = 72pt = 96px
expect(box?.widthPx).toBe(96)
expect(box?.heightPx).toBe(96)
// VML strokes default on/black — Word draws the canvas textbox border
expect(box?.borderColor).toBe('000000')
expect(box?.paras[0]?.runs[0]?.text).toBe('Словарь')
// floated at its canvas position: (4257-3834)×sx, (5969-5690)×sy (EMU: ×9525)
expect(box?.floating).toBe(true)
expect(box?.offsetXEmu).toBe(Math.round((4257 - 3834) * (168 / 1976) * 9525))
expect(box?.offsetYEmu).toBe(Math.round((5969 - 5690) * (132 / 1533) * 9525))
})
it('keeps paragraph text next to the canvas visible as a display-only line', async () => {
@@ -197,8 +206,8 @@ describe('VML drawing canvas (v:group) textboxes', () => {
)
const block = doc.blocks[0]
expect(block.label).toBe('Text box')
expect(block.textboxes).toHaveLength(2)
const stray = block.textboxes?.[1]
expect(block.textboxes).toHaveLength(3)
const stray = block.textboxes?.[2]
expect(stray?.readOnly).toBe(true)
expect(stray?.paras[0]?.runs.map((r) => r.text).join('')).toBe('Hyperlink line')
expect(block.previewText).toContain('Словарь')
@@ -217,7 +226,7 @@ describe('VML drawing canvas (v:group) textboxes', () => {
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="http://www.google.com" TargetMode="External"/>',
}),
)
const stray = doc.blocks[0].textboxes?.[1]
const stray = doc.blocks[0].textboxes?.[2]
const run = stray?.paras[0]?.runs[0]
expect(run?.text).toBe('Hyperlink')
expect(run?.link?.href).toBe('http://www.google.com')
@@ -282,3 +291,72 @@ describe('w14:textFill run color approximation', () => {
expect(doc.blocks[0].runs?.[0]?.color).toBe('112233')
})
})
describe('VML pictures and geometry in w:pict', () => {
const txbxShape =
'<v:shape id="tb" type="#_x0000_t202" style="position:absolute;left:100;top:100;width:400;height:100">' +
'<v:textbox><w:txbxContent><w:p><w:r><w:t>label</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape>'
it('renders a grouped t75 picture shape as a floating photo box', async () => {
const bodyXml =
`<w:p><w:r><w:pict><v:group ${V_NS} style="width:150pt;height:75pt" coordsize="2000,1000">` +
'<v:shape id="pic" type="#_x0000_t75" style="position:absolute;left:100;top:50;width:200;height:100">' +
'<v:imagedata r:id="rId10" o:title=""/></v:shape>' +
txbxShape +
'</v:group></w:pict></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml, withImage: true }))
const boxes = doc.blocks[0].textboxes ?? []
// canvas spacer, photo, textbox — in document order
expect(boxes).toHaveLength(3)
const photo = boxes[1]
expect(photo?.fillImageDataUrl).toContain('data:image/')
// 150pt=200px, 2000 units wide → sx 0.1; 75pt=100px, 1000 units → sy 0.1
expect(photo?.widthPx).toBe(20)
expect(photo?.heightPx).toBe(10)
expect(photo?.floating).toBe(true)
expect(photo?.offsetXEmu).toBe(Math.round(10 * 9525))
expect(photo?.offsetYEmu).toBe(Math.round(5 * 9525))
})
it('converts an omitted-coordinate v:path into normalized pathData', async () => {
const bodyXml =
`<w:p><w:r><w:pict><v:group ${V_NS} style="width:150pt;height:75pt" coordsize="2000,1000">` +
'<v:shape id="bg" style="position:absolute;left:0;top:0;width:2000;height:1000" ' +
'fillcolor="#5B9BD5" stroked="f" coordsize="21600,21600" ' +
'path="m,l21600,,21600,21600,,21600nfxe"/>' +
txbxShape +
'</v:group></w:pict></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const geom = (doc.blocks[0].textboxes ?? []).find((b) => b.fill === '5B9BD5')
expect(geom).toBeDefined()
expect(geom?.pathData?.path).toBe('M 0 0 L 1 0 L 1 1 L 0 1 Z')
expect(geom?.widthPx).toBe(200)
expect(geom?.heightPx).toBe(100)
})
it('keeps lowercase #ffffff unstroked placeholders invisible', async () => {
const bodyXml =
`<w:p><w:r><w:pict><v:group ${V_NS} style="width:150pt;height:75pt" coordsize="2000,1000">` +
'<v:rect id="ph" style="position:absolute;left:0;top:0;width:2000;height:1000" ' +
'fillcolor="#ffffff" stroked="f"/>' +
txbxShape +
'</v:group></w:pict></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const boxes = doc.blocks[0].textboxes ?? []
// canvas spacer + textbox only — no box for the white placeholder
expect(boxes).toHaveLength(2)
expect(boxes.every((b) => b.fill === undefined)).toBe(true)
})
it('does not lift a filled shape nested in textbox content onto the page', async () => {
const bodyXml =
`<w:p><w:r><w:pict><v:shape ${V_NS} id="tb4" type="#_x0000_t202" style="width:100pt;height:40pt">` +
'<v:textbox><w:txbxContent><w:p><w:r><w:t>host</w:t></w:r><w:r><w:pict>' +
'<v:rect id="inner" style="width:50pt;height:10pt" fillcolor="#FF0000" stroked="f"/>' +
'</w:pict></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></w:r></w:p>'
const doc = await parseDocx(await buildDocx({ bodyXml }))
const boxes = doc.blocks[0].textboxes ?? []
expect(boxes).toHaveLength(1)
expect(boxes[0]?.fill).toBeUndefined()
})
})
@@ -27,13 +27,14 @@ function drawing(opts: {
cy: number
text: string
wrap: string
relH?: string
relV?: string
inner?: string
}): string {
return (
`<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>${opts.offXEmu}</wp:posOffset></wp:positionH>` +
`<wp:positionH relativeFrom="${opts.relH ?? 'column'}"><wp:posOffset>${opts.offXEmu}</wp:posOffset></wp:positionH>` +
`<wp:positionV relativeFrom="${opts.relV ?? 'paragraph'}"><wp:posOffset>${opts.offYEmu}</wp:posOffset></wp:positionV>` +
`<wp:extent cx="${opts.cx}" cy="${opts.cy}"/>${opts.wrap}` +
`<wp:docPr id="1" name="Box"/>` +
@@ -165,6 +166,197 @@ describe('wrapTopAndBottom band reservation', () => {
expect(box.bandBottomPx).toBeUndefined()
})
// body width in the test sectPr: 11906 − 2×1440 = 9026 twips = 5731510 EMU
it('reserves the band for a column-spanning wrapSquare box in a multi-drawing paragraph', async () => {
const para =
`<w:p><w:r>` +
drawing({
offXEmu: 60000,
offYEmu: 190500, // 20 px
cx: 5600000, // leaves < 36px beside the box
cy: 476250, // 50 px
text: 'wide',
wrap: '<wp:wrapSquare wrapText="bothSides"/>',
}) +
drawing({
offXEmu: 0,
offYEmu: 1905000,
cx: 1905000,
cy: 476250,
text: 'other',
wrap: '<wp:wrapNone/>',
}) +
`</w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [wide] = doc.blocks[0].textboxes!
expect(wide.floating).toBe(true)
expect(wide.bandTopPx).toBe(20)
expect(wide.bandBottomPx).toBe(70)
})
it('keeps a narrow wrapSquare box bandless in a multi-drawing paragraph', async () => {
const para =
`<w:p><w:r>` +
drawing({
offXEmu: 0,
offYEmu: 190500,
cx: 1905000, // wide sliver remains: text wraps beside it in Word
cy: 476250,
text: 'narrow',
wrap: '<wp:wrapSquare wrapText="bothSides"/>',
}) +
drawing({
offXEmu: 0,
offYEmu: 1905000,
cx: 1905000,
cy: 476250,
text: 'other',
wrap: '<wp:wrapNone/>',
}) +
`</w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [narrow] = doc.blocks[0].textboxes!
expect(narrow.floating).toBe(true)
expect(narrow.bandBottomPx).toBeUndefined()
})
// page-relative posOffset already lands in column space by parse time; the
// span test must not subtract the margin a second time
it('bands a page-relative wrapSquare box that covers the column', async () => {
const para =
`<w:p><w:r>` +
drawing({
offXEmu: 914400 + 60000, // margin (1440tw) + 60000 from the column left
offYEmu: 190500, // 20 px
cx: 5600000,
cy: 476250, // 50 px
text: 'page wide',
wrap: '<wp:wrapSquare wrapText="bothSides"/>',
relH: 'page',
}) +
`</w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [box] = doc.blocks[0].textboxes!
expect(box.floating).toBe(true)
expect(box.bandTopPx).toBe(20)
expect(box.bandBottomPx).toBe(70)
})
it('unions mixed page- and column-relative anchors in one coordinate space', async () => {
const para =
`<w:p><w:r>` +
drawing({
offXEmu: 914400, // page-relative left half: column x = 0
offYEmu: 190500, // 20 px
cx: 2900000,
cy: 476250, // 50 px
text: 'left half',
wrap: '<wp:wrapSquare wrapText="bothSides"/>',
relH: 'page',
}) +
drawing({
offXEmu: 2900000,
offYEmu: 190500,
cx: 2831510, // right half: no sliver remains
cy: 476250,
text: 'right half',
wrap: '<wp:wrapSquare wrapText="bothSides"/>',
}) +
`</w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [left, right] = doc.blocks[0].textboxes!
expect(left.bandTopPx).toBe(20)
expect(right.bandTopPx).toBe(20)
// a union band never overflows the page bottom
expect(left.bandOverflow).toBeUndefined()
expect(right.bandOverflow).toBeUndefined()
})
it('floats a lone column-spanning wrapSquare box with its band', async () => {
const para =
`<w:p><w:r>` +
drawing({
offXEmu: 60000,
offYEmu: 190500, // 20 px
cx: 5600000,
cy: 476250, // 50 px
text: 'solo wide',
wrap: '<wp:wrapSquare wrapText="bothSides"/>',
}) +
`</w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [box] = doc.blocks[0].textboxes!
expect(box.floating).toBe(true)
expect(box.bandTopPx).toBe(20)
expect(box.bandBottomPx).toBe(70)
})
it('bands a wrapSquare box when the paragraph union of anchors covers the column', async () => {
const para =
`<w:p><w:r>` +
drawing({
offXEmu: 60000,
offYEmu: 190500, // 20 px
cx: 2800000, // left half
cy: 476250, // 50 px
text: 'left frame',
wrap: '<wp:wrapSquare wrapText="bothSides"/>',
}) +
drawing({
offXEmu: 2860000,
offYEmu: 190500,
cx: 2800000, // right half: union leaves < 36px of column
cy: 476250,
text: 'right frame',
wrap: '<wp:wrapNone/>',
}) +
`</w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [left, right] = doc.blocks[0].textboxes!
expect(left.floating).toBe(true)
expect(left.bandTopPx).toBe(20)
expect(left.bandBottomPx).toBe(70)
// union spanning is not own spanning: the band is pushed whole, not overflowed
expect(left.bandOverflow).toBeUndefined()
expect(right.floating).toBe(true)
expect(right.bandBottomPx).toBeUndefined()
})
it('flags the overflow band only for a box spanning the column by itself', async () => {
const para =
`<w:p><w:r>` +
drawing({
offXEmu: 60000,
offYEmu: 190500,
cx: 5600000,
cy: 476250,
text: 'solo wide',
wrap: '<wp:wrapSquare wrapText="bothSides"/>',
}) +
`</w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [box] = doc.blocks[0].textboxes!
expect(box.bandOverflow).toBe(true)
})
it('keeps a lone narrow wrapSquare box on the flow path', async () => {
const para =
`<w:p><w:r>` +
drawing({
offXEmu: 60000,
offYEmu: 190500,
cx: 1905000, // wide sliver remains beside the box
cy: 476250,
text: 'solo narrow',
wrap: '<wp:wrapSquare wrapText="bothSides"/>',
}) +
`</w:r></w:p>`
const doc = await parseDocx(await buildDocx({ bodyXml: para }))
const [box] = doc.blocks[0].textboxes!
expect(box.floating).toBeUndefined()
expect(box.bandBottomPx).toBeUndefined()
})
it('keeps wrapNone semantics unchanged (floating, no band)', async () => {
const para =
`<w:p><w:r>` +