返回 oh-my-ppt
run-color-fidelity.test.ts
根目录 / tests / unit / html-pptx / run-color-fidelity.test.ts
1 import { describe, expect, it } from 'vitest'
2 import { readFileSync } from 'node:fs'
3 import { pathToFileURL } from 'node:url'
4 import os from 'os'
5 import path from 'path'
6 import { unzipSync } from 'fflate'
7 import {
8 HIDE_FOR_PPTX_BACKGROUND_SCRIPT,
9 buildMarkPptxExtractedTextForBackgroundScript
10 } from '../../../src/main/io/html-pptx/browser-scripts'
11
12 // 回归背景(用户反馈「导出的 PPT 与预览相比,文本加粗/颜色不一致」):
13 // 1. 标题里的蓝色 span(如「EMV <blue>L3</blue>认证」)跨行时导出后变回单色——
14 // html2pptx 0.0.10 的提取脚本在行界(display:block 子元素 / <br>)不把 \n
15 // 写进 runs,normalize 的完整性校验(runs 拼接 === 全文)失败后整组丢弃,
16 // writer 退化成单色单 run。html2pptx >= 0.2.0 修复:在块级边界把 \n 补进
17 // 最后一个非空白 run;normalize 一旦通过校验即保留 runs,writer 按 run
18 // 拆 <a:r> 且按 \n 切段落。
19 // 2. aria-hidden 装饰文字(如 440px 的「L3」水印)被提取端有意跳过、留给背景
20 // 截图,但背景隐藏规则会把「已提取容器」的所有后代文字透明化,水印一起被
21 // 清空。修复:隐藏规则对 aria-hidden 子树豁免,并以行内 !important 钉住
22 // 其计算后的画笔值(color / -webkit-text-fill-color 等会继承,仅靠选择器
23 // 无法撤销祖先链上的透明化)。
24
25 // vitest 会把 '@arcsin1/html2pptx' 别名到不存在的作者本地目录,且 CJS 入口在
26 // "type": "module" 包内 require ESM 直接报错;沿用 pptx-compat.test.ts 的方式,
27 // 用绝对路径动态导入 ESM 入口。
28 const html2pptxNode = (await import(
29 pathToFileURL(path.resolve('node_modules/@arcsin1/html2pptx/dist/node.js')).href
30 )) as { writeHtmlToPptx: (outputPath: string, document: unknown) => void }
31 const html2pptxEsm = await import(
32 pathToFileURL(path.resolve('node_modules/@arcsin1/html2pptx/dist/index.js')).href
33 ) as {
34 normalizeExtractedHtmlToPptxSlide: (extracted: unknown, title: string, size: { widthIn: number; heightIn: number }) => {
35 texts: Array<{ text: string; runs?: Array<{ text: string; color: string; bold?: boolean }> }>
36 }
37 buildHtmlToPptxExtractScript: (options: Record<string, unknown>) => string
38 }
39
40 type ExtractRun = {
41 text: string
42 color: string
43 bold?: boolean
44 italic?: boolean
45 fontSize?: number
46 fontFace?: string
47 }
48
49 const titleExtracted = {
50 texts: [
51 {
52 text: 'EMV L3认证\n问题复盘与经验分享',
53 x: 1,
54 y: 2.9,
55 w: 9,
56 h: 2.2,
57 fontSize: 55.2,
58 fontFace: 'Noto Sans SC',
59 bold: true,
60 color: '0F172A',
61 runs: [
62 { text: 'EMV ', color: '0F172A', bold: true, fontSize: 55.2, fontFace: 'Noto Sans SC' },
63 { text: 'L3', color: '3B82F6', bold: true, fontSize: 55.2, fontFace: 'Noto Sans SC' },
64 { text: '认证\n', color: '0F172A', bold: true, fontSize: 55.2, fontFace: 'Noto Sans SC' },
65 { text: '问题复盘与经验分享', color: '0F172A', bold: true, fontSize: 55.2, fontFace: 'Noto Sans SC' }
66 ] as ExtractRun[]
67 }
68 ],
69 shapes: [],
70 images: [],
71 tables: [],
72 limits: { maxTextChars: 1000, maxImageBytes: 12582912 }
73 }
74
75 describe('mixed-color runs survive export when a line break falls between runs', () => {
76 it('normalize keeps the runs once their joined text (with \\n) matches the full text', () => {
77 const slide = html2pptxEsm.normalizeExtractedHtmlToPptxSlide(titleExtracted, '混色标题', {
78 widthIn: 13.333333333,
79 heightIn: 7.5
80 })
81 const title = slide.texts.find((t) => t.text.includes('EMV'))
82 expect(title).toBeDefined()
83 const runs = title!.runs
84 expect(runs).toBeDefined()
85 expect(runs!.map((r) => r.text)).toEqual(['EMV ', 'L3', '认证\n', '问题复盘与经验分享'])
86 expect(runs!.find((r) => r.text === 'L3')!.color).toBe('3B82F6')
87 })
88
89 it('writer emits the blue run and splits paragraphs at the run-embedded newline', () => {
90 const slide = html2pptxEsm.normalizeExtractedHtmlToPptxSlide(titleExtracted, '混色标题', {
91 widthIn: 13.333333333,
92 heightIn: 7.5
93 })
94 const outPath = path.join(os.tmpdir(), `oh-my-ppt-run-colors-${Date.now()}.pptx`)
95 html2pptxNode.writeHtmlToPptx(outPath, { title: '混色标题', slides: [slide] })
96
97 const xml = Buffer.from(unzipSync(readFileSync(outPath))['ppt/slides/slide1.xml']).toString('utf-8')
98 // 蓝 run 必须原样出现在 XML 里(修复前整组 runs 被丢弃、只剩单色文本)
99 expect(xml).toContain('<a:srgbClr val="3B82F6"/>')
100 const l3Index = xml.indexOf('<a:t>L3</a:t>')
101 expect(l3Index).toBeGreaterThan(-1)
102 const restIndex = xml.indexOf('<a:t>问题复盘与经验分享</a:t>')
103 expect(restIndex).toBeGreaterThan(l3Index)
104 // 换行必须成为段落边界(修复前 runs 丢失,两行被合并成一个单色段落)
105 const between = xml.slice(l3Index, restIndex)
106 expect(between).toContain('</a:p>')
107 })
108 })
109
110 describe('decorative aria-hidden text stays in the raster background', () => {
111 it('background hide rule exempts aria-hidden subtrees', () => {
112 expect(HIDE_FOR_PPTX_BACKGROUND_SCRIPT).toContain(':not(:is([aria-hidden="true"], [aria-hidden="true"] *))')
113 })
114
115 it('hide script pins computed paint on aria-hidden subtrees with inline !important', () => {
116 // color / -webkit-text-fill-color 会从被标记祖先继承透明值,必须行内钉住
117 expect(HIDE_FOR_PPTX_BACKGROUND_SCRIPT).toContain(
118 "root.querySelectorAll('[aria-hidden=\"true\"], [aria-hidden=\"true\"] *')"
119 )
120 expect(HIDE_FOR_PPTX_BACKGROUND_SCRIPT).toContain("el.style.setProperty(prop, value, 'important')")
121 })
122
123 it('background text-match marking skips aria-hidden elements', () => {
124 const script = buildMarkPptxExtractedTextForBackgroundScript(
125 [{ x: 1, y: 1, w: 4, h: 1 }],
126 { widthIn: 13.333333333, heightIn: 7.5 }
127 )
128 expect(script).toContain("element.closest('[aria-hidden=\"true\"]')")
129 })
130 })
131
132 describe('html2pptx extract: block boundaries feed newlines into runs', () => {
133 it('extract script carries the block-boundary newline insertion', () => {
134 const script = html2pptxEsm.buildHtmlToPptxExtractScript({
135 pageWidthPx: 1600,
136 pageHeightPx: 900,
137 slideWidthIn: 13.333333333,
138 slideHeightIn: 7.5,
139 maxTextBoxes: 360,
140 maxShapes: 400,
141 maxImages: 80,
142 unsupportedTransformStrategy: 'raster-fallback'
143 })
144 // npm dist 是压缩产物,用占位正则匹配结构(标识符名在压缩间不稳定):
145 // 块级边界(<br> 或块级 display)时从最后一个非空白 run 向前找插入点,
146 // 追加纯 \n(追加到纯空白 run 会被过滤丢掉)
147 expect(script).toMatch(
148 /\("BR"===(\w+)\.tagName\|\|\/\^\(block\|flex\|grid\|list-item\|flow-root\|table\)\$\/\.test\(/
149 )
150 expect(script).toMatch(
151 /for\(let (\w+)=(\w+)\.length-1;\1>=0;\1--\)if\(\w+\(\2\[\1\]\.text\)\)return void\(\2\[\1\]\.text\+="\\n"\)/
152 )
153 // <br> 只插换行不递归子节点
154 expect(script).toContain('"BR"!==')
155 })
156 })
157
157 lines TYPESCRIPT