markdown-to-word 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"docx-font-preset.js","sourceRoot":"","sources":["../src/docx-font-preset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,IAAI,IAAI,GAC1B,MAAM,eAAe,CAAC;AAEvB,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG;IAC5B,YAAY;IACZ,eAAe;IACf,YAAY;IACZ,SAAS;CACV,CAAC;AAEF;;;GAGG;AACH,MAAM,cAAc,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAiBrD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,YAAkB,EAClB,MAAkB;IAElB,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,WAAW,GAAG,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;IAChD,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;IACJ,CAAC;IAED,IAAI,IAAI,GAAgB,IAAI,CAAC;IAC7B,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC;IACnC,IACE,QAAQ;QACR,MAAM,CAAC,SAAS,CAAC,WAAW,KAAK,MAAM;QACvC,MAAM,CAAC,SAAS,CAAC,oBAAoB,EACrC,CAAC;QACD,MAAM,aAAa,GAAG,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;QACpD,IAAI,CAAC,aAAa,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CACb,kEAAkE,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,CACpC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,CACzC,CAAC;IACF,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,CAAC,aAAa,CAAC,eAAe,CAAC,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC,CAAC;IAC7E,OAAO,QAAQ,KAAK,OAAO;QACzB,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,UAAU,CAAC;QACjD,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,cAAc,CAAC,GAAa,EAAE,SAAiB;IACtD,MAAM,OAAO,GAAG,GAAG,CAAC,sBAAsB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,kDAAkD,SAAS,WAAW,CACvE,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport type { FontPreset, LevelStyle, ParagraphStyle } from './font-presets.js';\nimport {\n keepXmlDeclaration,\n paragraphProperty,\n WORDPROCESSING_NS as W_NS,\n} from './xml-part.js';\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = [\n 'asciiTheme',\n 'eastAsiaTheme',\n 'hAnsiTheme',\n 'cstheme',\n];\n\n/**\n * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240\n * twips, so the preset writes the pair Word itself produces.\n */\nconst SINGLE_SPACING = { line: '240', rule: 'auto' };\n\n/** Word's document grid, in the units of `<w:docGrid>`. */\ninterface Grid {\n /** Line pitch in twips. */\n linePitch: number;\n /** Character pitch relative to the body font size, in 1/4096 point. */\n charSpace: number;\n}\n\n/** What the styles need to know about the paragraphs, resolved once. */\ninterface Layout {\n spacing: { line: string; rule: string };\n /** First-line indent of body paragraphs in twips, or 0 for none. */\n firstLineIndent: number;\n}\n\n/**\n * Rewrites the fonts, sizes, paragraph spacing and page grid of an already\n * generated .docx.\n *\n * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin\n * characters and digits; Chinese characters fall back to the theme font. The\n * East Asian slots are set here instead, so this stays out of the way of the\n * default conversion output.\n *\n * The grid is measured from the page the document actually has, so it still\n * fits when `pageMargins` overrode the preset's margins.\n */\nexport async function applyFontPreset(\n wordDocument: Blob,\n preset: FontPreset\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const stylesEntry = zip.file('word/styles.xml');\n if (!stylesEntry) {\n throw new Error(\n 'Cannot apply font preset: document contains no word/styles.xml'\n );\n }\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (\n pageGrid ||\n preset.paragraph.lineSpacing === 'grid' ||\n preset.paragraph.firstLineIndentChars\n ) {\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot apply font preset: document contains no word/document.xml'\n );\n }\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, preset);\n grid = patched.grid;\n zip.file('word/document.xml', patched.xml);\n }\n\n const stylesXml = await stylesEntry.async('string');\n zip.file('word/styles.xml', patchStylesXml(stylesXml, preset, grid));\n\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/**\n * Applies `preset` to the document default run properties and to the six\n * heading styles of a styles.xml part. `grid` is the page grid that\n * `patchDocumentXml` set, which `lineSpacing: 'grid'` takes its pitch from.\n */\nexport function patchStylesXml(\n stylesXml: string,\n preset: FontPreset,\n grid: Grid | null = null\n): string {\n const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');\n const layout = resolveLayout(preset, grid);\n\n const docDefaults = requireElement(dom, 'docDefaults');\n applyLevelStyle(docDefaults, preset.body, preset.paragraph, layout);\n if (layout.spacing.rule === 'exact') {\n // Widow control pulls a line onto the next page whenever a paragraph would\n // leave a single line behind, so pages would often hold one line fewer\n // than the grid. Word turns it on unless the document says otherwise.\n paragraphProperty(\n paragraphPropertiesOf(docDefaults),\n 'widowControl'\n ).setAttributeNS(W_NS, 'w:val', '0');\n }\n\n const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));\n for (const style of styles) {\n const heading = /^Heading([1-6])$/.exec(\n style.getAttributeNS(W_NS, 'styleId') ?? ''\n );\n if (heading) {\n applyLevelStyle(\n style,\n preset.headings[Number(heading[1]) - 1],\n preset.paragraph,\n layout\n );\n }\n }\n\n return keepXmlDeclaration(\n stylesXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction resolveLayout(preset: FontPreset, grid: Grid | null): Layout {\n const { lineSpacing, firstLineIndentChars = 0 } = preset.paragraph;\n if (lineSpacing === 'grid' && !grid) {\n throw new Error(\n \"Cannot apply font preset: lineSpacing 'grid' needs page.grid\"\n );\n }\n return {\n spacing:\n lineSpacing === 'grid' && grid\n ? { line: String(grid.linePitch), rule: 'exact' }\n : SINGLE_SPACING,\n firstLineIndent: Math.round(firstLineIndentChars * preset.body.sizePt * 20),\n };\n}\n\n/**\n * Sets the page grid in the section properties of a document.xml part, and\n * fixes up the paragraphs that the style-level layout would break:\n *\n * - The generator gives every paragraph `<w:spacing w:lineRule=\"auto\"/>`.\n * Spacing attributes inherit one at a time, so that lone `auto` combined\n * with the style's exact line height would read as a multiple of 240 twips\n * (about 2.4 lines). It is dropped when the preset uses grid spacing.\n * - Exact line spacing would crop an inline image to one line, so paragraphs\n * with a drawing keep single spacing; the grid then rounds them up to whole\n * lines.\n * - Table cells drop the first-line indent; it only crowds narrow columns.\n */\nexport function patchDocumentXml(\n documentXml: string,\n preset: FontPreset\n): { xml: string; grid: Grid | null } {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (pageGrid) {\n for (const sectPr of Array.from(\n dom.getElementsByTagNameNS(W_NS, 'sectPr')\n )) {\n grid = measureGrid(sectPr, pageGrid, preset.body.sizePt);\n setDocGrid(sectPr, grid);\n }\n }\n\n const gridSpacing = preset.paragraph.lineSpacing === 'grid';\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n const pPr = children(paragraph).find((child) => child.localName === 'pPr');\n\n if (gridSpacing) {\n if (paragraph.getElementsByTagNameNS(W_NS, 'drawing').length > 0) {\n const spacing = paragraphProperty(pPrOf(paragraph), 'spacing');\n spacing.setAttributeNS(W_NS, 'w:line', SINGLE_SPACING.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', SINGLE_SPACING.rule);\n } else {\n const spacing =\n pPr && children(pPr).find((child) => child.localName === 'spacing');\n if (spacing && !spacing.hasAttributeNS(W_NS, 'line')) {\n spacing.removeAttributeNS(W_NS, 'lineRule');\n if (spacing.attributes.length === 0) {\n spacing.remove();\n }\n }\n }\n }\n\n if (preset.paragraph.firstLineIndentChars && isInTableCell(paragraph)) {\n removeFirstLineIndent(pPrOf(paragraph));\n }\n }\n\n return {\n xml: keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n ),\n grid,\n };\n}\n\n/**\n * The grid for the text block of `sectPr`'s page. Word stores the character\n * pitch as an offset from the body font size. Both pitches are rounded down,\n * as Word does, so the lines and characters always fit: for the page Word\n * itself sets up with GB/T 9704 margins, this reproduces its linePitch=\"579\"\n * and charSpace=\"-834\".\n */\nfunction measureGrid(\n sectPr: Element,\n {\n linesPerPage,\n charsPerLine,\n }: { linesPerPage: number; charsPerLine: number },\n bodySizePt: number\n): Grid {\n const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');\n const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');\n const twips = (element: Element | undefined, attribute: string): number => {\n const value = Number(element?.getAttributeNS(W_NS, attribute));\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(\n `Cannot apply font preset: section has no page ${attribute}`\n );\n }\n return value;\n };\n\n const textHeight =\n twips(pgSz, 'h') - twips(pgMar, 'top') - twips(pgMar, 'bottom');\n const textWidth =\n twips(pgSz, 'w') - twips(pgMar, 'left') - twips(pgMar, 'right');\n const charPitchPt = textWidth / 20 / charsPerLine;\n\n return {\n linePitch: Math.floor(textHeight / linesPerPage),\n charSpace: Math.floor((charPitchPt - bodySizePt) * 4096),\n };\n}\n\nfunction setDocGrid(sectPr: Element, grid: Grid): void {\n let docGrid = children(sectPr).find((child) => child.localName === 'docGrid');\n if (!docGrid) {\n docGrid = sectPr.ownerDocument.createElementNS(W_NS, 'w:docGrid');\n // <w:docGrid> is the last section property but <w:printerSettings>.\n const printerSettings = children(sectPr).find(\n (child) => child.localName === 'printerSettings'\n );\n sectPr.insertBefore(docGrid, printerSettings ?? null);\n }\n docGrid.setAttributeNS(W_NS, 'w:type', 'linesAndChars');\n docGrid.setAttributeNS(W_NS, 'w:linePitch', String(grid.linePitch));\n docGrid.setAttributeNS(W_NS, 'w:charSpace', String(grid.charSpace));\n}\n\nfunction isInTableCell(paragraph: Element): boolean {\n for (let node = paragraph.parentElement; node; node = node.parentElement) {\n if (node.namespaceURI === W_NS && node.localName === 'tc') {\n return true;\n }\n }\n return false;\n}\n\nfunction removeFirstLineIndent(pPr: Element): void {\n const ind = paragraphProperty(pPr, 'ind');\n if (!ind.hasAttributeNS(W_NS, 'hanging')) {\n ind.setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n}\n\n/** A paragraph's `<w:pPr>`, created as its first child if missing. */\nfunction pPrOf(paragraph: Element): Element {\n return childOrCreate(paragraph, 'pPr', 'first');\n}\n\nfunction applyLevelStyle(\n scope: Element,\n style: LevelStyle,\n paragraph: ParagraphStyle,\n layout: Layout\n): void {\n const rPr = runPropertiesOf(scope);\n\n const rFonts = childOrCreate(rPr, 'rFonts', 'first');\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n rFonts.setAttributeNS(W_NS, 'w:ascii', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:hAnsi', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:eastAsia', style.eastAsia);\n\n for (const child of children(rPr)) {\n if (child.localName === 'b' || child.localName === 'bCs') {\n child.remove();\n }\n }\n if (style.bold) {\n rPr.insertBefore(\n rPr.ownerDocument.createElementNS(W_NS, 'w:b'),\n rFonts.nextSibling\n );\n }\n\n // <w:sz> is measured in half points.\n const size = String(style.sizePt * 2);\n childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);\n childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);\n\n const pPr = paragraphPropertiesOf(scope);\n const spacing = paragraphProperty(pPr, 'spacing');\n spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));\n spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));\n spacing.setAttributeNS(W_NS, 'w:line', layout.spacing.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', layout.spacing.rule);\n\n if (style.centered) {\n // An indented first line would push a centered title off center.\n if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n paragraphProperty(pPr, 'jc').setAttributeNS(W_NS, 'w:val', 'center');\n } else if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(\n W_NS,\n 'w:firstLine',\n String(layout.firstLineIndent)\n );\n }\n}\n\nfunction runPropertiesOf(parent: Element): Element {\n const container =\n parent.localName === 'docDefaults'\n ? childOrCreate(parent, 'rPrDefault', 'first')\n : parent;\n // In a <w:style> the run properties go last, after any <w:pPr>.\n return childOrCreate(container, 'rPr', 'last');\n}\n\nfunction paragraphPropertiesOf(parent: Element): Element {\n if (parent.localName === 'docDefaults') {\n const pPrDefault = childOrCreate(parent, 'pPrDefault', 'last');\n return childOrCreate(pPrDefault, 'pPr', 'first');\n }\n\n const existing = children(parent).find((child) => child.localName === 'pPr');\n if (existing) {\n return existing;\n }\n // In a <w:style> the paragraph properties go before the run properties.\n const created = parent.ownerDocument.createElementNS(W_NS, 'w:pPr');\n return parent.insertBefore(created, runPropertiesOf(parent));\n}\n\nfunction children(element: Element): Element[] {\n return Array.from(element.children).filter(\n (child) => child.namespaceURI === W_NS\n );\n}\n\nfunction childOrCreate(\n parent: Element,\n localName: string,\n position: 'first' | 'last'\n): Element {\n const existing = children(parent).find(\n (child) => child.localName === localName\n );\n if (existing) {\n return existing;\n }\n const created = parent.ownerDocument.createElementNS(W_NS, `w:${localName}`);\n return position === 'first'\n ? parent.insertBefore(created, parent.firstChild)\n : parent.appendChild(created);\n}\n\nfunction requireElement(dom: Document, localName: string): Element {\n const element = dom.getElementsByTagNameNS(W_NS, localName)[0];\n if (!element) {\n throw new Error(\n `Cannot apply font preset: styles.xml has no <w:${localName}> element`\n );\n }\n return element;\n}\n"]}
1
+ {"version":3,"file":"docx-font-preset.js","sourceRoot":"","sources":["../src/docx-font-preset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAQ1B,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,IAAI,IAAI,GAC1B,MAAM,eAAe,CAAC;AAEvB,+DAA+D;AAC/D,MAAM,qBAAqB,GAAG;IAC5B,YAAY;IACZ,eAAe;IACf,YAAY;IACZ,SAAS;CACV,CAAC;AAEF;;;GAGG;AACH,MAAM,cAAc,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAiBrD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,YAAkB,EAClB,MAAkB;IAElB,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,WAAW,GAAG,GAAG,CAAC,IAAI,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AM,CAAC,YAAY,CAAC,OAAO,EAAE,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,QAAQ,CAAC,OAAgB;IAChC,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,MAAM,CACxC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,CACvC,CAAC;AACJ,CAAC;AAED,SAAS,aAAa,CACpB,MAAe,EACf,SAAiB,EACjB,QAA0B;IAE1B,MAAM,QAAQ,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,IAAI,CACpC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,CACzC,CAAC;IACF,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,CAAC,aAAa,CAAC,eAAe,CAAC,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC,CAAC;IAC7E,OAAO,QAAQ,KAAK,OAAO;QACzB,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,UAAU,CAAC;QACjD,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,cAAc,CAAC,GAAa,EAAE,SAAiB;IACtD,MAAM,OAAO,GAAG,GAAG,CAAC,sBAAsB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,kDAAkD,SAAS,WAAW,CACvE,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport type {\n FontPreset,\n LevelStyle,\n LineSpacing,\n ParagraphStyle,\n TableStyle,\n} from './font-presets.js';\nimport {\n keepXmlDeclaration,\n paragraphProperty,\n WORDPROCESSING_NS as W_NS,\n} from './xml-part.js';\n\n/** Theme slots WinWord prefers over explicitly named fonts. */\nconst THEME_FONT_ATTRIBUTES = [\n 'asciiTheme',\n 'eastAsiaTheme',\n 'hAnsiTheme',\n 'cstheme',\n];\n\n/**\n * `<w:line>` is ignored while the rule is auto, but WinWord still writes 240\n * twips, so the preset writes the pair Word itself produces.\n */\nconst SINGLE_SPACING = { line: '240', rule: 'auto' };\n\n/** Word's document grid, in the units of `<w:docGrid>`. */\ninterface Grid {\n /** Line pitch in twips. */\n linePitch: number;\n /** Character pitch relative to the body font size, in 1/4096 point. */\n charSpace: number;\n}\n\n/** What the styles need to know about the paragraphs, resolved once. */\ninterface Layout {\n spacing: { line: string; rule: string };\n /** First-line indent of body paragraphs in twips, or 0 for none. */\n firstLineIndent: number;\n}\n\n/**\n * Rewrites the fonts, sizes, paragraph spacing, page grid and list layout of an\n * already generated .docx.\n *\n * `html-to-docx` only ever writes `w:ascii`, which WinWord applies to Latin\n * characters and digits; Chinese characters fall back to the theme font. The\n * East Asian slots are set here instead, so this stays out of the way of the\n * default conversion output.\n *\n * The grid is measured from the page the document actually has, so it still\n * fits when `pageMargins` overrode the preset's margins.\n */\nexport async function applyFontPreset(\n wordDocument: Blob,\n preset: FontPreset\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const stylesEntry = zip.file('word/styles.xml');\n if (!stylesEntry) {\n throw new Error(\n 'Cannot apply font preset: document contains no word/styles.xml'\n );\n }\n\n // The numbering part is read first: laying the document's lists out needs to\n // know which format each numbering definition uses at each level.\n const numberingEntry = zip.file('word/numbering.xml');\n const numberingXml = numberingEntry\n ? await numberingEntry.async('string')\n : null;\n const formats = numberingXml ? numberFormatsOf(numberingXml) : undefined;\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (\n pageGrid ||\n preset.paragraph.lineSpacing === 'grid' ||\n preset.paragraph.firstLineIndentChars ||\n preset.list?.multilevelNumbers ||\n preset.table\n ) {\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot apply font preset: document contains no word/document.xml'\n );\n }\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, preset, formats);\n grid = patched.grid;\n zip.file('word/document.xml', patched.xml);\n }\n\n const stylesXml = await stylesEntry.async('string');\n zip.file('word/styles.xml', patchStylesXml(stylesXml, preset, grid));\n\n // Lists are laid out only when the preset describes them; a document\n // without lists has no numbering part anyway.\n if (numberingXml !== null && preset.list) {\n zip.file('word/numbering.xml', patchNumberingXml(numberingXml, preset));\n }\n\n const patched = await zip.generateAsync({ type: 'arraybuffer' });\n return new Blob([patched], { type: wordDocument.type });\n}\n\n/**\n * Applies `preset` to the document default run properties and to the six\n * heading styles of a styles.xml part. `grid` is the page grid that\n * `patchDocumentXml` set, which `lineSpacing: 'grid'` takes its pitch from.\n */\nexport function patchStylesXml(\n stylesXml: string,\n preset: FontPreset,\n grid: Grid | null = null\n): string {\n const dom = new DOMParser().parseFromString(stylesXml, 'application/xml');\n const layout = resolveLayout(preset, grid);\n\n const docDefaults = requireElement(dom, 'docDefaults');\n applyLevelStyle(docDefaults, preset.body, preset.paragraph, layout);\n if (layout.spacing.rule === 'exact') {\n // Widow control pulls a line onto the next page whenever a paragraph would\n // leave a single line behind, so pages would often hold one line fewer\n // than the grid. Word turns it on unless the document says otherwise.\n paragraphProperty(\n paragraphPropertiesOf(docDefaults),\n 'widowControl'\n ).setAttributeNS(W_NS, 'w:val', '0');\n }\n\n const styles = Array.from(dom.getElementsByTagNameNS(W_NS, 'style'));\n for (const style of styles) {\n const heading = /^Heading([1-6])$/.exec(\n style.getAttributeNS(W_NS, 'styleId') ?? ''\n );\n if (heading) {\n applyLevelStyle(\n style,\n preset.headings[Number(heading[1]) - 1],\n preset.paragraph,\n layout\n );\n }\n }\n\n return keepXmlDeclaration(\n stylesXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction resolveLayout(preset: FontPreset, grid: Grid | null): Layout {\n const { lineSpacing, firstLineIndentChars = 0 } = preset.paragraph;\n return {\n spacing: spacingFor(lineSpacing, grid),\n firstLineIndent: Math.round(firstLineIndentChars * preset.body.sizePt * 20),\n };\n}\n\n/** The `<w:spacing>` pair a line-spacing choice resolves to on this page. */\nfunction spacingFor(\n lineSpacing: LineSpacing,\n grid: Grid | null\n): { line: string; rule: string } {\n if (lineSpacing !== 'grid') {\n return SINGLE_SPACING;\n }\n if (!grid) {\n throw new Error(\n \"Cannot apply font preset: lineSpacing 'grid' needs page.grid\"\n );\n }\n return { line: String(grid.linePitch), rule: 'exact' };\n}\n\n/**\n * Sets the page grid in the section properties of a document.xml part, and\n * fixes up the paragraphs that the style-level layout would break:\n *\n * - The generator gives every paragraph `<w:spacing w:lineRule=\"auto\"/>`.\n * Spacing attributes inherit one at a time, so that lone `auto` combined\n * with the style's exact line height would read as a multiple of 240 twips\n * (about 2.4 lines). It is dropped when the preset uses grid spacing.\n * - Exact line spacing would crop an inline image to one line, so paragraphs\n * with a drawing keep single spacing; the grid then rounds them up to whole\n * lines.\n * - Table cells drop the first-line indent; it only crowds narrow columns.\n * - When the preset describes table cells, they are laid out on their own\n * terms instead of inheriting the page grid: vertical alignment, line\n * spacing and grid snapping.\n */\nexport function patchDocumentXml(\n documentXml: string,\n preset: FontPreset,\n formats?: NumberFormats\n): { xml: string; grid: Grid | null } {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n\n if (preset.list?.multilevelNumbers && formats) {\n unifyListNumbering(dom, formats);\n }\n\n let grid: Grid | null = null;\n const pageGrid = preset.page?.grid;\n if (pageGrid) {\n for (const sectPr of Array.from(\n dom.getElementsByTagNameNS(W_NS, 'sectPr')\n )) {\n grid = measureGrid(sectPr, pageGrid, preset.body.sizePt);\n setDocGrid(sectPr, grid);\n }\n }\n\n const gridSpacing = preset.paragraph.lineSpacing === 'grid';\n const table = preset.table;\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n const pPr = children(paragraph).find((child) => child.localName === 'pPr');\n const inTableCell = isInTableCell(paragraph);\n\n if (gridSpacing && !inTableCell) {\n if (paragraph.getElementsByTagNameNS(W_NS, 'drawing').length > 0) {\n const spacing = paragraphProperty(pPrOf(paragraph), 'spacing');\n spacing.setAttributeNS(W_NS, 'w:line', SINGLE_SPACING.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', SINGLE_SPACING.rule);\n } else {\n const spacing =\n pPr && children(pPr).find((child) => child.localName === 'spacing');\n if (spacing && !spacing.hasAttributeNS(W_NS, 'line')) {\n spacing.removeAttributeNS(W_NS, 'lineRule');\n if (spacing.attributes.length === 0) {\n spacing.remove();\n }\n }\n }\n }\n\n if (table && inTableCell) {\n layoutTableCell(pPrOf(paragraph), table, grid);\n }\n\n if (preset.paragraph.firstLineIndentChars && inTableCell) {\n removeFirstLineIndent(pPrOf(paragraph));\n }\n }\n\n if (table) {\n for (const cell of Array.from(dom.getElementsByTagNameNS(W_NS, 'tc'))) {\n cellVerticalAlign(cell).setAttributeNS(\n W_NS,\n 'w:val',\n table.verticalAlign\n );\n }\n }\n\n return {\n xml: keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n ),\n grid,\n };\n}\n\n/** The number format a numbering definition uses at each level. */\nexport type NumberFormats = ReadonlyMap<string, string[]>;\n\n/**\n * Reads the numbering part into a `numId` → formats map, the way the document's\n * paragraphs reference it. `<w:num>` names an `<w:abstractNum>`, so the\n * abstract's levels answer for the id the paragraphs use.\n */\nfunction numberFormatsOf(numberingXml: string): NumberFormats {\n const dom = new DOMParser().parseFromString(numberingXml, 'application/xml');\n const formatsByAbstract = new Map<string, string[]>();\n\n for (const abstract of Array.from(\n dom.getElementsByTagNameNS(W_NS, 'abstractNum')\n )) {\n const abstractId = abstract.getAttributeNS(W_NS, 'abstractNumId');\n if (abstractId === null) {\n continue;\n }\n const levels: string[] = [];\n for (const lvl of children(abstract).filter(\n (child) => child.localName === 'lvl'\n )) {\n const ilvl = Number(lvl.getAttributeNS(W_NS, 'ilvl') ?? levels.length);\n levels[ilvl] =\n children(lvl)\n .find((child) => child.localName === 'numFmt')\n ?.getAttributeNS(W_NS, 'val') ?? '';\n }\n formatsByAbstract.set(abstractId, levels);\n }\n\n const formats = new Map<string, string[]>();\n for (const num of Array.from(dom.getElementsByTagNameNS(W_NS, 'num'))) {\n const numId = num.getAttributeNS(W_NS, 'numId');\n const abstractId = num\n .getElementsByTagNameNS(W_NS, 'abstractNumId')[0]\n ?.getAttributeNS(W_NS, 'val');\n const levels =\n abstractId === null ? undefined : formatsByAbstract.get(abstractId);\n if (numId !== null && levels) {\n formats.set(numId, levels);\n }\n }\n\n return formats;\n}\n\ninterface ParagraphNumbering {\n ilvl: number;\n numId: string;\n numIdElement: Element;\n}\n\n/** The `<w:numPr>` of a paragraph, when it has one that names a numbering. */\nfunction numberingOf(paragraph: Element): ParagraphNumbering | null {\n const pPr = children(paragraph).find((child) => child.localName === 'pPr');\n const numPr =\n pPr && children(pPr).find((child) => child.localName === 'numPr');\n if (!numPr) {\n return null;\n }\n\n const numIdElement = children(numPr).find(\n (child) => child.localName === 'numId'\n );\n const numId = numIdElement?.getAttributeNS(W_NS, 'val');\n if (!numIdElement || numId === undefined || numId === null) {\n return null;\n }\n\n const ilvl = Number(\n children(numPr)\n .find((child) => child.localName === 'ilvl')\n ?.getAttributeNS(W_NS, 'val') ?? '0'\n );\n return { ilvl, numId, numIdElement };\n}\n\n/**\n * Word counts a multi-level list inside one numbering definition: its items\n * share a `w:numId` and only `w:ilvl` changes. The generator instead gives\n * every nesting depth its own definition, so a nested item's `%1` is that\n * sub-list's counter rather than its parent's, and 1.1 can never appear.\n *\n * Point the deeper items of a list at the definition its first level uses. A\n * fresh first-level definition opens a new list, so separate lists never share\n * a counter, and a nested level whose format differs from the list's own (a\n * bullet inside a numbered list) keeps its own definition.\n */\nfunction unifyListNumbering(dom: Document, formats: NumberFormats): void {\n let listNumId: string | null = null;\n\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n const numbering = numberingOf(paragraph);\n if (!numbering) {\n // A list item's later paragraphs are unnumbered but indented under the\n // item, so only an unindented paragraph ends the list.\n const ind = paragraph.getElementsByTagNameNS(W_NS, 'ind')[0];\n if (Number(ind?.getAttributeNS(W_NS, 'left') ?? 0) <= 0) {\n listNumId = null;\n }\n continue;\n }\n\n if (numbering.ilvl === 0) {\n listNumId = numbering.numId;\n continue;\n }\n if (listNumId === null) {\n continue;\n }\n\n const list = formats.get(listNumId);\n const own = formats.get(numbering.numId);\n if (!list || !own || list[numbering.ilvl] !== own[numbering.ilvl]) {\n continue;\n }\n numbering.numIdElement.setAttributeNS(W_NS, 'w:val', listNumId);\n }\n}\n\n/**\n * Lays out lists the way a 公文 does, in the place Word itself writes these\n * choices — the numbering definitions:\n *\n * - 首行缩进 N 字符: the item's first line is indented by the preset's\n * `firstLineIndentChars`, written as `w:firstLineChars` so Word shows it in\n * characters and it scales with the font size.\n * - 编号与内容的间距 适中: `w:suff` is `space`, so one space separates the\n * number or bullet from its content instead of a tab.\n * - 文本之前: ordered levels sit flush with the text block at every level, the\n * way a printed 公文 numbers its items (1. (1) ① all start from the same\n * margin). Bulleted levels instead step out by the preset's indent each\n * level, because a bullet carries no hierarchy of its own.\n * - one bullet per nesting level, ● then ○ then ▪.\n *\n * Numbering itself is left alone: ordered levels keep the generator's\n * `%1.` / `%2.` text. The level's tab stop stays where it is, so a renderer\n * that ignores `w:suff` still puts the content near the indent rather than on\n * top of the mark.\n */\nexport function patchNumberingXml(\n numberingXml: string,\n preset: FontPreset\n): string {\n const dom = new DOMParser().parseFromString(numberingXml, 'application/xml');\n const indentChars = preset.paragraph.firstLineIndentChars ?? 0;\n const bullets = preset.list?.bullets ?? [];\n\n for (const lvl of Array.from(dom.getElementsByTagNameNS(W_NS, 'lvl'))) {\n const format = children(lvl).find((child) => child.localName === 'numFmt');\n const bulleted = format?.getAttributeNS(W_NS, 'val') === 'bullet';\n const level = Number(lvl.getAttributeNS(W_NS, 'ilvl') ?? '0');\n // Only bullets nest by indentation; numbering text already shows the level.\n const indentLevel = bulleted ? level : 0;\n\n setNumberSeparator(lvl);\n\n const ind = childOrCreate(numberingParagraphOf(lvl), 'ind', 'last');\n for (const attribute of ['hanging', 'hangingChars', 'firstLine']) {\n ind.removeAttributeNS(W_NS, attribute);\n }\n // One character is the body font size in twips, which is what a renderer\n // that ignores the `*Chars` attributes needs alongside them.\n ind.setAttributeNS(\n W_NS,\n 'w:left',\n String(indentLevel * indentChars * preset.body.sizePt * 20)\n );\n ind.setAttributeNS(\n W_NS,\n 'w:leftChars',\n String(indentLevel * indentChars * 100)\n );\n ind.setAttributeNS(W_NS, 'w:firstLineChars', String(indentChars * 100));\n\n if (bulleted && bullets.length) {\n setBulletGlyph(lvl, level, bullets, preset.body.eastAsia);\n } else if (!bulleted && preset.list?.multilevelNumbers) {\n setMultilevelNumber(lvl, level);\n }\n }\n\n return keepXmlDeclaration(\n numberingXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\n/**\n * Gives each nesting level its own bullet, as Word's multi-level library does.\n * The generator repeats one private-use glyph in the Symbol font at every\n * level, so the level's run properties move to the body font, which carries\n * these shapes.\n */\nfunction setBulletGlyph(\n lvl: Element,\n level: number,\n bullets: string[],\n font: string\n): void {\n const format = children(lvl).find((child) => child.localName === 'numFmt');\n if (format?.getAttributeNS(W_NS, 'val') !== 'bullet') {\n return;\n }\n\n const lvlText = children(lvl).find((child) => child.localName === 'lvlText');\n if (!lvlText) {\n return;\n }\n lvlText.setAttributeNS(\n W_NS,\n 'w:val',\n bullets[Math.min(level, bullets.length - 1)]\n );\n\n const rFonts = childOrCreate(\n childOrCreate(lvl, 'rPr', 'last'),\n 'rFonts',\n 'first'\n );\n for (const attribute of ['ascii', 'hAnsi', 'eastAsia', 'cs']) {\n rFonts.setAttributeNS(W_NS, `w:${attribute}`, font);\n }\n}\n\n/**\n * Makes a nested number carry its parents: level 0 stays `1.`, level 1 becomes\n * `1.1`, level 2 `1.1.1`. Word restarts a level whenever the one above it\n * moves, which is its default, so the second item of the third item reads 3.2.\n */\nfunction setMultilevelNumber(lvl: Element, level: number): void {\n const lvlText = children(lvl).find((child) => child.localName === 'lvlText');\n if (!lvlText) {\n return;\n }\n\n const parents = Array.from({ length: level }, (_, index) => `%${index + 1}`);\n lvlText.setAttributeNS(\n W_NS,\n 'w:val',\n [...parents, `%${level + 1}.`].join('.')\n );\n}\n\n/** `<w:suff>` sits between `<w:isLgl>` and `<w:lvlText>` in a level. */\nfunction setNumberSeparator(lvl: Element): void {\n const existing = children(lvl).find((child) => child.localName === 'suff');\n const suff = existing ?? lvl.ownerDocument.createElementNS(W_NS, 'w:suff');\n if (!existing) {\n const lvlText = children(lvl).find(\n (child) => child.localName === 'lvlText'\n );\n lvl.insertBefore(suff, lvlText ?? null);\n }\n suff.setAttributeNS(W_NS, 'w:val', 'space');\n}\n\n/** The paragraph properties a numbering level carries, created when absent. */\nfunction numberingParagraphOf(lvl: Element): Element {\n return childOrCreate(lvl, 'pPr', 'last');\n}\n\n/**\n * Cells sit outside the page grid: exact spacing at the line pitch would\n * stretch every row to a whole pitch and clip what wraps, so a cell paragraph\n * takes its own line spacing and stops snapping to the grid (Word's 如果定义了\n * 文档网格,则与网格对齐 checkbox, `w:snapToGrid`).\n */\nfunction layoutTableCell(\n pPr: Element,\n table: TableStyle,\n grid: Grid | null\n): void {\n const spacing = spacingFor(table.lineSpacing, grid);\n const spacingElement = paragraphProperty(pPr, 'spacing');\n spacingElement.setAttributeNS(W_NS, 'w:line', spacing.line);\n spacingElement.setAttributeNS(W_NS, 'w:lineRule', spacing.rule);\n\n paragraphProperty(pPr, 'snapToGrid').setAttributeNS(\n W_NS,\n 'w:val',\n table.snapToGrid ? '1' : '0'\n );\n}\n\n/** `<w:vAlign>` in a cell's properties, created where Word writes it. */\nfunction cellVerticalAlign(cell: Element): Element {\n const tcPr = childOrCreate(cell, 'tcPr', 'first');\n const existing = children(tcPr).find((child) => child.localName === 'vAlign');\n if (existing) {\n return existing;\n }\n const created = tcPr.ownerDocument.createElementNS(W_NS, 'w:vAlign');\n const hideMark = children(tcPr).find(\n (child) => child.localName === 'hideMark'\n );\n return tcPr.insertBefore(created, hideMark ?? null);\n}\n\n/**\n * The grid for the text block of `sectPr`'s page. Word stores the character\n * pitch as an offset from the body font size. Both pitches are rounded down,\n * as Word does, so the lines and characters always fit: for the page Word\n * itself sets up with GB/T 9704 margins, this reproduces its linePitch=\"579\"\n * and charSpace=\"-834\".\n */\nfunction measureGrid(\n sectPr: Element,\n {\n linesPerPage,\n charsPerLine,\n }: { linesPerPage: number; charsPerLine: number },\n bodySizePt: number\n): Grid {\n const pgSz = children(sectPr).find((child) => child.localName === 'pgSz');\n const pgMar = children(sectPr).find((child) => child.localName === 'pgMar');\n const twips = (element: Element | undefined, attribute: string): number => {\n const value = Number(element?.getAttributeNS(W_NS, attribute));\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(\n `Cannot apply font preset: section has no page ${attribute}`\n );\n }\n return value;\n };\n\n const textHeight =\n twips(pgSz, 'h') - twips(pgMar, 'top') - twips(pgMar, 'bottom');\n const textWidth =\n twips(pgSz, 'w') - twips(pgMar, 'left') - twips(pgMar, 'right');\n const charPitchPt = textWidth / 20 / charsPerLine;\n\n return {\n linePitch: Math.floor(textHeight / linesPerPage),\n charSpace: Math.floor((charPitchPt - bodySizePt) * 4096),\n };\n}\n\nfunction setDocGrid(sectPr: Element, grid: Grid): void {\n let docGrid = children(sectPr).find((child) => child.localName === 'docGrid');\n if (!docGrid) {\n docGrid = sectPr.ownerDocument.createElementNS(W_NS, 'w:docGrid');\n // <w:docGrid> is the last section property but <w:printerSettings>.\n const printerSettings = children(sectPr).find(\n (child) => child.localName === 'printerSettings'\n );\n sectPr.insertBefore(docGrid, printerSettings ?? null);\n }\n docGrid.setAttributeNS(W_NS, 'w:type', 'linesAndChars');\n docGrid.setAttributeNS(W_NS, 'w:linePitch', String(grid.linePitch));\n docGrid.setAttributeNS(W_NS, 'w:charSpace', String(grid.charSpace));\n}\n\nfunction isInTableCell(paragraph: Element): boolean {\n for (let node = paragraph.parentElement; node; node = node.parentElement) {\n if (node.namespaceURI === W_NS && node.localName === 'tc') {\n return true;\n }\n }\n return false;\n}\n\nfunction removeFirstLineIndent(pPr: Element): void {\n const ind = paragraphProperty(pPr, 'ind');\n if (!ind.hasAttributeNS(W_NS, 'hanging')) {\n ind.setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n}\n\n/** A paragraph's `<w:pPr>`, created as its first child if missing. */\nfunction pPrOf(paragraph: Element): Element {\n return childOrCreate(paragraph, 'pPr', 'first');\n}\n\nfunction applyLevelStyle(\n scope: Element,\n style: LevelStyle,\n paragraph: ParagraphStyle,\n layout: Layout\n): void {\n const rPr = runPropertiesOf(scope);\n\n const rFonts = childOrCreate(rPr, 'rFonts', 'first');\n for (const attribute of THEME_FONT_ATTRIBUTES) {\n rFonts.removeAttributeNS(W_NS, attribute);\n }\n rFonts.setAttributeNS(W_NS, 'w:ascii', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:hAnsi', style.latin);\n rFonts.setAttributeNS(W_NS, 'w:eastAsia', style.eastAsia);\n\n for (const child of children(rPr)) {\n if (child.localName === 'b' || child.localName === 'bCs') {\n child.remove();\n }\n }\n if (style.bold) {\n rPr.insertBefore(\n rPr.ownerDocument.createElementNS(W_NS, 'w:b'),\n rFonts.nextSibling\n );\n }\n\n // <w:sz> is measured in half points.\n const size = String(style.sizePt * 2);\n childOrCreate(rPr, 'sz', 'last').setAttributeNS(W_NS, 'w:val', size);\n childOrCreate(rPr, 'szCs', 'last').setAttributeNS(W_NS, 'w:val', size);\n\n const pPr = paragraphPropertiesOf(scope);\n const spacing = paragraphProperty(pPr, 'spacing');\n spacing.setAttributeNS(W_NS, 'w:before', String(paragraph.beforePt * 20));\n spacing.setAttributeNS(W_NS, 'w:after', String(paragraph.afterPt * 20));\n spacing.setAttributeNS(W_NS, 'w:line', layout.spacing.line);\n spacing.setAttributeNS(W_NS, 'w:lineRule', layout.spacing.rule);\n\n if (style.centered) {\n // An indented first line would push a centered title off center.\n if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(W_NS, 'w:firstLine', '0');\n }\n paragraphProperty(pPr, 'jc').setAttributeNS(W_NS, 'w:val', 'center');\n } else if (layout.firstLineIndent) {\n paragraphProperty(pPr, 'ind').setAttributeNS(\n W_NS,\n 'w:firstLine',\n String(layout.firstLineIndent)\n );\n }\n}\n\nfunction runPropertiesOf(parent: Element): Element {\n const container =\n parent.localName === 'docDefaults'\n ? childOrCreate(parent, 'rPrDefault', 'first')\n : parent;\n // In a <w:style> the run properties go last, after any <w:pPr>.\n return childOrCreate(container, 'rPr', 'last');\n}\n\nfunction paragraphPropertiesOf(parent: Element): Element {\n if (parent.localName === 'docDefaults') {\n const pPrDefault = childOrCreate(parent, 'pPrDefault', 'last');\n return childOrCreate(pPrDefault, 'pPr', 'first');\n }\n\n const existing = children(parent).find((child) => child.localName === 'pPr');\n if (existing) {\n return existing;\n }\n // In a <w:style> the paragraph properties go before the run properties.\n const created = parent.ownerDocument.createElementNS(W_NS, 'w:pPr');\n return parent.insertBefore(created, runPropertiesOf(parent));\n}\n\nfunction children(element: Element): Element[] {\n return Array.from(element.children).filter(\n (child) => child.namespaceURI === W_NS\n );\n}\n\nfunction childOrCreate(\n parent: Element,\n localName: string,\n position: 'first' | 'last'\n): Element {\n const existing = children(parent).find(\n (child) => child.localName === localName\n );\n if (existing) {\n return existing;\n }\n const created = parent.ownerDocument.createElementNS(W_NS, `w:${localName}`);\n return position === 'first'\n ? parent.insertBefore(created, parent.firstChild)\n : parent.appendChild(created);\n}\n\nfunction requireElement(dom: Document, localName: string): Element {\n const element = dom.getElementsByTagNameNS(W_NS, localName)[0];\n if (!element) {\n throw new Error(\n `Cannot apply font preset: styles.xml has no <w:${localName}> element`\n );\n }\n return element;\n}\n"]}
@@ -18,17 +18,25 @@ export declare const RULE_TEXT = "* * *";
18
18
  * the same. Each becomes a ☒ or ☐ character.
19
19
  * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span
20
20
  * naming the code block font, which the generator does carry over.
21
- * - Table header cells: `<th>` isn't bold, so its content is wrapped in
22
- * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but
23
- * the same value as a `text-align` style is honored.
21
+ * - Table cells: the generator makes each inline child of a cell its own
22
+ * paragraph, so `**bold** text` would read as two lines. Each run of
23
+ * inline content is wrapped in one `<p>`. `<th>` isn't bold, so its
24
+ * content is wrapped in `<strong>`. Column alignment from GFM's `align`
25
+ * attribute is ignored, but the same value as a `text-align` style is
26
+ * honored.
24
27
  * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT
25
28
  * paragraph for the structure patch to draw as a rule.
26
29
  * - Block quotes: the generator joins everything in a `<blockquote>` into one
27
30
  * justified paragraph. Its paragraphs and headings are kept apart instead,
28
31
  * left aligned and indented one step per level of nesting.
29
- * - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their
30
- * text is dropped, so each is replaced by a span or `<em>` (see
31
- * UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.
32
+ * - Elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, `<my-element>`,
33
+ * ...): the generator drops their text, so this keeps it. Some are
34
+ * replaced by a span or `<em>` (see UNKNOWN_INLINE), the rest by their
35
+ * children; content a browser wouldn't show as text (HIDDEN_CONTENT) is
36
+ * left for the generator to drop. A placeholder like `<your-name>` that's
37
+ * never closed isn't markup at all, so it stays as literal text, spelled
38
+ * as in the source. `<mark>` loses its highlight, so it's set as a
39
+ * shading.
32
40
  * - Footnotes: the reference and back links point into the page, which a
33
41
  * Word reader can't follow, so references keep only their number and the
34
42
  * back links (↩) go. So does the footnotes heading, which the page only
@@ -26,8 +26,9 @@ const QUOTE_INDENT_INCHES = 0.5;
26
26
  const QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
27
27
  /**
28
28
  * Inline elements the generator doesn't know, whose text it drops. Each is
29
- * replaced by what a browser shows: a span (in the code font, for the ones a
30
- * browser draws in monospace), emphasis, or quotation marks.
29
+ * replaced by what a browser shows: a span in the code font (for the ones a
30
+ * browser draws in monospace), emphasis, or quotation marks. Other unknown
31
+ * elements are unwrapped (see GENERATOR_ELEMENTS).
31
32
  */
32
33
  const UNKNOWN_INLINE = {
33
34
  kbd: 'code',
@@ -37,21 +38,46 @@ const UNKNOWN_INLINE = {
37
38
  cite: 'em',
38
39
  dfn: 'em',
39
40
  q: 'quote',
40
- abbr: 'text',
41
- acronym: 'text',
42
- bdi: 'text',
43
- bdo: 'text',
44
- big: 'text',
45
- data: 'text',
46
- font: 'text',
47
- label: 'text',
48
- small: 'text',
49
- time: 'text',
50
41
  };
42
+ /**
43
+ * Elements the generator keeps the text of (each checked against it), or
44
+ * that a later step here rewrites (`hr`, `mark`, `input`). Any other element
45
+ * in a paragraph loses its text, so it's replaced by its children: an
46
+ * allowlist, because a list of the ones it drops (`<abbr>`, `<small>`, a
47
+ * custom `<my-element>`, ...) is never complete.
48
+ */
49
+ const GENERATOR_ELEMENTS = new Set([
50
+ ...['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'section', 'pre'],
51
+ ...['ul', 'ol', 'li', 'blockquote', 'hr', 'br', 'img', 'input'],
52
+ ...['table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'colgroup', 'col'],
53
+ ...['a', 'span', 'code', 'strong', 'b', 'em', 'i', 'u', 's', 'del'],
54
+ ...['strike', 'ins', 'sub', 'sup', 'mark', 'caption', 'figcaption'],
55
+ ...['article', 'aside', 'header', 'footer', 'main', 'nav', 'address'],
56
+ ...['hgroup', 'dl', 'dt', 'dd', 'details', 'summary', 'fieldset', 'legend'],
57
+ ]);
58
+ /**
59
+ * Elements whose content isn't prose: code, fallbacks a browser hides, and
60
+ * drawings. The generator drops them, which is right; unwrapping them would
61
+ * put a script, or an SVG's or formula's bare parts, in the document.
62
+ */
63
+ const HIDDEN_CONTENT = new Set([
64
+ ...['script', 'style', 'template', 'noscript', 'iframe', 'object'],
65
+ ...['video', 'audio', 'canvas', 'svg', 'math'],
66
+ ]);
51
67
  /** `Node.TEXT_NODE`, which Node's globals lack. */
52
68
  const TEXT_NODE = 3;
53
69
  /** The highlight browsers give `<mark>`; the generator drops it. */
54
70
  const MARK_COLOR = '#FFFF00';
71
+ /** `Node.ELEMENT_NODE`, which Node's globals lack too. */
72
+ const ELEMENT_NODE = 1;
73
+ /**
74
+ * Elements that start their own paragraph in a table cell. Anything else is
75
+ * inline, and a run of it is kept together in one paragraph.
76
+ */
77
+ const CELL_BLOCKS = new Set([
78
+ ...['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'pre', 'blockquote'],
79
+ ...['ul', 'ol', 'table', 'hr', 'section'],
80
+ ]);
55
81
  /**
56
82
  * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of
57
83
  * what the browser preview renders:
@@ -60,17 +86,25 @@ const MARK_COLOR = '#FFFF00';
60
86
  * the same. Each becomes a ☒ or ☐ character.
61
87
  * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span
62
88
  * naming the code block font, which the generator does carry over.
63
- * - Table header cells: `<th>` isn't bold, so its content is wrapped in
64
- * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but
65
- * the same value as a `text-align` style is honored.
89
+ * - Table cells: the generator makes each inline child of a cell its own
90
+ * paragraph, so `**bold** text` would read as two lines. Each run of
91
+ * inline content is wrapped in one `<p>`. `<th>` isn't bold, so its
92
+ * content is wrapped in `<strong>`. Column alignment from GFM's `align`
93
+ * attribute is ignored, but the same value as a `text-align` style is
94
+ * honored.
66
95
  * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT
67
96
  * paragraph for the structure patch to draw as a rule.
68
97
  * - Block quotes: the generator joins everything in a `<blockquote>` into one
69
98
  * justified paragraph. Its paragraphs and headings are kept apart instead,
70
99
  * left aligned and indented one step per level of nesting.
71
- * - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their
72
- * text is dropped, so each is replaced by a span or `<em>` (see
73
- * UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.
100
+ * - Elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, `<my-element>`,
101
+ * ...): the generator drops their text, so this keeps it. Some are
102
+ * replaced by a span or `<em>` (see UNKNOWN_INLINE), the rest by their
103
+ * children; content a browser wouldn't show as text (HIDDEN_CONTENT) is
104
+ * left for the generator to drop. A placeholder like `<your-name>` that's
105
+ * never closed isn't markup at all, so it stays as literal text, spelled
106
+ * as in the source. `<mark>` loses its highlight, so it's set as a
107
+ * shading.
74
108
  * - Footnotes: the reference and back links point into the page, which a
75
109
  * Word reader can't follow, so references keep only their number and the
76
110
  * back links (↩) go. So does the footnotes heading, which the page only
@@ -106,16 +140,32 @@ export function prepareHtmlForDocx(html) {
106
140
  strong.append(...Array.from(cell.childNodes));
107
141
  cell.append(strong);
108
142
  }
143
+ wrapInlineRuns(cell);
109
144
  }
110
145
  for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {
111
146
  // Outermost first; each one unwraps its nested quotes as it goes.
112
147
  if (quote.isConnected)
113
148
  unwrapQuote(quote, 1);
114
149
  }
115
- for (const element of Array.from(dom.body.querySelectorAll('*'))) {
116
- const kind = UNKNOWN_INLINE[element.localName];
117
- if (!kind || element.closest('pre'))
150
+ const elements = Array.from(dom.body.querySelectorAll('*'));
151
+ const startTags = new SourceStartTags(html, elements);
152
+ for (const element of elements) {
153
+ const name = element.localName;
154
+ if (GENERATOR_ELEMENTS.has(name) || element.closest('pre'))
155
+ continue;
156
+ if (HIDDEN_CONTENT.has(name) || element.closest('svg, math'))
118
157
  continue;
158
+ const kind = UNKNOWN_INLINE[name];
159
+ if (!kind) {
160
+ const children = Array.from(element.childNodes);
161
+ if (isUnclosedPlaceholder(element, html)) {
162
+ element.replaceWith(startTags.of(element), ...children);
163
+ }
164
+ else {
165
+ element.replaceWith(...children);
166
+ }
167
+ continue;
168
+ }
119
169
  if (kind === 'quote') {
120
170
  element.replaceWith('“', ...Array.from(element.childNodes), '”');
121
171
  continue;
@@ -154,6 +204,36 @@ export function prepareHtmlForDocx(html) {
154
204
  // Only inside tags: text can't contain a raw `<`, so it's never touched.
155
205
  return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) => tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style='));
156
206
  }
207
+ /**
208
+ * Wraps each run of `cell`'s inline children (text, links, emphasis, `<br>`)
209
+ * in a `<p>`, which the generator keeps as one paragraph. Whitespace-only runs
210
+ * are left alone, so an empty cell stays empty.
211
+ */
212
+ function wrapInlineRuns(cell) {
213
+ const document = cell.ownerDocument;
214
+ let run = [];
215
+ const flush = (before) => {
216
+ const hasContent = run.some((node) => node.nodeType === ELEMENT_NODE ||
217
+ (node.nodeType === TEXT_NODE && node.textContent?.trim()));
218
+ if (hasContent) {
219
+ const paragraph = document.createElement('p');
220
+ cell.insertBefore(paragraph, before);
221
+ paragraph.append(...run);
222
+ }
223
+ run = [];
224
+ };
225
+ for (const child of Array.from(cell.childNodes)) {
226
+ const isBlock = child.nodeType === ELEMENT_NODE &&
227
+ CELL_BLOCKS.has(child.localName);
228
+ if (isBlock) {
229
+ flush(child);
230
+ }
231
+ else {
232
+ run.push(child);
233
+ }
234
+ }
235
+ flush(null);
236
+ }
157
237
  /**
158
238
  * Replaces `quote` with its children, indenting its paragraphs and headings
159
239
  * `depth` steps. Other blocks (lists, code, tables) keep their own layout, and
@@ -177,4 +257,60 @@ function unwrapQuote(quote, depth) {
177
257
  }
178
258
  quote.replaceWith(...Array.from(quote.childNodes));
179
259
  }
260
+ /**
261
+ * Whether `element` is a made-up tag, like `<your-name>`, that `html` never
262
+ * closes: a placeholder meant to be read, which a browser would hide.
263
+ */
264
+ function isUnclosedPlaceholder(element, html) {
265
+ const isMadeUp = element.localName.includes('-') ||
266
+ Object.prototype.toString.call(element) === '[object HTMLUnknownElement]';
267
+ return isMadeUp && !html.toLowerCase().includes(`</${element.localName}`);
268
+ }
269
+ /**
270
+ * Each element's start tag as written in the source, so a placeholder shown
271
+ * as text keeps its exact spelling (case, quotes, entities). The DOM only
272
+ * has decoded attribute values, which can't say whether the source wrote
273
+ * `&` or `&amp;`.
274
+ */
275
+ class SourceStartTags {
276
+ html;
277
+ ordinals = new Map();
278
+ counts = new Map();
279
+ tags = new Map();
280
+ constructor(html, elements) {
281
+ this.html = html;
282
+ // Document order is source order of start tags, so the nth <x> element
283
+ // is the nth `<x` in the source.
284
+ for (const element of elements) {
285
+ const count = this.counts.get(element.localName) ?? 0;
286
+ this.ordinals.set(element, count);
287
+ this.counts.set(element.localName, count + 1);
288
+ }
289
+ }
290
+ of(element) {
291
+ const name = element.localName;
292
+ let tags = this.tags.get(name);
293
+ if (!tags) {
294
+ // Quoted values may hold `>`. Each alternative starts with a different
295
+ // character, so this can't backtrack.
296
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
297
+ const startTag = new RegExp(`<${escaped}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^'">])*>`, 'gi');
298
+ tags = this.html.match(startTag) ?? [];
299
+ this.tags.set(name, tags);
300
+ }
301
+ // A mismatch means a `<x` the parser didn't turn into an element (in a
302
+ // comment, say), so the ordinal can't be trusted: rebuild the tag.
303
+ const tag = tags.length === this.counts.get(name)
304
+ ? tags[this.ordinals.get(element) ?? -1]
305
+ : undefined;
306
+ return tag ?? rebuiltStartTag(element);
307
+ }
308
+ }
309
+ /** A start tag for `element` rebuilt from the DOM. */
310
+ function rebuiltStartTag(element) {
311
+ const attributes = Array.from(element.attributes)
312
+ .map(({ name, value }) => (value ? ` ${name}="${value}"` : ` ${name}`))
313
+ .join('');
314
+ return `<${element.localName}${attributes}>`;
315
+ }
180
316
  //# sourceMappingURL=docx-html.js.map
@@ -1 +1 @@
1
- {"version":3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AAK,GAAG,KAAK,CAAC,YAAY,CAAC,iBAAiB,CAAC,CAAC;YACpD,KAAK,CAAC,YAAY,CAChB,iBAAiB,EACjB,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CACvC,CAAC;QACJ,CAAC;IACH,CAAC;IACD,KAAK,CAAC,WAAW,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * A monospace face that ships with Windows, so Chinese comments stay aligned.\n * Defined here rather than in the code block patch so the main bundle can use\n * it without loading that patch and JSZip.\n */\nexport const CODE_FONT = 'Courier New';\n\n/** What Word shows in place of a task list checkbox, which it can't render. */\nconst CHECKBOX = { checked: '☒', unchecked: '☐' };\n\n/**\n * Stands in for `<hr>`, which the generator drops. The structure patch turns\n * each one into a bordered paragraph; if that patch fails, a centered `* * *`\n * still reads as a section break.\n */\nexport const RULE_TEXT = '* * *';\n\n/**\n * Stands in for `style` while the HTML is a live DOM. The page's CSP applies\n * to DOMParser documents too, and blocks (and reports) `style` attributes set\n * there. (CSSOM is allowed, but it quotes a font name with a space, which the\n * generator would read as part of the name.) Renamed back to `style` in the\n * serialized tags, where the CSP doesn't reach.\n */\nconst STYLE_PLACEHOLDER = 'data-docx-style';\n\n/** How far each level of block quote is indented. */\nconst QUOTE_INDENT_INCHES = 0.5;\n\n/** Block quote children that become indented paragraphs. */\nconst QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/**\n * Inline elements the generator doesn't know, whose text it drops. Each is\n * replaced by what a browser shows: a span (in the code font, for the ones a\n * browser draws in monospace), emphasis, or quotation marks.\n */\nconst UNKNOWN_INLINE: Record<string, 'code' | 'em' | 'quote' | 'text'> = {\n kbd: 'code',\n samp: 'code',\n tt: 'code',\n var: 'em',\n cite: 'em',\n dfn: 'em',\n q: 'quote',\n abbr: 'text',\n acronym: 'text',\n bdi: 'text',\n bdo: 'text',\n big: 'text',\n data: 'text',\n font: 'text',\n label: 'text',\n small: 'text',\n time: 'text',\n};\n\n/** `Node.TEXT_NODE`, which Node's globals lack. */\nconst TEXT_NODE = 3;\n\n/** The highlight browsers give `<mark>`; the generator drops it. */\nconst MARK_COLOR = '#FFFF00';\n\n/**\n * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of\n * what the browser preview renders:\n *\n * - Task list checkboxes: `<input>` is dropped, so done and pending items read\n * the same. Each becomes a ☒ or ☐ character.\n * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span\n * naming the code block font, which the generator does carry over.\n * - Table header cells: `<th>` isn't bold, so its content is wrapped in\n * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but\n * the same value as a `text-align` style is honored.\n * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT\n * paragraph for the structure patch to draw as a rule.\n * - Block quotes: the generator joins everything in a `<blockquote>` into one\n * justified paragraph. Its paragraphs and headings are kept apart instead,\n * left aligned and indented one step per level of nesting.\n * - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their\n * text is dropped, so each is replaced by a span or `<em>` (see\n * UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.\n * - Footnotes: the reference and back links point into the page, which a\n * Word reader can't follow, so references keep only their number and the\n * back links (↩) go. So does the footnotes heading, which the page only\n * shows to screen readers.\n *\n * Only the HTML bound for the .docx changes; the preview keeps the original.\n */\nexport function prepareHtmlForDocx(html: string): string {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n\n for (const input of Array.from(\n dom.querySelectorAll('input[type=\"checkbox\"]')\n )) {\n const box = input.hasAttribute('checked')\n ? CHECKBOX.checked\n : CHECKBOX.unchecked;\n input.replaceWith(dom.createTextNode(box));\n }\n\n for (const code of Array.from(dom.querySelectorAll('code'))) {\n if (code.closest('pre')) continue;\n const span = dom.createElement('span');\n // A raw attribute, not `style.fontFamily`: see STYLE_PLACEHOLDER.\n span.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n span.append(...Array.from(code.childNodes));\n code.append(span);\n }\n\n for (const cell of Array.from(dom.querySelectorAll('th, td'))) {\n const align = cell.getAttribute('align');\n if (align) {\n (cell as HTMLElement).style.textAlign = align;\n cell.removeAttribute('align');\n }\n if (cell.localName === 'th' && cell.textContent?.trim()) {\n const strong = dom.createElement('strong');\n strong.append(...Array.from(cell.childNodes));\n cell.append(strong);\n }\n }\n\n for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {\n // Outermost first; each one unwraps its nested quotes as it goes.\n if (quote.isConnected) unwrapQuote(quote, 1);\n }\n\n for (const element of Array.from(dom.body.querySelectorAll('*'))) {\n const kind = UNKNOWN_INLINE[element.localName];\n if (!kind || element.closest('pre')) continue;\n if (kind === 'quote') {\n element.replaceWith('“', ...Array.from(element.childNodes), '”');\n continue;\n }\n const replacement = dom.createElement(kind === 'em' ? 'em' : 'span');\n if (kind === 'code') {\n replacement.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n }\n replacement.append(...Array.from(element.childNodes));\n element.replaceWith(replacement);\n }\n\n for (const mark of Array.from(dom.querySelectorAll('mark'))) {\n const span = dom.createElement('span');\n span.setAttribute(STYLE_PLACEHOLDER, `background-color: ${MARK_COLOR}`);\n span.append(...Array.from(mark.childNodes));\n mark.replaceWith(span);\n }\n\n for (const reference of Array.from(\n dom.querySelectorAll('a[data-footnote-ref]')\n )) {\n reference.replaceWith(...Array.from(reference.childNodes));\n }\n for (const backReference of Array.from(\n dom.querySelectorAll('a[data-footnote-backref]')\n )) {\n // The space before it, too, so the note doesn't end in one.\n const before = backReference.previousSibling;\n if (before?.nodeType === TEXT_NODE && before.textContent?.endsWith(' ')) {\n before.textContent = before.textContent.slice(0, -1);\n }\n backReference.remove();\n }\n dom.querySelector('section[data-footnotes] > h2')?.remove();\n\n for (const rule of Array.from(dom.querySelectorAll('hr'))) {\n const paragraph = dom.createElement('p');\n paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');\n paragraph.textContent = RULE_TEXT;\n rule.replaceWith(paragraph);\n }\n\n // Only inside tags: text can't contain a raw `<`, so it's never touched.\n return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) =>\n tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style=')\n );\n}\n\n/**\n * Replaces `quote` with its children, indenting its paragraphs and headings\n * `depth` steps. Other blocks (lists, code, tables) keep their own layout, and\n * so does a quote in a list item: the generator indents that paragraph for the\n * list already, and a second indent would be invalid or move the bullet.\n */\nfunction unwrapQuote(quote: Element, depth: number): void {\n const inList = quote.closest('li') !== null;\n for (const child of Array.from(quote.children)) {\n if (child.localName === 'blockquote') {\n unwrapQuote(child, depth + 1);\n } else if (QUOTE_PARAGRAPHS.has(child.localName)) {\n const align = 'text-align: left';\n const layout = inList\n ? align\n : `margin-left: ${depth * QUOTE_INDENT_INCHES}in; ${align}`;\n const style = child.getAttribute(STYLE_PLACEHOLDER);\n child.setAttribute(\n STYLE_PLACEHOLDER,\n style ? `${style}; ${layout}` : layout\n );\n }\n }\n quote.replaceWith(...Array.from(quote.childNodes));\n}\n"]}
1
+ {"version":3,"file":"docx-html.js","sourceRoot":"","sources":["../src/docx-html.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,aAAa,CAAC;AAEvC,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;AAElD;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC;AAEjC;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAE5C,qDAAqD;AACrD,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,4DAA4D;AAC5D,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,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,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,KAAK,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;SACtE,IAAI,CAAC,EAAE,CAAC,CAAC;IACZ,OAAO,IAAI,OAAO,CAAC,SAAS,GAAG,UAAU,GAAG,CAAC;AAC/C,CAAC","sourcesContent":["/**\n * A monospace face that ships with Windows, so Chinese comments stay aligned.\n * Defined here rather than in the code block patch so the main bundle can use\n * it without loading that patch and JSZip.\n */\nexport const CODE_FONT = 'Courier New';\n\n/** What Word shows in place of a task list checkbox, which it can't render. */\nconst CHECKBOX = { checked: '☒', unchecked: '☐' };\n\n/**\n * Stands in for `<hr>`, which the generator drops. The structure patch turns\n * each one into a bordered paragraph; if that patch fails, a centered `* * *`\n * still reads as a section break.\n */\nexport const RULE_TEXT = '* * *';\n\n/**\n * Stands in for `style` while the HTML is a live DOM. The page's CSP applies\n * to DOMParser documents too, and blocks (and reports) `style` attributes set\n * there. (CSSOM is allowed, but it quotes a font name with a space, which the\n * generator would read as part of the name.) Renamed back to `style` in the\n * serialized tags, where the CSP doesn't reach.\n */\nconst STYLE_PLACEHOLDER = 'data-docx-style';\n\n/** How far each level of block quote is indented. */\nconst QUOTE_INDENT_INCHES = 0.5;\n\n/** Block quote children that become indented paragraphs. */\nconst QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/**\n * Inline elements the generator doesn't know, whose text it drops. Each is\n * replaced by what a browser shows: a span in the code font (for the ones a\n * browser draws in monospace), emphasis, or quotation marks. Other unknown\n * elements are unwrapped (see GENERATOR_ELEMENTS).\n */\nconst UNKNOWN_INLINE: Record<string, 'code' | 'em' | 'quote'> = {\n kbd: 'code',\n samp: 'code',\n tt: 'code',\n var: 'em',\n cite: 'em',\n dfn: 'em',\n q: 'quote',\n};\n\n/**\n * Elements the generator keeps the text of (each checked against it), or\n * that a later step here rewrites (`hr`, `mark`, `input`). Any other element\n * in a paragraph loses its text, so it's replaced by its children: an\n * allowlist, because a list of the ones it drops (`<abbr>`, `<small>`, a\n * custom `<my-element>`, ...) is never complete.\n */\nconst GENERATOR_ELEMENTS = new Set([\n ...['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'section', 'pre'],\n ...['ul', 'ol', 'li', 'blockquote', 'hr', 'br', 'img', 'input'],\n ...['table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'colgroup', 'col'],\n ...['a', 'span', 'code', 'strong', 'b', 'em', 'i', 'u', 's', 'del'],\n ...['strike', 'ins', 'sub', 'sup', 'mark', 'caption', 'figcaption'],\n ...['article', 'aside', 'header', 'footer', 'main', 'nav', 'address'],\n ...['hgroup', 'dl', 'dt', 'dd', 'details', 'summary', 'fieldset', 'legend'],\n]);\n\n/**\n * Elements whose content isn't prose: code, fallbacks a browser hides, and\n * drawings. The generator drops them, which is right; unwrapping them would\n * put a script, or an SVG's or formula's bare parts, in the document.\n */\nconst HIDDEN_CONTENT = new Set([\n ...['script', 'style', 'template', 'noscript', 'iframe', 'object'],\n ...['video', 'audio', 'canvas', 'svg', 'math'],\n]);\n\n/** `Node.TEXT_NODE`, which Node's globals lack. */\nconst TEXT_NODE = 3;\n\n/** The highlight browsers give `<mark>`; the generator drops it. */\nconst MARK_COLOR = '#FFFF00';\n\n/** `Node.ELEMENT_NODE`, which Node's globals lack too. */\nconst ELEMENT_NODE = 1;\n\n/**\n * Elements that start their own paragraph in a table cell. Anything else is\n * inline, and a run of it is kept together in one paragraph.\n */\nconst CELL_BLOCKS = new Set([\n ...['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'pre', 'blockquote'],\n ...['ul', 'ol', 'table', 'hr', 'section'],\n]);\n\n/**\n * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of\n * what the browser preview renders:\n *\n * - Task list checkboxes: `<input>` is dropped, so done and pending items read\n * the same. Each becomes a ☒ or ☐ character.\n * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span\n * naming the code block font, which the generator does carry over.\n * - Table cells: the generator makes each inline child of a cell its own\n * paragraph, so `**bold** text` would read as two lines. Each run of\n * inline content is wrapped in one `<p>`. `<th>` isn't bold, so its\n * content is wrapped in `<strong>`. Column alignment from GFM's `align`\n * attribute is ignored, but the same value as a `text-align` style is\n * honored.\n * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT\n * paragraph for the structure patch to draw as a rule.\n * - Block quotes: the generator joins everything in a `<blockquote>` into one\n * justified paragraph. Its paragraphs and headings are kept apart instead,\n * left aligned and indented one step per level of nesting.\n * - Elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, `<my-element>`,\n * ...): the generator drops their text, so this keeps it. Some are\n * replaced by a span or `<em>` (see UNKNOWN_INLINE), the rest by their\n * children; content a browser wouldn't show as text (HIDDEN_CONTENT) is\n * left for the generator to drop. A placeholder like `<your-name>` that's\n * never closed isn't markup at all, so it stays as literal text, spelled\n * as in the source. `<mark>` loses its highlight, so it's set as a\n * shading.\n * - Footnotes: the reference and back links point into the page, which a\n * Word reader can't follow, so references keep only their number and the\n * back links (↩) go. So does the footnotes heading, which the page only\n * shows to screen readers.\n *\n * Only the HTML bound for the .docx changes; the preview keeps the original.\n */\nexport function prepareHtmlForDocx(html: string): string {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n\n for (const input of Array.from(\n dom.querySelectorAll('input[type=\"checkbox\"]')\n )) {\n const box = input.hasAttribute('checked')\n ? CHECKBOX.checked\n : CHECKBOX.unchecked;\n input.replaceWith(dom.createTextNode(box));\n }\n\n for (const code of Array.from(dom.querySelectorAll('code'))) {\n if (code.closest('pre')) continue;\n const span = dom.createElement('span');\n // A raw attribute, not `style.fontFamily`: see STYLE_PLACEHOLDER.\n span.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n span.append(...Array.from(code.childNodes));\n code.append(span);\n }\n\n for (const cell of Array.from(dom.querySelectorAll('th, td'))) {\n const align = cell.getAttribute('align');\n if (align) {\n (cell as HTMLElement).style.textAlign = align;\n cell.removeAttribute('align');\n }\n if (cell.localName === 'th' && cell.textContent?.trim()) {\n const strong = dom.createElement('strong');\n strong.append(...Array.from(cell.childNodes));\n cell.append(strong);\n }\n wrapInlineRuns(cell);\n }\n\n for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {\n // Outermost first; each one unwraps its nested quotes as it goes.\n if (quote.isConnected) unwrapQuote(quote, 1);\n }\n\n const elements = Array.from(dom.body.querySelectorAll('*'));\n const startTags = new SourceStartTags(html, elements);\n for (const element of elements) {\n const name = element.localName;\n if (GENERATOR_ELEMENTS.has(name) || element.closest('pre')) continue;\n if (HIDDEN_CONTENT.has(name) || element.closest('svg, math')) continue;\n const kind = UNKNOWN_INLINE[name];\n if (!kind) {\n const children = Array.from(element.childNodes);\n if (isUnclosedPlaceholder(element, html)) {\n element.replaceWith(startTags.of(element), ...children);\n } else {\n element.replaceWith(...children);\n }\n continue;\n }\n if (kind === 'quote') {\n element.replaceWith('“', ...Array.from(element.childNodes), '”');\n continue;\n }\n const replacement = dom.createElement(kind === 'em' ? 'em' : 'span');\n if (kind === 'code') {\n replacement.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n }\n replacement.append(...Array.from(element.childNodes));\n element.replaceWith(replacement);\n }\n\n for (const mark of Array.from(dom.querySelectorAll('mark'))) {\n const span = dom.createElement('span');\n span.setAttribute(STYLE_PLACEHOLDER, `background-color: ${MARK_COLOR}`);\n span.append(...Array.from(mark.childNodes));\n mark.replaceWith(span);\n }\n\n for (const reference of Array.from(\n dom.querySelectorAll('a[data-footnote-ref]')\n )) {\n reference.replaceWith(...Array.from(reference.childNodes));\n }\n for (const backReference of Array.from(\n dom.querySelectorAll('a[data-footnote-backref]')\n )) {\n // The space before it, too, so the note doesn't end in one.\n const before = backReference.previousSibling;\n if (before?.nodeType === TEXT_NODE && before.textContent?.endsWith(' ')) {\n before.textContent = before.textContent.slice(0, -1);\n }\n backReference.remove();\n }\n dom.querySelector('section[data-footnotes] > h2')?.remove();\n\n for (const rule of Array.from(dom.querySelectorAll('hr'))) {\n const paragraph = dom.createElement('p');\n paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');\n paragraph.textContent = RULE_TEXT;\n rule.replaceWith(paragraph);\n }\n\n // Only inside tags: text can't contain a raw `<`, so it's never touched.\n return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) =>\n tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style=')\n );\n}\n\n/**\n * Wraps each run of `cell`'s inline children (text, links, emphasis, `<br>`)\n * in a `<p>`, which the generator keeps as one paragraph. Whitespace-only runs\n * are left alone, so an empty cell stays empty.\n */\nfunction wrapInlineRuns(cell: Element): void {\n const document = cell.ownerDocument;\n let run: ChildNode[] = [];\n const flush = (before: ChildNode | null): void => {\n const hasContent = run.some(\n (node) =>\n node.nodeType === ELEMENT_NODE ||\n (node.nodeType === TEXT_NODE && node.textContent?.trim())\n );\n if (hasContent) {\n const paragraph = document.createElement('p');\n cell.insertBefore(paragraph, before);\n paragraph.append(...run);\n }\n run = [];\n };\n for (const child of Array.from(cell.childNodes)) {\n const isBlock =\n child.nodeType === ELEMENT_NODE &&\n CELL_BLOCKS.has((child as Element).localName);\n if (isBlock) {\n flush(child);\n } else {\n run.push(child);\n }\n }\n flush(null);\n}\n\n/**\n * Replaces `quote` with its children, indenting its paragraphs and headings\n * `depth` steps. Other blocks (lists, code, tables) keep their own layout, and\n * so does a quote in a list item: the generator indents that paragraph for the\n * list already, and a second indent would be invalid or move the bullet.\n */\nfunction unwrapQuote(quote: Element, depth: number): void {\n const inList = quote.closest('li') !== null;\n for (const child of Array.from(quote.children)) {\n if (child.localName === 'blockquote') {\n unwrapQuote(child, depth + 1);\n } else if (QUOTE_PARAGRAPHS.has(child.localName)) {\n const align = 'text-align: left';\n const layout = inList\n ? align\n : `margin-left: ${depth * QUOTE_INDENT_INCHES}in; ${align}`;\n const style = child.getAttribute(STYLE_PLACEHOLDER);\n child.setAttribute(\n STYLE_PLACEHOLDER,\n style ? `${style}; ${layout}` : layout\n );\n }\n }\n quote.replaceWith(...Array.from(quote.childNodes));\n}\n\n/**\n * Whether `element` is a made-up tag, like `<your-name>`, that `html` never\n * closes: a placeholder meant to be read, which a browser would hide.\n */\nfunction isUnclosedPlaceholder(element: Element, html: string): boolean {\n const isMadeUp =\n element.localName.includes('-') ||\n Object.prototype.toString.call(element) === '[object HTMLUnknownElement]';\n return isMadeUp && !html.toLowerCase().includes(`</${element.localName}`);\n}\n\n/**\n * Each element's start tag as written in the source, so a placeholder shown\n * as text keeps its exact spelling (case, quotes, entities). The DOM only\n * has decoded attribute values, which can't say whether the source wrote\n * `&` or `&amp;`.\n */\nclass SourceStartTags {\n private readonly ordinals = new Map<Element, number>();\n private readonly counts = new Map<string, number>();\n private readonly tags = new Map<string, string[]>();\n\n constructor(\n private readonly html: string,\n elements: Element[]\n ) {\n // Document order is source order of start tags, so the nth <x> element\n // is the nth `<x` in the source.\n for (const element of elements) {\n const count = this.counts.get(element.localName) ?? 0;\n this.ordinals.set(element, count);\n this.counts.set(element.localName, count + 1);\n }\n }\n\n of(element: Element): string {\n const name = element.localName;\n let tags = this.tags.get(name);\n if (!tags) {\n // Quoted values may hold `>`. Each alternative starts with a different\n // character, so this can't backtrack.\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const startTag = new RegExp(\n `<${escaped}(?=[\\\\s/>])(?:\"[^\"]*\"|'[^']*'|[^'\">])*>`,\n 'gi'\n );\n tags = this.html.match(startTag) ?? [];\n this.tags.set(name, tags);\n }\n // A mismatch means a `<x` the parser didn't turn into an element (in a\n // comment, say), so the ordinal can't be trusted: rebuild the tag.\n const tag =\n tags.length === this.counts.get(name)\n ? tags[this.ordinals.get(element) ?? -1]\n : undefined;\n return tag ?? rebuiltStartTag(element);\n }\n}\n\n/** A start tag for `element` rebuilt from the DOM. */\nfunction rebuiltStartTag(element: Element): string {\n const attributes = Array.from(element.attributes)\n .map(({ name, value }) => (value ? ` ${name}=\"${value}\"` : ` ${name}`))\n .join('');\n return `<${element.localName}${attributes}>`;\n}\n"]}
@@ -16,7 +16,9 @@ export declare const CONCURRENCY = 4;
16
16
  * which html-to-docx embeds without downloading it again. An image that can't
17
17
  * be fetched becomes its alt text, linked to its URL, where html-to-docx would
18
18
  * drop it without a trace. Other sources it can't embed either, such as a
19
- * relative path, keep their alt text too.
19
+ * relative path, keep their alt text too. So does a `data:` URI that isn't a
20
+ * PNG, JPEG, GIF, BMP or SVG image; one that is gets rewritten as base64 of
21
+ * the type its bytes show, which is the form html-to-docx reads.
20
22
  *
21
23
  * Each URL is fetched once, however many times it appears: at most
22
24
  * MAX_IMAGES of them, CONCURRENCY at a time.