fix(docx): keep header and footer paragraphs right-to-left on save (#62)

The rich header/footer writer hand-builds its paragraph properties and emits
only w:jc, so editing an RTL header drops w:bidi entirely. It also writes the
alignment back unswapped: parse.ts converts Word's logical w:jc to a visual
direction on read for bidi paragraphs, so para.align holds the visual value,
and writing it straight out turns right into left. Both faults together:

  before  <w:pPr><w:bidi/><w:jc w:val="right"/></w:pPr>
  after   <w:pPr><w:jc w:val="left"/></w:pPr>

The header looks right in the app and is wrong the moment Word reopens it: an
Arabic header carrying a Latin or numeric run loses its paragraph direction,
so the neutral characters around it resolve to the other end of the line.

Build the properties with mergePPrFormat instead, so the bidi swap lives in
one place rather than two. Spacing, indent, borders and tab stops in headers
come along for free.

That makes this the first caller of mergePPrFormat outside the tests, and its
fresh-build branch, the one '<w:pPr/>' takes, joined the model's children in
emission order. Every other path sorts: generateParagraphXml sorts its own
children by PPR_CHILD_ORDER, and so does the interleaving branch of
mergePPrFormat itself. Over every combination of the fourteen ParaFormat
fields formatPPrChildren reads, 8168 of 16384 came out in the wrong CT_PPr
order, the smallest being align plus tabStops emitting w:jc before w:tabs.
Wrong CT_PPr order is what makes Word show the repair dialog, which
schema-order.test.ts already exists to prevent; its cases just never reached
the self-closing branch. Sorted there too, and extended that test to cover it.
This commit is contained in:
Waiel Al-Shujaa
2026-08-09 08:52:29 +08:00
committed by GitHub
parent 6a2d1cd823
commit d2e03aad1c
4 changed files with 59 additions and 9 deletions
+6 -2
View File
@@ -1145,8 +1145,12 @@ export function mergePPrFormat(rawPPr: string, format: ParaFormat | undefined):
const open = /^<w:pPr(?: [^>]*)?>/.exec(rawPPr)?.[0]
const fresh = formatPPrChildren(format)
if (!open) {
// '<w:pPr/>' or unrecognized: rebuild from the format model alone
return fresh.length > 0 ? `<w:pPr>${fresh.map((c) => c.xml).join('')}</w:pPr>` : ''
// '<w:pPr/>' or unrecognized: rebuild from the format model alone, in schema order
// (formatPPrChildren emits by concern, and CT_PPr order is not optional)
const sorted = [...fresh].sort(
(a, b) => PPR_CHILD_ORDER.indexOf(a.name) - PPR_CHILD_ORDER.indexOf(b.name),
)
return sorted.length > 0 ? `<w:pPr>${sorted.map((c) => c.xml).join('')}</w:pPr>` : ''
}
const inner = rawPPr.slice(open.length, rawPPr.length - '</w:pPr>'.length)
// build set of managed tags for this format (base + conditional)
+11 -5
View File
@@ -1,5 +1,11 @@
import JSZip from 'jszip'
import { applyImageWrap, generateParagraphXml, inlineRunsXml, splitXmlChildren } from './generate'
import {
applyImageWrap,
generateParagraphXml,
inlineRunsXml,
mergePPrFormat,
splitXmlChildren,
} from './generate'
import {
NOTE_CONTENT_TYPE,
NOTE_PART_PATH,
@@ -1262,9 +1268,9 @@ function headerFooterPartXml(
let pageEmitted = !hf.pageNumber
content = hf.paras
.map((para) => {
const jc = para.align
? `<w:pPr><w:jc w:val="${para.align === 'justify' ? 'both' : para.align}"/></w:pPr>`
: ''
// the parsed format, not just w:jc: hand-building it here dropped w:bidi and wrote
// the visual align back as the logical one, flipping RTL headers to LTR
const pPr = mergePPrFormat('<w:pPr/>', para)
let runs = ''
for (const run of para.runs) {
if (run.text.includes(TOTAL_PAGES_MARK) || (!pageEmitted && run.text.includes('#'))) {
@@ -1285,7 +1291,7 @@ function headerFooterPartXml(
runs += inlineRunsXml([run])
}
}
return `<w:p>${jc}${runs}</w:p>`
return `<w:p>${pPr}${runs}</w:p>`
})
.join('')
if (!pageEmitted) content += `<w:p><w:pPr><w:jc w:val="center"/></w:pPr>${pageField}</w:p>`
@@ -12,6 +12,22 @@ async function base() {
}
describe('rich header / footer', () => {
it('keeps an RTL header right-to-left and keeps its alignment side', async () => {
const { parsed, saveBlocks } = await base()
const saved = await saveDocx(parsed, saveBlocks, {
header: {
text: '',
paras: [
{ bidi: true, align: 'left', runs: [{ text: 'ترويسة عربية' }] },
{ bidi: true, runs: [{ text: 'بدون محاذاة' }] },
],
},
})
const reparsed = await parseDocx(saved)
expect(reparsed.headerParas![0]).toMatchObject({ bidi: true, align: 'left' })
expect(reparsed.headerParas![1]?.bidi).toBe(true)
})
it('saves multi-paragraph styled header and reparses it as headerParas', async () => {
const { parsed, saveBlocks } = await base()
const saved = await saveDocx(parsed, saveBlocks, {
@@ -22,7 +22,10 @@ function assertSchemaOrder(fragment: string, rootTag: string, order: readonly st
for (const child of splitXmlChildren(inner)) {
const rank = order.indexOf(child.name)
if (rank === -1) continue
expect(rank, `${child.name} appears after ${prevName}, violating the ${rootTag} schema order`).toBeGreaterThanOrEqual(prev)
expect(
rank,
`${child.name} appears after ${prevName}, violating the ${rootTag} schema order`,
).toBeGreaterThanOrEqual(prev)
prev = rank
prevName = child.name
}
@@ -37,7 +40,10 @@ describe('rPr schema order (mergeRPrModel)', () => {
['add bold', { text: 'x', bold: true }],
['add italic + highlight', { text: 'x', italic: true, highlight: 'yellow' }],
['change color + size', { text: 'x', color: 'FF0000', sizeHalfPoints: 36 }],
['add style + vertAlign', { text: 'x', styleId: 'Emphasis', vertAlign: 'superscript' as const }],
[
'add style + vertAlign',
{ text: 'x', styleId: 'Emphasis', vertAlign: 'superscript' as const },
],
['clear underline + add font', { text: 'x', underline: false, font: '微软雅黑' }],
])('%s keeps CT_RPr child order', (_label, run) => {
const out = mergeRPrModel(RAW, { ...run }, false)
@@ -77,4 +83,22 @@ describe('pPr schema order (mergePPrFormat)', () => {
// elements inside pPr)
expect(out).toContain('<w:rPr><w:b/></w:rPr>')
})
// The fresh-build branch ('<w:pPr/>', taken by the header/footer writer) has no raw
// children to interleave against, so it has to sort on its own.
it.each([
['bidi + align', { bidi: true, align: 'left' as const }],
['tabs + bidi', { bidi: true, tabStops: [{ pos: 720, val: 'left' as const }] }],
[
'framePr + tabs + bidi + align',
{
align: 'center' as const,
bidi: true,
tabStops: [{ pos: 1440, val: 'right' as const }],
dropCap: { type: 'drop' as const, lines: 3 },
},
],
])('%s keeps CT_PPr child order when built from the model alone', (_label, format) => {
assertSchemaOrder(mergePPrFormat('<w:pPr/>', format), 'w:pPr', PPR_CHILD_ORDER)
})
})