fix(docx): preserve edge spaces in field patches (#320)
Co-authored-by: Aniruddha Adak <aniruddhaadak80@users.noreply.github.com>
This commit is contained in:
co-authored by
Aniruddha Adak
parent
601ba438d7
commit
c5ff3ea4e1
@@ -298,7 +298,13 @@ function replaceTextNodes(
|
||||
): string {
|
||||
let out = xml
|
||||
for (const { node, text } of [...replacements].sort((a, b) => b.node.start - a.node.start)) {
|
||||
const replacement = node.open + escapeXmlText(text) + node.close
|
||||
// wtText drops edge whitespace without xml:space="preserve": pin it when
|
||||
// the replacement introduces a leading/trailing space or tab.
|
||||
const open =
|
||||
/xml:space\s*=/.test(node.open) || !/(^[\t ]|[\t ]$)/.test(text)
|
||||
? node.open
|
||||
: node.open.replace(/<w:t(?=\s|>)/, '<w:t xml:space="preserve"')
|
||||
const replacement = open + escapeXmlText(text) + node.close
|
||||
out = out.slice(0, node.start) + replacement + out.slice(node.end)
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -48,6 +48,18 @@ describe('protected visible-text patching', () => {
|
||||
expect(patched).not.toContain('Latar Belakang')
|
||||
})
|
||||
|
||||
it('pins xml:space preserve when the patched text gains edge spaces', async () => {
|
||||
const entry =
|
||||
'<w:p><w:pPr><w:pStyle w:val="TOC2"/></w:pPr>' +
|
||||
'<w:r><w:t>Title</w:t></w:r><w:r><w:tab/></w:r>' +
|
||||
'<w:r><w:t>7</w:t></w:r></w:p>'
|
||||
const patched = patchFieldParagraphXml(entry, { left: ' Title ', right: '7' })
|
||||
// without preserve, wtText drops the edge spaces on re-parse and Word loses them too
|
||||
expect(patched).toContain('<w:t xml:space="preserve"> Title </w:t>')
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: patched }))
|
||||
expect(parsed.blocks[0].fieldDisplay?.kind).toBe('tocLine')
|
||||
})
|
||||
|
||||
it('edits OMML tokens while preserving the formula tree', async () => {
|
||||
const patched = patchMathTokens(FORMULA, ['x & 1', 'y'])
|
||||
expect(patched).toContain('<m:f><m:num>')
|
||||
|
||||
Reference in New Issue
Block a user