dsh-ppt 0.4.3 → 0.4.5

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,811 +1,994 @@
1
- #! /usr/bin/env node
2
- /**
3
- * deck-core.mjs —— dsh-ppt 的零依赖演示文稿引擎。
4
- *
5
- * 这是插件工具与裸 SKILL.md 共用的唯一事实源:
6
- * - DSH 内:ppt_create 工具动态加载本文件
7
- * - 其他 harness:直接运行同目录的 build-deck.mjs
8
- *
9
- * 能力:Markdown / 结构化 slides → 三件套
10
- * deck.html 独立网页放映(键盘/触屏/打印,无外链)
11
- * deck.pptx 可编辑 PPTX(16:9,OOXML 由本文件手写,zip 用 node:zlib)
12
- * deck.json 结构化 deck manifest
13
- *
14
- * 零运行时依赖,仅使用 node:fs / node:path / node:zlib。
15
- */
16
-
17
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
18
- import { resolve as resolvePath } from 'node:path'
19
- import { deflateRawSync } from 'node:zlib'
20
-
21
- /**
22
- * manifest 版本跟随发布包 package.json;把 skills/dsh-ppt 独立复制到其他
23
- * harness(没有 package.json)时回退为 0.0.0,避免版本号悄悄漂移。
24
- */
25
- function readDeckVersion() {
26
- try {
27
- const pkg = JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8'))
28
- const version = String(pkg.version ?? '').trim()
29
- return version !== '' ? version : '0.0.0'
30
- } catch {
31
- return '0.0.0'
32
- }
33
- }
34
-
35
- export const DECK_VERSION = readDeckVersion()
36
-
37
- // ---------------------------------------------------------------------------
38
- // 主题
39
- // ---------------------------------------------------------------------------
40
-
41
- export const THEMES = {
42
- swiss: {
43
- id: 'swiss',
44
- name: { zh: '瑞士脉冲', en: 'Swiss Pulse' },
45
- mood: { zh: '精准、理性、数据', en: 'Precise, rational, data-driven' },
46
- bestFor: { zh: 'SaaS、数据、开发者工具', en: 'SaaS, data, developer tools' },
47
- dark: true,
48
- palette: {
49
- bg: '#10151B',
50
- panel: '#161D26',
51
- fg: '#F5F7FA',
52
- muted: '#8E9AAA',
53
- accent: '#2F6BFF',
54
- accent2: '#FFB300',
55
- },
56
- fonts: {
57
- heading: '"Helvetica Neue", Inter, "PingFang SC", "Microsoft YaHei", sans-serif',
58
- body: '"Helvetica Neue", Inter, "PingFang SC", "Microsoft YaHei", sans-serif',
59
- },
60
- },
61
- velvet: {
62
- id: 'velvet',
63
- name: { zh: '天鹅绒标准', en: 'Velvet Standard' },
64
- mood: { zh: '高级、克制、可信', en: 'Premium, restrained, trustworthy' },
65
- bestFor: { zh: '高管汇报、品牌、融资路演', en: 'Executive decks, brand, investor pitches' },
66
- dark: true,
67
- palette: {
68
- bg: '#111316',
69
- panel: '#1A1D22',
70
- fg: '#F4EFE6',
71
- muted: '#A79F91',
72
- accent: '#C9A84C',
73
- accent2: '#3D4A63',
74
- },
75
- fonts: {
76
- heading: 'Georgia, "Times New Roman", "Songti SC", "SimSun", serif',
77
- body: '"Helvetica Neue", Inter, "PingFang SC", "Microsoft YaHei", sans-serif',
78
- },
79
- },
80
- data: {
81
- id: 'data',
82
- name: { zh: '数据漂移', en: 'Data Drift' },
83
- mood: { zh: '未来、沉浸、前沿', en: 'Futuristic, immersive, cutting-edge' },
84
- bestFor: { zh: 'AI、数据、研究、技术发布', en: 'AI, data, research, tech launches' },
85
- dark: true,
86
- palette: {
87
- bg: '#070B14',
88
- panel: '#0D1424',
89
- fg: '#E8F1FF',
90
- muted: '#7E8BA8',
91
- accent: '#7C3AED',
92
- accent2: '#06B6D4',
93
- },
94
- fonts: {
95
- heading: '"Space Grotesk", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
96
- body: '"Space Grotesk", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
97
- },
98
- },
99
- soft: {
100
- id: 'soft',
101
- name: { zh: '柔和信号', en: 'Soft Signal' },
102
- mood: { zh: '温暖、亲近、人本', en: 'Warm, intimate, human' },
103
- bestFor: { zh: '品牌故事、培训、个人分享', en: 'Brand stories, training, personal talks' },
104
- dark: false,
105
- palette: {
106
- bg: '#FFF8EC',
107
- panel: '#FFF2DE',
108
- fg: '#3B2F2A',
109
- muted: '#7E6F68',
110
- accent: '#E58A2F',
111
- accent2: '#8FAF8C',
112
- },
113
- fonts: {
114
- heading: '"Avenir Next", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
115
- body: '"Avenir Next", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
116
- },
117
- },
118
- bold: {
119
- id: 'bold',
120
- name: { zh: '极繁大字', en: 'Maximalist Type' },
121
- mood: { zh: '大声、动能、发布', en: 'Loud, kinetic, launch' },
122
- bestFor: { zh: '产品发布、活动、品牌大事件', en: 'Product launches, events, brand moments' },
123
- dark: true,
124
- palette: {
125
- bg: '#0D0D0D',
126
- panel: '#181818',
127
- fg: '#FFFFFF',
128
- muted: '#B8B8B8',
129
- accent: '#E63946',
130
- accent2: '#FFD60A',
131
- },
132
- fonts: {
133
- heading: 'Impact, "Arial Black", "PingFang SC", "Microsoft YaHei", sans-serif',
134
- body: '"Helvetica Neue", Inter, "PingFang SC", "Microsoft YaHei", sans-serif',
135
- },
136
- },
137
- }
138
-
139
- export const THEME_IDS = Object.keys(THEMES)
140
- export const DEFAULT_THEME = 'data'
141
-
142
- export const LANGUAGES = {
143
- zh: {
144
- id: 'zh',
145
- attr: 'zh-CN',
146
- ui: {
147
- slide: '第',
148
- of: '/ 共',
149
- theme: '主题',
150
- help: '← → 翻页 · F 全屏 · G 总览 · S 备注 · P 打印',
151
- coverKicker: '开场',
152
- pointKicker: '要点',
153
- statementKicker: '核心观点',
154
- quoteKicker: '金句',
155
- tableKicker: '数据',
156
- notesLabel: '演讲者备注',
157
- notesToggle: '备注',
158
- closingTitle: '谢谢',
159
- closingSubtitle: '讨论与问答',
1
+ #! /usr/bin/env node
2
+ /**
3
+ * deck-core.mjs —— dsh-ppt 的零依赖演示文稿引擎。
4
+ *
5
+ * 这是插件工具与裸 SKILL.md 共用的唯一事实源:
6
+ * - DSH 内:ppt_create 工具动态加载本文件
7
+ * - 其他 harness:直接运行同目录的 build-deck.mjs
8
+ *
9
+ * 能力:Markdown / 结构化 slides → 三件套
10
+ * deck.html 独立网页放映(键盘/触屏/打印,无外链)
11
+ * deck.pptx 可编辑 PPTX(16:9,OOXML 由本文件手写,zip 用 node:zlib)
12
+ * deck.json 结构化 deck manifest
13
+ *
14
+ * 零运行时依赖,仅使用 node:fs / node:path / node:zlib。
15
+ */
16
+
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
18
+ import { resolve as resolvePath, join as joinPath } from 'node:path'
19
+ import { deflateRawSync } from 'node:zlib'
20
+
21
+ /**
22
+ * manifest 版本跟随发布包 package.json;把 skills/dsh-ppt 独立复制到其他
23
+ * harness(没有 package.json)时回退为 0.0.0,避免版本号悄悄漂移。
24
+ */
25
+ function readDeckVersion() {
26
+ try {
27
+ const pkg = JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8'))
28
+ const version = String(pkg.version ?? '').trim()
29
+ return version !== '' ? version : '0.0.0'
30
+ } catch {
31
+ return '0.0.0'
32
+ }
33
+ }
34
+
35
+ export const DECK_VERSION = readDeckVersion()
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // 主题
39
+ // ---------------------------------------------------------------------------
40
+
41
+ export const THEMES = {
42
+ swiss: {
43
+ id: 'swiss',
44
+ name: { zh: '瑞士脉冲', en: 'Swiss Pulse' },
45
+ mood: { zh: '精准、理性、数据', en: 'Precise, rational, data-driven' },
46
+ bestFor: { zh: 'SaaS、数据、开发者工具', en: 'SaaS, data, developer tools' },
47
+ dark: true,
48
+ palette: {
49
+ bg: '#10151B',
50
+ panel: '#161D26',
51
+ fg: '#F5F7FA',
52
+ muted: '#8E9AAA',
53
+ accent: '#2F6BFF',
54
+ accent2: '#FFB300',
55
+ },
56
+ fonts: {
57
+ heading: '"Helvetica Neue", Inter, "PingFang SC", "Microsoft YaHei", sans-serif',
58
+ body: '"Helvetica Neue", Inter, "PingFang SC", "Microsoft YaHei", sans-serif',
59
+ },
60
+ },
61
+ velvet: {
62
+ id: 'velvet',
63
+ name: { zh: '天鹅绒标准', en: 'Velvet Standard' },
64
+ mood: { zh: '高级、克制、可信', en: 'Premium, restrained, trustworthy' },
65
+ bestFor: { zh: '高管汇报、品牌、融资路演', en: 'Executive decks, brand, investor pitches' },
66
+ dark: true,
67
+ palette: {
68
+ bg: '#111316',
69
+ panel: '#1A1D22',
70
+ fg: '#F4EFE6',
71
+ muted: '#A79F91',
72
+ accent: '#C9A84C',
73
+ accent2: '#3D4A63',
74
+ },
75
+ fonts: {
76
+ heading: 'Georgia, "Times New Roman", "Songti SC", "SimSun", serif',
77
+ body: '"Helvetica Neue", Inter, "PingFang SC", "Microsoft YaHei", sans-serif',
78
+ },
79
+ },
80
+ data: {
81
+ id: 'data',
82
+ name: { zh: '数据漂移', en: 'Data Drift' },
83
+ mood: { zh: '未来、沉浸、前沿', en: 'Futuristic, immersive, cutting-edge' },
84
+ bestFor: { zh: 'AI、数据、研究、技术发布', en: 'AI, data, research, tech launches' },
85
+ dark: true,
86
+ palette: {
87
+ bg: '#070B14',
88
+ panel: '#0D1424',
89
+ fg: '#E8F1FF',
90
+ muted: '#7E8BA8',
91
+ accent: '#7C3AED',
92
+ accent2: '#06B6D4',
93
+ },
94
+ fonts: {
95
+ heading: '"Space Grotesk", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
96
+ body: '"Space Grotesk", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
97
+ },
98
+ },
99
+ soft: {
100
+ id: 'soft',
101
+ name: { zh: '柔和信号', en: 'Soft Signal' },
102
+ mood: { zh: '温暖、亲近、人本', en: 'Warm, intimate, human' },
103
+ bestFor: { zh: '品牌故事、培训、个人分享', en: 'Brand stories, training, personal talks' },
104
+ dark: false,
105
+ palette: {
106
+ bg: '#FFF8EC',
107
+ panel: '#FFF2DE',
108
+ fg: '#3B2F2A',
109
+ muted: '#7E6F68',
110
+ accent: '#E58A2F',
111
+ accent2: '#8FAF8C',
112
+ },
113
+ fonts: {
114
+ heading: '"Avenir Next", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
115
+ body: '"Avenir Next", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
116
+ },
117
+ },
118
+ bold: {
119
+ id: 'bold',
120
+ name: { zh: '极繁大字', en: 'Maximalist Type' },
121
+ mood: { zh: '大声、动能、发布', en: 'Loud, kinetic, launch' },
122
+ bestFor: { zh: '产品发布、活动、品牌大事件', en: 'Product launches, events, brand moments' },
123
+ dark: true,
124
+ palette: {
125
+ bg: '#0D0D0D',
126
+ panel: '#181818',
127
+ fg: '#FFFFFF',
128
+ muted: '#B8B8B8',
129
+ accent: '#E63946',
130
+ accent2: '#FFD60A',
131
+ },
132
+ fonts: {
133
+ heading: 'Impact, "Arial Black", "PingFang SC", "Microsoft YaHei", sans-serif',
134
+ body: '"Helvetica Neue", Inter, "PingFang SC", "Microsoft YaHei", sans-serif',
135
+ },
136
+ },
137
+ }
138
+
139
+ export const THEME_IDS = Object.keys(THEMES)
140
+ export const DEFAULT_THEME = 'data'
141
+
142
+ export const LANGUAGES = {
143
+ zh: {
144
+ id: 'zh',
145
+ attr: 'zh-CN',
146
+ ui: {
147
+ slide: '第',
148
+ of: '/ 共',
149
+ theme: '主题',
150
+ help: '← → 翻页 · F 全屏 · G 总览 · S 备注 · P 打印',
151
+ coverKicker: '开场',
152
+ pointKicker: '要点',
153
+ statementKicker: '核心观点',
154
+ quoteKicker: '金句',
155
+ tableKicker: '数据',
156
+ continuation: '(续)',
157
+ notesLabel: '演讲者备注',
158
+ notesToggle: '备注',
159
+ closingTitle: '谢谢',
160
+ closingSubtitle: '讨论与问答',
160
161
  generatedBy: '由 dsh-ppt 生成',
161
- },
162
- },
163
- en: {
164
- id: 'en',
165
- attr: 'en-US',
166
- ui: {
167
- slide: 'Slide',
168
- of: '/',
169
- theme: 'Theme',
170
- help: '← → navigate · F fullscreen · G overview · S notes · P print',
171
- coverKicker: 'Opening',
172
- pointKicker: 'Key point',
173
- statementKicker: 'Core idea',
174
- quoteKicker: 'Quote',
175
- tableKicker: 'Data',
176
- notesLabel: 'Speaker notes',
177
- notesToggle: 'Notes',
178
- closingTitle: 'Thank You',
179
- closingSubtitle: 'Discussion & Q&A',
162
+ overviewToggle: '总览',
163
+ presenterToggle: '演讲者',
164
+ presenterLabel: '演讲者视图 · Presenter view',
165
+ helpTitle: '快捷键 · Shortcuts',
166
+ noNotes: '(本页无备注)',
167
+ closeLabel: '关闭',
168
+ currentLabel: '当前页 · Current',
169
+ nextLabel: '下一页 · Next',
170
+ timerLabel: '计时 · Timer',
171
+ presenterHint: '备注:未开演讲者窗口时按 S 显示在顶部;打开后只在演讲者窗口显示,观众看不到',
172
+ wrapHint: '已环绕到',
173
+ popupBlocked: '浏览器拦截了演讲者窗口,请允许弹出窗口后按 V 重试',
174
+ notesCloseLabel: '关闭备注',
175
+ overviewHint: '点击缩略图跳页,方向键切换,Enter 进入,Esc 退出'
176
+ },
177
+ },
178
+ en: {
179
+ id: 'en',
180
+ attr: 'en-US',
181
+ ui: {
182
+ slide: 'Slide',
183
+ of: '/',
184
+ theme: 'Theme',
185
+ help: '← → navigate · F fullscreen · G overview · S notes · P print',
186
+ coverKicker: 'Opening',
187
+ pointKicker: 'Key point',
188
+ statementKicker: 'Core idea',
189
+ quoteKicker: 'Quote',
190
+ tableKicker: 'Data',
191
+ continuation: ' (continued)',
192
+ notesLabel: 'Speaker notes',
193
+ notesToggle: 'Notes',
194
+ closingTitle: 'Thank You',
195
+ closingSubtitle: 'Discussion & Q&A',
180
196
  generatedBy: 'Generated with dsh-ppt',
181
- },
182
- },
183
- bilingual: {
184
- id: 'bilingual',
185
- attr: 'zh-CN',
186
- ui: {
187
- slide: '第',
188
- of: '/ 共',
189
- theme: '主题 · Theme',
190
- help: '← → 翻页 · F 全屏 · G 总览 · S 备注 · P 打印',
191
- coverKicker: '开场 · Opening',
192
- pointKicker: '要点 · Key point',
193
- statementKicker: '核心观点 · Core Idea',
194
- quoteKicker: '金句 · Quote',
195
- tableKicker: '数据 · Data',
196
- notesLabel: '演讲者备注 · Speaker notes',
197
- notesToggle: '备注 · Notes',
198
- closingTitle: '谢谢 · Thank You',
199
- closingSubtitle: '讨论与问答 · Q&A',
197
+ overviewToggle: 'Overview',
198
+ presenterToggle: 'Presenter',
199
+ presenterLabel: 'Presenter view',
200
+ helpTitle: 'Keyboard shortcuts',
201
+ noNotes: '(No notes on this slide)',
202
+ closeLabel: 'Close',
203
+ currentLabel: 'Current',
204
+ nextLabel: 'Next',
205
+ timerLabel: 'Timer',
206
+ presenterHint: 'Notes: S shows them on top until a presenter window is open; afterwards only in the presenter window.',
207
+ wrapHint: 'Wrapped to',
208
+ popupBlocked: 'The presenter window was blocked. Allow pop-ups and press V to retry.',
209
+ notesCloseLabel: 'Close notes',
210
+ overviewHint: 'Click a thumbnail to jump; arrows move, Enter opens, Esc exits'
211
+ },
212
+ },
213
+ bilingual: {
214
+ id: 'bilingual',
215
+ attr: 'zh-CN',
216
+ ui: {
217
+ slide: '第',
218
+ of: '/ 共',
219
+ theme: '主题 · Theme',
220
+ help: '← → 翻页 · F 全屏 · G 总览 · S 备注 · P 打印',
221
+ coverKicker: '开场 · Opening',
222
+ pointKicker: '要点 · Key point',
223
+ statementKicker: '核心观点 · Core Idea',
224
+ quoteKicker: '金句 · Quote',
225
+ tableKicker: '数据 · Data',
226
+ continuation: '(续 · continued)',
227
+ notesLabel: '演讲者备注 · Speaker notes',
228
+ notesToggle: '备注 · Notes',
229
+ closingTitle: '谢谢 · Thank You',
230
+ closingSubtitle: '讨论与问答 · Q&A',
200
231
  generatedBy: '由 dsh-ppt 生成 · Generated with dsh-ppt',
232
+ overviewToggle: '总览 · Overview',
233
+ presenterToggle: '演讲者 · Presenter',
234
+ presenterLabel: '演讲者视图 · Presenter view',
235
+ helpTitle: '快捷键 · Shortcuts',
236
+ noNotes: '(本页无备注 · No notes on this slide)',
237
+ closeLabel: '关闭 · Close',
238
+ currentLabel: '当前页 · Current',
239
+ nextLabel: '下一页 · Next',
240
+ timerLabel: '计时 · Timer',
241
+ presenterHint: '备注:未开演讲者窗口时按 S 显示在顶部;打开后只在演讲者窗口显示 · Notes: S shows on top until a presenter window is open',
242
+ wrapHint: '已环绕到 · Wrapped to',
243
+ popupBlocked: '浏览器拦截了演讲者窗口 · Presenter window blocked; allow pop-ups and press V',
244
+ notesCloseLabel: '关闭备注 · Close notes',
245
+ overviewHint: '点击缩略图跳页 · Click to jump, arrows move, Enter opens, Esc exits'
201
246
  },
202
247
  },
203
248
  }
204
249
 
205
- export function resolveTheme(input) {
206
- const id = String(input ?? DEFAULT_THEME).trim().toLowerCase()
207
- const theme = THEMES[id]
208
- if (!theme) {
209
- throw new Error('dsh-ppt:未知主题 "' + id + '",可选:' + THEME_IDS.join(' / ') + '(默认 ' + DEFAULT_THEME + ')')
210
- }
211
- return theme
212
- }
213
-
214
- export function resolveLanguage(input) {
215
- const id = String(input ?? 'zh').trim().toLowerCase()
216
- const language = LANGUAGES[id]
217
- if (!language) {
218
- throw new Error('dsh-ppt:未知语言 "' + id + '",可选:zh / en / bilingual')
219
- }
220
- return language
221
- }
222
-
223
- export function resolveMotion(input) {
224
- if (input === undefined || input === null || input === '') return true
225
- if (input === true || input === 'on') return true
226
- if (input === false || input === 'off') return false
227
- throw new Error('dsh-ppt:未知 motion 值 "' + String(input) + '",可选:on / off(默认 on)')
228
- }
229
-
230
- export function listThemes(lang = 'zh') {
231
- const pick = (pair) => (lang === 'en' ? pair.en : pair.zh)
232
- return THEME_IDS.map((id) => {
233
- const theme = THEMES[id]
234
- return {
235
- id,
236
- name: pick(theme.name),
237
- mood: pick(theme.mood),
238
- bestFor: pick(theme.bestFor),
239
- dark: theme.dark,
240
- palette: { ...theme.palette },
241
- fonts: { ...theme.fonts },
242
- }
243
- })
244
- }
245
-
246
- // ---------------------------------------------------------------------------
247
- // 文本工具
250
+ // ---------------------------------------------------------------------------
251
+ // 主题预览(ppt_themes preview=true / buildThemePreview)
248
252
  // ---------------------------------------------------------------------------
249
253
 
250
- export function clampInt(value, fallback, min, max) {
251
- const n = typeof value === 'number' ? Math.trunc(value) : fallback
252
- if (!Number.isFinite(n)) return fallback
253
- return Math.min(max, Math.max(min, n))
254
- }
255
-
256
- // Windows 保留设备名:首个点之前的主名命中即不可用(NUL、com1、aux.report.html 都算)。
257
- const WINDOWS_RESERVED_FILE_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i
258
-
259
- export function sanitizeFileName(input) {
260
- const base = String(input ?? 'deck').trim().replace(/\.(html?|pptx|json)$/i, '')
261
- let cleaned = base
262
- .replace(/[<>:"/\\|?*\u0000-\u001F]/g, '-')
263
- .replace(/\s+/g, '-')
264
- .replace(/-+/g, '-')
265
- .replace(/^-+|-+$/g, '')
266
- if (WINDOWS_RESERVED_FILE_NAME.test(cleaned)) cleaned = 'deck-' + cleaned
267
- return cleaned.slice(0, 120) || 'deck'
268
- }
269
-
270
- const DECK_ARTIFACT_EXTENSIONS = ['.html', '.pptx', '.json']
271
-
272
- /**
273
- * 为三件套选择同一个可用文件名前缀。默认不覆盖:任一产物已存在时,
274
- * 整组改用 -1/-2… 后缀,避免新旧 deck 被静默混写。
275
- */
276
- function resolveDeckFileName(outputDir, requestedFileName, overwrite) {
277
- // 一次 readdir 建集,替代逐个候选 existsSync 探测(最坏 ~3000 次 stat);
278
- // 统一小写比较,避免 Windows 大小写不敏感文件系统把已占用的名字判成可用。
279
- const existing = new Set(readdirSync(outputDir).map((name) => name.toLowerCase()))
280
- const isAvailable = (candidate) => DECK_ARTIFACT_EXTENSIONS.every((ext) => !existing.has((candidate + ext).toLowerCase()))
281
- if (overwrite || isAvailable(requestedFileName)) return requestedFileName
282
- for (let index = 1; index < 1000; index += 1) {
283
- const candidate = requestedFileName + '-' + index
284
- if (isAvailable(candidate)) return candidate
285
- }
286
- throw new Error('dsh-ppt:找不到可用的输出文件名(同名前缀超过 999 个),请更换 fileName 或显式允许 overwrite。')
287
- }
288
-
289
- export function escapeXml(value) {
290
- return String(value ?? '')
291
- .replace(/&/g, '&amp;')
292
- .replace(/</g, '&lt;')
293
- .replace(/>/g, '&gt;')
294
- .replace(/"/g, '&quot;')
295
- .replace(/'/g, '&apos;')
296
- }
297
-
298
- export function escapeHtml(value) {
299
- return String(value ?? '')
300
- .replace(/&/g, '&amp;')
301
- .replace(/</g, '&lt;')
302
- .replace(/>/g, '&gt;')
303
- .replace(/"/g, '&quot;')
304
- }
305
-
306
- export function stripInlineMarkdown(value) {
307
- return String(value ?? '')
308
- .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
309
- .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
310
- .replace(/`([^`]*)`/g, '$1')
311
- .replace(/\*\*([^*]+)\*\*/g, '$1')
312
- .replace(/__([^_]+)__/g, '$1')
313
- .replace(/\*([^*\n]+)\*/g, '$1')
314
- .replace(/_([^_\n]+)_/g, '$1')
315
- .replace(/<[^>]+>/g, '')
316
- .replace(/\s+/g, ' ')
317
- .trim()
318
- }
319
-
320
- export function splitSentences(value) {
321
- const text = String(value ?? '').trim()
322
- if (text === '') return []
323
- const parts = text.split(/(?<=[。!?])|(?<=[.!?…])\s+/).map((part) => part.trim()).filter(Boolean)
324
- return parts.length > 0 ? parts : [text]
325
- }
326
-
327
- export function truncate(value, max) {
328
- const text = String(value ?? '').trim()
329
- if (text.length <= max) return text
330
- return text.slice(0, max - 1).replace(/\s+\S*$/, '') + '…'
331
- }
332
-
333
- function chunk(items, size) {
334
- const out = []
335
- for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size))
336
- return out
337
- }
338
-
339
- // ---------------------------------------------------------------------------
340
- // Markdown → deck
341
- // ---------------------------------------------------------------------------
342
-
343
- function createSection(heading = '', level = 0, coverOnly = false) {
344
- return { heading, level, coverOnly, bullets: [], paragraphs: [], quote: [], table: null, notes: [] }
345
- }
346
-
347
- function splitTableRow(line) {
348
- const trimmed = line.trim()
349
- const match = /^\|(.+)\|$/.exec(trimmed)
350
- if (match === null) return null
351
- return match[1].split('|').map((cell) => cell.trim())
352
- }
353
-
354
- function isTableSeparator(cells) {
355
- return cells.length > 0 && cells.every((cell) => /^:?-{2,}:?$/.test(cell) || /^:?-+:?$/.test(cell))
356
- }
357
-
358
- const NOTES_COMMENT = /^<!--\s*(?:notes?|备注)\s*[::]\s*([\s\S]*?)\s*-->$/
359
-
360
- function quoteSlideFrom(section, ui) {
361
- const lines = [...section.quote]
362
- let attribution = ''
363
- const attrMatch = /^(?:——|—|--|-)\s*(.+)$/.exec(lines[lines.length - 1] ?? '')
364
- if (attrMatch !== null && lines.length > 1) {
365
- attribution = attrMatch[1]
366
- lines.pop()
367
- }
368
- return { layout: 'quote', kicker: ui.quoteKicker, title: truncate(lines.join(' '), 220), subtitle: attribution }
369
- }
370
-
371
- function tableSlideFrom(section, ui) {
372
- const table = section.table
373
- const rows = [table.header, ...table.rows]
374
- .slice(0, 9)
375
- .map((row) => row.slice(0, 8).map((cell) => truncate(cell, 60)))
376
- const heading = section.heading || ui.tableKicker
377
- return { layout: 'table', kicker: heading, title: heading, rows }
254
+ function themePages(lang) {
255
+ return lang === 'en'
256
+ ? { title: 'dsh-ppt theme gallery', hint: 'Pick a theme id for ppt_create', usage: 'theme', dark: 'dark', light: 'light', palette: 'Palette' }
257
+ : { title: 'dsh-ppt 主题预览', hint: '把 id 填给 ppt_create 的 theme 参数', usage: 'theme', dark: '深色', light: '浅色', palette: '色板' }
378
258
  }
379
259
 
380
- /** 把一个 section 里的金句/表格拆成独立页;备注附着到第一张产出页。 */
381
- function specialSlidesFor(section, ui) {
260
+ /** 单套主题的 960x540 SVG 色板卡:可直接放进 README / npm 首屏。 */
261
+ export function renderThemeSvg(input, lang = 'zh') {
262
+ const theme = typeof input === 'string' ? resolveTheme(input) : input
263
+ const pick = (pair) => (lang === 'en' ? pair.en : pair.zh)
264
+ const p = theme.palette
265
+ const L = themePages(lang === 'en' ? 'en' : 'zh')
266
+ const font = theme.fonts.heading.replace(/"/g, "'")
267
+ const bodyFont = theme.fonts.body.replace(/"/g, "'")
382
268
  const out = []
383
- if (section.quote.length > 0) out.push(quoteSlideFrom(section, ui))
384
- if (section.table !== null) out.push(tableSlideFrom(section, ui))
385
- if (out.length > 0 && section.notes.length > 0) out[0].notes = section.notes.join('\n')
386
- return out
387
- }
388
-
389
- export function parseMarkdownDeck(titleInput, content, lang = 'zh') {
390
- const language = resolveLanguage(lang)
391
- const ui = language.ui
392
- const title = String(titleInput ?? '').trim()
393
- let coverTitle = title
394
- let coverSubtitle = ''
395
- let coverSubtitleConsumed = false
396
-
397
- let body = String(content ?? '')
398
- .replace(/^\uFEFF/, '')
399
- .replace(/\r\n?/g, '\n')
400
- // 去除文档级 YAML frontmatter(如果有)
401
- body = body.replace(/^---[ \t]*\n[\s\S]*?\n---[ \t]*\n?/, '')
402
-
403
- const sections = []
404
- let current = null
405
- let firstH1Seen = false
406
-
407
- const flush = () => {
408
- if (current !== null && (current.heading !== '' || current.bullets.length > 0 || current.paragraphs.length > 0)) {
409
- sections.push(current)
410
- }
411
- current = null
412
- }
413
-
414
- for (const rawLine of body.split('\n')) {
415
- const line = rawLine.trim()
416
- if (line === '') {
417
- // 无标题分组按空行分段,保证「文档无标题」时按段落生成幻灯片
418
- if (current !== null && current.heading === '') flush()
419
- continue
420
- }
421
-
422
- const headingMatch = /^(#{1,6})\s+(.+)$/.exec(line)
423
- if (headingMatch !== null) {
424
- const level = headingMatch[1].length
425
- const heading = stripInlineMarkdown(headingMatch[2])
426
- if (level === 1 && !firstH1Seen) {
427
- firstH1Seen = true
428
- if (coverTitle === '') coverTitle = heading
429
- flush()
430
- current = createSection(heading, level, true)
431
- continue
432
- }
433
- flush()
434
- current = createSection(heading, level, false)
435
- continue
436
- }
437
-
438
- const bulletMatch = /^\s*(?:[-*+]|\d+[.)])\s+(.+)$/.exec(line)
439
- if (bulletMatch !== null) {
440
- const bullet = stripInlineMarkdown(bulletMatch[1])
441
- if (bullet !== '') {
442
- if (current === null) current = createSection()
443
- current.bullets.push(bullet)
444
- }
445
- continue
446
- }
447
-
448
- // 演讲者备注:`<!-- 备注: ... -->` / `<!-- note: ... -->` 附到当前页
449
- const notesMatch = NOTES_COMMENT.exec(line)
450
- if (notesMatch !== null && notesMatch[1].trim() !== '') {
451
- if (current === null) current = createSection()
452
- current.notes.push(notesMatch[1].trim())
453
- continue
454
- }
455
-
456
- // Markdown 表格:连续的 | ... | 行,第二行是分隔线
457
- const tableCells = splitTableRow(line)
458
- if (tableCells !== null) {
459
- if (current === null) current = createSection()
460
- if (isTableSeparator(tableCells)) continue
461
- if (current.table === null) {
462
- current.table = { header: tableCells.map((cell) => stripInlineMarkdown(cell)), rows: [] }
463
- } else if (current.table.rows.length < 12) {
464
- current.table.rows.push(tableCells.map((cell) => stripInlineMarkdown(cell)))
465
- }
466
- continue
467
- }
468
-
469
- // 金句:`>` 引用块(最后一行 `—— 出处` 识别为署名)
470
- const quoteMatch = /^>\s?(.*)$/.exec(line)
471
- if (quoteMatch !== null) {
472
- const quoted = stripInlineMarkdown(quoteMatch[1])
473
- if (quoted !== '') {
474
- if (current === null) current = createSection()
475
- current.quote.push(quoted)
476
- }
477
- continue
478
- }
479
-
480
- const paragraph = stripInlineMarkdown(line)
481
- if (paragraph === '') continue
482
- if (current === null) current = createSection()
483
- current.paragraphs.push(paragraph)
484
- }
485
- flush()
486
-
487
- const slides = []
488
- const coverSource = sections.find((section) => section.coverOnly === true)
489
- if (coverSource !== null && coverSource !== undefined) {
490
- const coverText = coverSource.paragraphs[0] ?? coverSource.bullets[0] ?? ''
491
- if (coverSubtitle === '') {
492
- coverSubtitle = truncate(coverText, 180)
493
- coverSubtitleConsumed = true
494
- }
495
- }
496
-
497
- let bodySections = sections.filter((section) => section.coverOnly !== true)
498
- // 首个 H1 既是封面又把所有要点收在封面节里时,把封面副标题之外的剩余要点
499
- // 提升为一个无标题节,走下面的要点页生成逻辑,避免丢掉内容。
500
- if (bodySections.length === 0 && coverSource !== null && coverSource !== undefined) {
501
- const usedParagraph = coverSource.paragraphs.length > 0
502
- const extras = [
503
- ...(usedParagraph ? coverSource.bullets : coverSource.bullets.slice(1)),
504
- ...coverSource.paragraphs.slice(usedParagraph ? 1 : 0),
505
- ]
506
- if (extras.length > 0) {
507
- const synthetic = createSection()
508
- synthetic.bullets = extras
509
- bodySections = [synthetic]
510
- }
511
- }
512
-
513
- if (bodySections.length === 0) {
514
- // 一句话 / 无结构输入:封面 + 核心观点 + 结束页(仍是完整的三页演示文稿)
515
- const allText = coverSource !== null && coverSource !== undefined
516
- ? [...coverSource.bullets, ...coverSource.paragraphs].join(' ')
517
- : String(content ?? '').trim()
518
- if (coverSubtitle === '') coverSubtitle = truncate(splitSentences(allText)[0] ?? '', 180)
519
- slides.push({ layout: 'cover', kicker: ui.coverKicker, title: coverTitle || 'Untitled', subtitle: coverSubtitle })
520
- if (coverSubtitle !== '') {
521
- slides.push({ layout: 'statement', kicker: ui.statementKicker, title: coverSubtitle, subtitle: coverTitle })
522
- }
523
- slides.push({ layout: 'closing', title: ui.closingTitle, subtitle: coverTitle || 'Untitled' })
524
- return { title: coverTitle || 'Untitled', subtitle: coverSubtitle, slides }
525
- }
526
-
527
- const hadHeadings = bodySections.some((section) => section.heading !== '')
528
-
529
- if (!hadHeadings) {
530
- // 无标题文档:第一段摘要作封面副标题,后续段落拆成要点页
531
- const ordered = bodySections.map((section) => ({
532
- section,
533
- sentences: [...section.bullets, ...section.paragraphs].flatMap((part) => splitSentences(part)),
534
- }))
535
- const firstSentence = ordered[0]?.sentences[0] ?? ''
536
- if (coverSubtitle === '') coverSubtitle = truncate(firstSentence, 180)
537
- const bodySlides = []
538
- let pointIndex = 0
539
- ordered.forEach((group, groupIndex) => {
540
- const specials = specialSlidesFor(group.section, ui)
541
- bodySlides.push(...specials)
542
- const sentences = (groupIndex === 0 && !coverSubtitleConsumed) ? group.sentences.slice(1) : group.sentences
543
- for (const points of chunk(sentences, 5)) {
544
- pointIndex += 1
545
- const slide = {
546
- layout: 'bullets',
547
- kicker: ui.pointKicker + ' ' + pointIndex,
548
- title: truncate(points[0], 40) || ui.pointKicker + ' ' + pointIndex,
549
- bullets: points,
550
- }
551
- if (specials.length === 0 && group.section.notes.length > 0) slide.notes = group.section.notes.join('\n')
552
- bodySlides.push(slide)
553
- }
554
- })
555
- slides.push({ layout: 'cover', kicker: ui.coverKicker, title: coverTitle || 'Untitled', subtitle: coverSubtitle })
556
- if (bodySlides.length === 0) {
557
- if (coverSubtitle !== '') {
558
- slides.push({ layout: 'statement', kicker: ui.statementKicker, title: coverSubtitle, subtitle: coverTitle || 'Untitled' })
559
- }
560
- } else {
561
- slides.push(...bodySlides)
562
- }
563
- slides.push({ layout: 'closing', title: ui.closingTitle, subtitle: coverTitle || 'Untitled' })
564
- return { title: coverTitle || 'Untitled', subtitle: coverSubtitle, slides }
565
- }
566
-
567
- slides.push({ layout: 'cover', kicker: ui.coverKicker, title: coverTitle || 'Untitled', subtitle: coverSubtitle })
568
- let pointIndex = 0
569
- for (const section of bodySections) {
570
- const notes = section.notes.join('\n')
571
- const specials = specialSlidesFor(section, ui)
572
- slides.push(...specials)
573
- if (section.heading === '') {
574
- const points = [...section.bullets, ...section.paragraphs]
575
- .flatMap((part) => splitSentences(part))
576
- // 超过 8 条自动续页,不再静默丢弃;备注只挂在第一页
577
- for (const [pageIndex, pagePoints] of chunk(points, 8).entries()) {
578
- pointIndex += 1
579
- const slide = {
580
- layout: 'bullets',
581
- kicker: ui.pointKicker + ' ' + pointIndex,
582
- title: truncate(pagePoints[0], 40) || ui.pointKicker + ' ' + pointIndex,
583
- bullets: pagePoints,
584
- }
585
- if (pageIndex === 0 && specials.length === 0 && notes !== '') slide.notes = notes
586
- slides.push(slide)
587
- }
588
- continue
589
- }
590
- const points = [
591
- ...section.bullets,
592
- ...section.paragraphs.flatMap((part) => splitSentences(part)),
593
- ]
594
- const pages = chunk(points, 8)
595
- if (pages.length > 0) {
596
- // 超过 8 条自动续页,不再静默丢弃;备注只挂在第一页
597
- pages.forEach((pagePoints, pageIndex) => {
598
- const label = pageIndex === 0 ? section.heading : section.heading + '(续)'
599
- const slide = { layout: 'bullets', kicker: label, title: label, bullets: pagePoints }
600
- if (pageIndex === 0 && specials.length === 0 && notes !== '') slide.notes = notes
601
- slides.push(slide)
602
- })
603
- } else if (specials.length === 0) {
604
- const slide = { layout: 'section', kicker: section.heading, title: section.heading }
605
- if (notes !== '') slide.notes = notes
606
- slides.push(slide)
607
- }
608
- }
609
- slides.push({ layout: 'closing', title: ui.closingTitle, subtitle: coverTitle || 'Untitled' })
610
- return { title: coverTitle || 'Untitled', subtitle: coverSubtitle, slides }
611
- }
612
-
613
- const SLIDE_LAYOUTS = new Set(['cover', 'section', 'bullets', 'statement', 'closing', 'quote', 'table'])
614
-
615
- function normalizeSlide(raw, index) {
616
- const source = (raw !== null && typeof raw === 'object') ? raw : {}
617
- const layout = SLIDE_LAYOUTS.has(source.layout) ? source.layout : 'bullets'
618
- const title = stripInlineMarkdown(source.title ?? '')
619
- const subtitle = stripInlineMarkdown(source.subtitle ?? '')
620
- const kicker = stripInlineMarkdown(source.kicker ?? '')
621
- const text = stripInlineMarkdown(source.text ?? '')
622
- // 备注保留换行(放映面板与备注页都按原文显示),只做转义,不做 Markdown 清洗
623
- const notes = String(source.notes ?? '').trim()
624
- let bullets = []
625
- if (Array.isArray(source.bullets)) {
626
- bullets = source.bullets.map((item) => stripInlineMarkdown(String(item))).filter(Boolean)
627
- } else if (typeof source.bullets === 'string' && source.bullets.trim() !== '') {
628
- bullets = splitSentences(source.bullets)
629
- }
630
- if (layout === 'statement' && title === '' && text !== '') {
631
- return { layout, kicker, title: text, subtitle: subtitle || '', bullets, ...(notes !== '' ? { notes } : {}) }
632
- }
633
- if (layout === 'quote') {
634
- const quoteText = title !== '' ? title : text
635
- if (quoteText === '') return { layout: 'statement', kicker, title: subtitle, subtitle: '', bullets, ...(notes !== '' ? { notes } : {}) }
636
- return { layout, kicker, title: truncate(quoteText, 220), subtitle, ...(notes !== '' ? { notes } : {}) }
637
- }
638
- if (layout === 'table') {
639
- let rows = []
640
- if (Array.isArray(source.rows)) {
641
- rows = source.rows
642
- .map((row) => (Array.isArray(row) ? row : [row]).map((cell) => stripInlineMarkdown(String(cell))))
643
- .filter((row) => row.some((cell) => cell !== ''))
644
- .slice(0, 9)
645
- .map((row) => row.slice(0, 8).map((cell) => truncate(cell, 60)))
646
- }
647
- if (rows.length === 0) {
648
- // 没有表格数据的 table 页退化成要点页,避免产出空白版式
649
- return { layout: 'bullets', kicker, title, subtitle, bullets, ...(notes !== '' ? { notes } : {}) }
650
- }
651
- return { layout, kicker: kicker || title, title, rows, ...(notes !== '' ? { notes } : {}) }
652
- }
653
- return { layout, kicker, title, subtitle, text, bullets, ...(notes !== '' ? { notes } : {}) }
654
- }
655
-
656
- export function normalizeSlides(rawSlides, maxSlides = 60) {
657
- if (!Array.isArray(rawSlides) || rawSlides.length === 0) {
658
- throw new Error('dsh-ppt:slides 必须是非空数组(每个元素是 { layout, title, subtitle, kicker, bullets } 对象)')
659
- }
660
- const limit = clampInt(maxSlides, 60, 1, 120)
661
- const bounded = rawSlides.length > limit && limit >= 3
662
- ? [rawSlides[0], ...rawSlides.slice(1, limit - 1), rawSlides[rawSlides.length - 1]]
663
- : rawSlides.slice(0, limit)
664
- const slides = bounded.map(normalizeSlide)
665
- if (slides.length === 0) throw new Error('dsh-ppt:slides 规范化后为空')
666
- return slides
269
+ out.push('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 540" width="960" height="540" role="img" aria-label="' + escapeXml(theme.id + ' ' + pick(theme.name)) + '">')
270
+ out.push('<rect width="960" height="540" fill="' + p.bg + '"/>')
271
+ out.push('<rect x="0" y="0" width="960" height="6" fill="' + p.accent + '"/><rect x="0" y="534" width="960" height="6" fill="' + p.accent2 + '"/>')
272
+ out.push('<rect x="36" y="40" width="560" height="360" rx="16" fill="' + p.panel + '" stroke="' + hexToRgba(p.muted, 0.45) + '"/>')
273
+ out.push('<text x="64" y="92" fill="' + p.accent + '" font-family="' + escapeXml(bodyFont) + '" font-size="14" font-weight="700" letter-spacing="3">' + escapeXml(pick(theme.mood).toUpperCase()) + '</text>')
274
+ out.push('<text x="64" y="158" fill="' + p.fg + '" font-family="' + escapeXml(font) + '" font-size="42" font-weight="800">' + escapeXml('Aa ' + pick(theme.name)) + '</text>')
275
+ out.push('<circle cx="72" cy="206" r="5" fill="' + p.accent + '"/><rect x="92" y="199" width="360" height="12" rx="6" fill="' + hexToRgba(p.fg, 0.75) + '"/>')
276
+ out.push('<circle cx="72" cy="240" r="5" fill="' + p.accent + '"/><rect x="92" y="233" width="300" height="12" rx="6" fill="' + hexToRgba(p.fg, 0.55) + '"/>')
277
+ out.push('<circle cx="72" cy="274" r="5" fill="' + p.accent + '"/><rect x="92" y="267" width="330" height="12" rx="6" fill="' + hexToRgba(p.fg, 0.55) + '"/>')
278
+ out.push('<rect x="64" y="312" width="500" height="34" rx="6" fill="' + p.accent + '"/>')
279
+ out.push('<text x="78" y="334" fill="' + p.bg + '" font-family="' + escapeXml(bodyFont) + '" font-size="14" font-weight="700">dsh-ppt</text>')
280
+ out.push('<text x="470" y="334" fill="' + p.bg + '" font-family="' + escapeXml(bodyFont) + '" font-size="14" font-weight="700" text-anchor="end">1,234</text>')
281
+ out.push('<rect x="64" y="346" width="500" height="2" fill="' + hexToRgba(p.muted, 0.5) + '"/>')
282
+ out.push('<text x="64" y="378" fill="' + p.muted + '" font-family="' + escapeXml(bodyFont) + '" font-size="13">' + escapeXml(theme.id + ' · ' + (theme.dark ? L.dark : L.light) + ' · v' + DECK_VERSION) + '</text>')
283
+ const swatches = ['bg', 'panel', 'fg', 'muted', 'accent', 'accent2']
284
+ const labels = ['bg', 'panel', 'fg', 'muted', 'accent', 'accent2']
285
+ out.push('<text x="632" y="76" fill="' + p.muted + '" font-family="' + escapeXml(bodyFont) + '" font-size="13" font-weight="700" letter-spacing="2">' + escapeXml(L.palette.toUpperCase()) + '</text>')
286
+ swatches.forEach((key, i) => {
287
+ const y = 96 + i * 62
288
+ out.push('<rect x="632" y="' + y + '" width="44" height="44" rx="10" fill="' + p[key] + '" stroke="' + hexToRgba(p.muted, 0.45) + '"/>')
289
+ out.push('<text x="692" y="' + (y + 20) + '" fill="' + p.fg + '" font-family="' + escapeXml(bodyFont) + '" font-size="14" font-weight="600">' + escapeXml(labels[i]) + '</text>')
290
+ out.push('<text x="692" y="' + (y + 38) + '" fill="' + p.muted + '" font-family="' + escapeXml(bodyFont) + '" font-size="13">' + escapeXml(String(p[key]).toUpperCase()) + '</text>')
291
+ })
292
+ out.push('<text x="632" y="508" fill="' + p.muted + '" font-family="' + escapeXml(bodyFont) + '" font-size="12">' + escapeXml(pick(theme.bestFor)).slice(0, 44) + '</text>')
293
+ out.push('</svg>')
294
+ return out.join('')
667
295
  }
668
296
 
669
- // ---------------------------------------------------------------------------
670
- // 构建入口
671
- // ---------------------------------------------------------------------------
672
-
673
- export function normalizeBuildOptions(options = {}) {
674
- const title = String(options.title ?? '').trim()
675
- if (title === '') throw new Error('dsh-ppt:title 不能为空')
676
- const theme = resolveTheme(options.theme)
677
- const language = resolveLanguage(options.lang)
678
- const motion = resolveMotion(options.motion)
679
- const maxSlides = clampInt(options.maxSlides, 60, 3, 120)
680
- let deck
681
- if (Array.isArray(options.slides) && options.slides.length > 0) {
682
- deck = {
683
- title,
684
- subtitle: stripInlineMarkdown(options.subtitle ?? ''),
685
- slides: normalizeSlides(options.slides, maxSlides),
686
- }
687
- } else {
688
- const content = String(options.content ?? '').trim()
689
- if (content === '') throw new Error('dsh-ppt:content 不能为空(或用 slides 传结构化幻灯片)')
690
- deck = parseMarkdownDeck(title, content, language.id)
691
- const slideLimit = clampInt(maxSlides, 60, 3, 120)
692
- if (deck.slides.length > slideLimit) {
693
- deck.slides = [deck.slides[0], ...deck.slides.slice(1, slideLimit - 1), deck.slides[deck.slides.length - 1]]
694
- }
695
- }
696
- if (deck.slides.length < 1) throw new Error('dsh-ppt:没有可生成的幻灯片')
697
- const outputDir = resolvePath(String(options.outputDir ?? '.').trim() || '.')
698
- const fileName = sanitizeFileName(options.fileName ?? title)
297
+ /** 自包含主题对比页:5 套主题并排,含色板与用法。 */
298
+ export function renderThemePreviewHtml(lang = 'zh') {
299
+ const L = themePages(lang === 'en' ? 'en' : 'zh')
300
+ const cards = THEME_IDS.map((id) => {
301
+ const theme = THEMES[id]
302
+ const pick = (pair) => (lang === 'en' ? pair.en : pair.zh)
303
+ const chips = Object.keys(theme.palette).map((key) =>
304
+ '<span class="chip"><i style="background:' + theme.palette[key] + '"></i>' + escapeHtml(String(theme.palette[key]).toUpperCase()) + '</span>').join('')
305
+ return '<figure class="card" id="theme-' + escapeHtml(id) + '">' +
306
+ renderThemeSvg(theme, lang === 'en' ? 'en' : 'zh') +
307
+ '<figcaption><div class="row"><strong>' + escapeHtml(id) + '</strong><span class="badge">' + escapeHtml(pick(theme.name)) + '</span></div>' +
308
+ '<p class="muted">' + escapeHtml(pick(theme.mood)) + ' · ' + escapeHtml(pick(theme.bestFor)) + '</p>' +
309
+ '<p class="chips">' + chips + '</p>' +
310
+ '<p class="usage">' + escapeHtml(L.usage) + ': <code>' + escapeHtml(id) + '</code></p></figcaption></figure>'
311
+ }).join('')
312
+ return '<!DOCTYPE html>' + eolSafe('<html lang="zh-CN">') +
313
+ '<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">' +
314
+ '<title>' + escapeHtml(L.title) + '</title><style>' +
315
+ 'body{margin:0;background:#0b0f17;color:#e8f1ff;font-family:"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;padding:28px}' +
316
+ 'h1{font-size:26px;margin:0 0 6px}p.sub{color:#8b98ad;margin:0 0 24px;font-size:14px}' +
317
+ '.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(430px,1fr));gap:22px}' +
318
+ '.card{margin:0;background:#111827;border:1px solid #263043;border-radius:16px;overflow:hidden}' +
319
+ '.card svg{display:block;width:100%;height:auto}' +
320
+ 'figcaption{padding:14px 16px 16px}.row{display:flex;align-items:center;gap:10px;font-size:16px}' +
321
+ '.badge{color:#8b98ad;font-size:13px}.muted{color:#8b98ad;font-size:13px;margin:6px 0 10px;line-height:1.5}' +
322
+ '.chips{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 10px}.chip{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:#aab6c9;background:#0b0f17;border:1px solid #263043;border-radius:99px;padding:3px 9px}' +
323
+ '.chip i{width:10px;height:10px;border-radius:3px;display:inline-block}' +
324
+ '.usage{margin:0;font-size:13px;color:#aab6c9}code{background:#0b0f17;border:1px solid #263043;border-radius:6px;padding:1px 6px}' +
325
+ '@media (prefers-reduced-motion: reduce){*{transition:none!important;animation:none!important}}' +
326
+ '</style></head><body><h1>' + escapeHtml(L.title) + '</h1><p class="sub">' + escapeHtml(L.hint) + ' · dsh-ppt v' + escapeHtml(DECK_VERSION) + '</p>' +
327
+ '<div class="grid">' + cards + '</div></body></html>'
328
+ }
329
+
330
+ function eolSafe(text) { return text }
331
+
332
+ /** 写主题对比页 + 每套主题 SVG 色板卡;默认不覆盖同名文件。 */
333
+ export function buildThemePreview(options = {}) {
334
+ const langInput = typeof options.lang === 'string' && options.lang.trim() !== '' ? options.lang.trim() : 'zh'
335
+ const language = resolveLanguage(langInput)
336
+ const outputDir = resolvePath(String(options.outputDir ?? '.'))
337
+ mkdirSync(outputDir, { recursive: true })
699
338
  const overwrite = options.overwrite === true
700
- return { title, theme, language, motion, deck, outputDir, fileName, overwrite }
701
- }
702
-
703
- /**
704
- * 三件套落盘:三份内容全部先写同目录临时文件,再逐个 rename 提交。
705
- * 任一步失败都清理临时文件,并把已提交的目标恢复为调用前的内容,
706
- * 避免出现「json/html 已更新、pptx 还是旧的」这类混版状态。
707
- */
708
- function commitDeckArtifacts(artifacts) {
709
- const stamp = process.pid.toString(36) + '-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8)
710
- const items = artifacts.map((item, index) => ({ ...item, tempPath: item.path + '.' + stamp + '-' + index + '.tmp' }))
711
- const removeTemp = (item) => {
712
- try {
713
- rmSync(item.tempPath, { force: true })
714
- } catch {}
715
- }
716
-
717
- // 阶段 0:记下已有产物内容用于回滚;读不出来(如被同名目录占用)先报错,不碰任何文件。
718
- const previous = new Map()
719
- for (const item of items) {
720
- if (!existsSync(item.path)) continue
721
- try {
722
- previous.set(item.path, readFileSync(item.path))
723
- } catch (error) {
724
- throw new Error('dsh-ppt:三件套写入失败(' + item.path + ' 已存在但无法读取),原文件未改动:' + error.message)
339
+ const pickPath = (base, ext) => {
340
+ const first = resolvePath(joinPath(outputDir, base + ext))
341
+ if (overwrite || !existsSync(first)) return first
342
+ for (let i = 1; i < 1000; i += 1) {
343
+ const candidate = resolvePath(joinPath(outputDir, base + '-' + i + ext))
344
+ if (!existsSync(candidate)) return candidate
725
345
  }
346
+ throw new Error('dsh-ppt:找不到可用的预览文件名(同名前缀超过 999 个),请允许 overwrite。')
726
347
  }
727
-
728
- // 阶段 1:全部写临时文件;这一步失败时目标文件尚未被改动。
729
- let written = 0
730
- try {
731
- for (const item of items) {
732
- writeFileSync(item.tempPath, item.data, item.encoding)
733
- written += 1
734
- }
735
- } catch (error) {
736
- for (const item of items.slice(0, written + 1)) removeTemp(item)
737
- throw new Error('dsh-ppt:写入临时文件失败(' + items[written].path + '),原三件套未改动:' + error.message)
738
- }
739
-
740
- // 阶段 2:逐个 rename 提交;中途失败则把已提交的目标回滚成旧内容。
741
- const committed = []
742
- try {
743
- for (const item of items) {
744
- renameSync(item.tempPath, item.path)
745
- committed.push(item)
746
- }
747
- } catch (error) {
748
- const failedPath = items[committed.length].path
749
- for (const item of items) removeTemp(item)
750
- for (const item of committed) {
751
- try {
752
- const previousData = previous.get(item.path)
753
- if (previousData === undefined) rmSync(item.path, { force: true })
754
- else writeFileSync(item.path, previousData)
755
- } catch {}
756
- }
757
- throw new Error('dsh-ppt:提交三件套失败(' + failedPath + '),已回滚为原文件:' + error.message)
758
- }
759
- }
760
-
761
- export function buildDeck(options = {}) {
762
- const normalized = normalizeBuildOptions(options)
763
- const { title, theme, language, motion, deck, outputDir, overwrite } = normalized
764
- mkdirSync(outputDir, { recursive: true })
765
- const fileName = resolveDeckFileName(outputDir, normalized.fileName, overwrite)
766
-
767
- const manifest = {
768
- version: DECK_VERSION,
769
- title,
770
- theme: theme.id,
771
- language: language.id,
772
- motion,
773
- slideCount: deck.slides.length,
774
- slides: deck.slides,
775
- }
776
- const jsonPath = resolvePath(outputDir, fileName + '.json')
777
- const htmlPath = resolvePath(outputDir, fileName + '.html')
778
- const pptxPath = resolvePath(outputDir, fileName + '.pptx')
779
-
780
- // 先生成三份内容再统一提交:生成阶段抛错时也不会留下半套文件。
781
- commitDeckArtifacts([
782
- { path: jsonPath, data: JSON.stringify(manifest, null, 2) + '\n', encoding: 'utf8' },
783
- { path: htmlPath, data: renderHtml(manifest, theme, language), encoding: 'utf8' },
784
- { path: pptxPath, data: buildPptx(manifest, theme, language) },
785
- ])
786
-
787
- return {
788
- ok: true,
789
- title,
790
- theme: theme.id,
791
- language: language.id,
792
- slideCount: deck.slides.length,
793
- outputDir,
794
- files: {
795
- html: htmlPath,
796
- pptx: pptxPath,
797
- json: jsonPath,
798
- },
799
- htmlPath,
800
- pptxPath,
801
- jsonPath,
802
- }
803
- }
804
-
805
- // ---------------------------------------------------------------------------
806
- // HTML 网页放映
807
- // ---------------------------------------------------------------------------
808
-
348
+ const htmlPath = pickPath('themes-preview', '.html')
349
+ writeFileSync(htmlPath, renderThemePreviewHtml(language.id), 'utf8')
350
+ const svgs = THEME_IDS.map((id) => {
351
+ const svgPath = pickPath('theme-' + id, '.svg')
352
+ writeFileSync(svgPath, renderThemeSvg(id, language.id), 'utf8')
353
+ return { id, path: svgPath }
354
+ })
355
+ return { ok: true, outputDir, htmlPath, svgs, themeCount: THEME_IDS.length, language: language.id }
356
+ }
357
+
358
+
359
+ export function resolveTheme(input) {
360
+ const id = String(input ?? DEFAULT_THEME).trim().toLowerCase()
361
+ const theme = THEMES[id]
362
+ if (!theme) {
363
+ throw new Error('dsh-ppt:未知主题 "' + id + '",可选:' + THEME_IDS.join(' / ') + '(默认 ' + DEFAULT_THEME + ')')
364
+ }
365
+ return theme
366
+ }
367
+
368
+ export function resolveLanguage(input) {
369
+ const id = String(input ?? 'zh').trim().toLowerCase()
370
+ const language = LANGUAGES[id]
371
+ if (!language) {
372
+ throw new Error('dsh-ppt:未知语言 "' + id + '",可选:zh / en / bilingual')
373
+ }
374
+ return language
375
+ }
376
+
377
+ export function resolveMotion(input) {
378
+ if (input === undefined || input === null || input === '') return true
379
+ if (input === true || input === 'on') return true
380
+ if (input === false || input === 'off') return false
381
+ throw new Error('dsh-ppt:未知 motion 值 "' + String(input) + '",可选:on / off(默认 on)')
382
+ }
383
+
384
+ export function listThemes(lang = 'zh') {
385
+ const pick = (pair) => (lang === 'en' ? pair.en : pair.zh)
386
+ return THEME_IDS.map((id) => {
387
+ const theme = THEMES[id]
388
+ return {
389
+ id,
390
+ name: pick(theme.name),
391
+ mood: pick(theme.mood),
392
+ bestFor: pick(theme.bestFor),
393
+ dark: theme.dark,
394
+ palette: { ...theme.palette },
395
+ fonts: { ...theme.fonts },
396
+ }
397
+ })
398
+ }
399
+
400
+ // ---------------------------------------------------------------------------
401
+ // 文本工具
402
+ // ---------------------------------------------------------------------------
403
+
404
+ export function clampInt(value, fallback, min, max) {
405
+ const n = typeof value === 'number' ? Math.trunc(value) : fallback
406
+ if (!Number.isFinite(n)) return fallback
407
+ return Math.min(max, Math.max(min, n))
408
+ }
409
+
410
+ // Windows 保留设备名:首个点之前的主名命中即不可用(NUL、com1、aux.report.html 都算)。
411
+ const WINDOWS_RESERVED_FILE_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i
412
+
413
+ export function sanitizeFileName(input) {
414
+ const base = String(input ?? 'deck').trim().replace(/\.(html?|pptx|json)$/i, '')
415
+ let cleaned = base
416
+ .replace(/[<>:"/\\|?*\u0000-\u001F]/g, '-')
417
+ .replace(/\s+/g, '-')
418
+ .replace(/-+/g, '-')
419
+ .replace(/^-+|-+$/g, '')
420
+ if (WINDOWS_RESERVED_FILE_NAME.test(cleaned)) cleaned = 'deck-' + cleaned
421
+ return cleaned.slice(0, 120) || 'deck'
422
+ }
423
+
424
+ const DECK_ARTIFACT_EXTENSIONS = ['.html', '.pptx', '.json']
425
+
426
+ /**
427
+ * 为三件套选择同一个可用文件名前缀。默认不覆盖:任一产物已存在时,
428
+ * 整组改用 -1/-2… 后缀,避免新旧 deck 被静默混写。
429
+ */
430
+ function resolveDeckFileName(outputDir, requestedFileName, overwrite) {
431
+ // 一次 readdir 建集,替代逐个候选 existsSync 探测(最坏 ~3000 次 stat);
432
+ // 统一小写比较,避免 Windows 大小写不敏感文件系统把已占用的名字判成可用。
433
+ const existing = new Set(readdirSync(outputDir).map((name) => name.toLowerCase()))
434
+ const isAvailable = (candidate) => DECK_ARTIFACT_EXTENSIONS.every((ext) => !existing.has((candidate + ext).toLowerCase()))
435
+ if (overwrite || isAvailable(requestedFileName)) return requestedFileName
436
+ for (let index = 1; index < 1000; index += 1) {
437
+ const candidate = requestedFileName + '-' + index
438
+ if (isAvailable(candidate)) return candidate
439
+ }
440
+ throw new Error('dsh-ppt:找不到可用的输出文件名(同名前缀超过 999 个),请更换 fileName 或显式允许 overwrite。')
441
+ }
442
+
443
+ export function escapeXml(value) {
444
+ return String(value ?? '')
445
+ .replace(/&/g, '&amp;')
446
+ .replace(/</g, '&lt;')
447
+ .replace(/>/g, '&gt;')
448
+ .replace(/"/g, '&quot;')
449
+ .replace(/'/g, '&apos;')
450
+ }
451
+
452
+ export function escapeHtml(value) {
453
+ return String(value ?? '')
454
+ .replace(/&/g, '&amp;')
455
+ .replace(/</g, '&lt;')
456
+ .replace(/>/g, '&gt;')
457
+ .replace(/"/g, '&quot;')
458
+ }
459
+
460
+ export function stripInlineMarkdown(value) {
461
+ return String(value ?? '')
462
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
463
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
464
+ .replace(/`([^`]*)`/g, '$1')
465
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
466
+ .replace(/__([^_]+)__/g, '$1')
467
+ .replace(/\*([^*\n]+)\*/g, '$1')
468
+ .replace(/_([^_\n]+)_/g, '$1')
469
+ .replace(/<[^>]+>/g, '')
470
+ .replace(/\s+/g, ' ')
471
+ .trim()
472
+ }
473
+
474
+ export function splitSentences(value) {
475
+ const text = String(value ?? '').trim()
476
+ if (text === '') return []
477
+ const parts = text.split(/(?<=[。!?])|(?<=[.!?…])\s+/).map((part) => part.trim()).filter(Boolean)
478
+ return parts.length > 0 ? parts : [text]
479
+ }
480
+
481
+ export function truncate(value, max) {
482
+ const text = String(value ?? '').trim()
483
+ if (text.length <= max) return text
484
+ return text.slice(0, max - 1).replace(/\s+\S*$/, '') + '…'
485
+ }
486
+
487
+ function chunk(items, size) {
488
+ const out = []
489
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size))
490
+ return out
491
+ }
492
+
493
+ // ---------------------------------------------------------------------------
494
+ // Markdown → deck
495
+ // ---------------------------------------------------------------------------
496
+
497
+ function createSection(heading = '', level = 0, coverOnly = false) {
498
+ return { heading, level, coverOnly, bullets: [], paragraphs: [], quote: [], table: null, notes: [] }
499
+ }
500
+
501
+ function splitTableRow(line) {
502
+ const trimmed = line.trim()
503
+ const match = /^\|(.+)\|$/.exec(trimmed)
504
+ if (match === null) return null
505
+ return match[1].split('|').map((cell) => cell.trim())
506
+ }
507
+
508
+ function isTableSeparator(cells) {
509
+ return cells.length > 0 && cells.every((cell) => /^:?-{2,}:?$/.test(cell) || /^:?-+:?$/.test(cell))
510
+ }
511
+
512
+ const NOTES_COMMENT = /^<!--\s*(?:notes?|备注)\s*[::]\s*([\s\S]*?)\s*-->$/
513
+
514
+ function quoteSlideFrom(section, ui) {
515
+ const lines = [...section.quote]
516
+ let attribution = ''
517
+ const attrMatch = /^(?:——|—|--|-)\s*(.+)$/.exec(lines[lines.length - 1] ?? '')
518
+ if (attrMatch !== null && lines.length > 1) {
519
+ attribution = attrMatch[1]
520
+ lines.pop()
521
+ }
522
+ return { layout: 'quote', kicker: ui.quoteKicker, title: truncate(lines.join(' '), 220), subtitle: attribution }
523
+ }
524
+
525
+ function paginateTable(slide, continuation = '(续)') {
526
+ const rows = slide.rows
527
+ const columns = Math.max(...rows.map(row => row.length))
528
+ if (columns > 8) throw new Error('dsh-ppt:表格最多 8 列,请拆成多个表格后重试 / tables support up to 8 columns')
529
+ if (rows.some(row => row.some(cell => [...cell].length > 60))) {
530
+ throw new Error('dsh-ppt:表格单元格最多 60 个字符,请精简或拆分内容后重试 / cells support up to 60 characters')
531
+ }
532
+ const padded = rows.map(row => Array.from({ length: columns }, (_, i) => row[i] ?? ''))
533
+ const pages = chunk(padded.slice(1), 8)
534
+ if (pages.length === 0) pages.push([])
535
+ return pages.map((body, index) => {
536
+ const { notes, ...rest } = slide
537
+ const title = slide.title + (index === 0 ? '' : continuation)
538
+ // 同名 kicker/title 共用紧凑标题;续页不能凭空多出一行大标题挤压表格。
539
+ return { ...rest, title, kicker: slide.kicker === slide.title ? title : slide.kicker, rows: [padded[0], ...body],
540
+ ...(index === 0 && notes ? { notes } : {}) }
541
+ })
542
+ }
543
+
544
+ function tableSlidesFrom(section, ui) {
545
+ const table = section.table
546
+ const rows = [table.header, ...table.rows]
547
+ const heading = section.heading || ui.tableKicker
548
+ return paginateTable({ layout: 'table', kicker: heading, title: heading, rows }, ui.continuation)
549
+ }
550
+
551
+ /** 把一个 section 里的金句/表格拆成独立页;备注附着到第一张产出页。 */
552
+ function specialSlidesFor(section, ui) {
553
+ const out = []
554
+ if (section.quote.length > 0) out.push(quoteSlideFrom(section, ui))
555
+ if (section.table !== null) out.push(...tableSlidesFrom(section, ui))
556
+ if (out.length > 0 && section.notes.length > 0) out[0].notes = section.notes.join('\n')
557
+ return out
558
+ }
559
+
560
+ export function parseMarkdownDeck(titleInput, content, lang = 'zh') {
561
+ const language = resolveLanguage(lang)
562
+ const ui = language.ui
563
+ const title = String(titleInput ?? '').trim()
564
+ let coverTitle = title
565
+ let coverSubtitle = ''
566
+ let coverSubtitleConsumed = false
567
+
568
+ let body = String(content ?? '')
569
+ .replace(/^\uFEFF/, '')
570
+ .replace(/\r\n?/g, '\n')
571
+ // 去除文档级 YAML frontmatter(如果有)
572
+ body = body.replace(/^---[ \t]*\n[\s\S]*?\n---[ \t]*\n?/, '')
573
+
574
+ const sections = []
575
+ let current = null
576
+ let firstH1Seen = false
577
+
578
+ const flush = () => {
579
+ if (current !== null && (current.heading !== '' || current.bullets.length > 0 || current.paragraphs.length > 0
580
+ || current.table !== null || current.quote.length > 0)) {
581
+ sections.push(current)
582
+ }
583
+ current = null
584
+ }
585
+
586
+ for (const rawLine of body.split('\n')) {
587
+ const line = rawLine.trim()
588
+ if (line === '') {
589
+ // 无标题分组按空行分段,保证「文档无标题」时按段落生成幻灯片
590
+ if (current !== null && current.heading === '') flush()
591
+ continue
592
+ }
593
+
594
+ const headingMatch = /^(#{1,6})\s+(.+)$/.exec(line)
595
+ if (headingMatch !== null) {
596
+ const level = headingMatch[1].length
597
+ const heading = stripInlineMarkdown(headingMatch[2])
598
+ if (level === 1 && !firstH1Seen) {
599
+ firstH1Seen = true
600
+ if (coverTitle === '') coverTitle = heading
601
+ flush()
602
+ current = createSection(heading, level, true)
603
+ continue
604
+ }
605
+ flush()
606
+ current = createSection(heading, level, false)
607
+ continue
608
+ }
609
+
610
+ const bulletMatch = /^\s*(?:[-*+]|\d+[.)])\s+(.+)$/.exec(line)
611
+ if (bulletMatch !== null) {
612
+ const bullet = stripInlineMarkdown(bulletMatch[1])
613
+ if (bullet !== '') {
614
+ if (current === null) current = createSection()
615
+ current.bullets.push(bullet)
616
+ }
617
+ continue
618
+ }
619
+
620
+ // 演讲者备注:`<!-- 备注: ... -->` / `<!-- note: ... -->` 附到当前页
621
+ const notesMatch = NOTES_COMMENT.exec(line)
622
+ if (notesMatch !== null && notesMatch[1].trim() !== '') {
623
+ if (current === null) current = createSection()
624
+ current.notes.push(notesMatch[1].trim())
625
+ continue
626
+ }
627
+
628
+ // Markdown 表格:连续的 | ... | 行,第二行是分隔线
629
+ const tableCells = splitTableRow(line)
630
+ if (tableCells !== null) {
631
+ if (current === null) current = createSection()
632
+ if (isTableSeparator(tableCells)) continue
633
+ if (current.table === null) {
634
+ current.table = { header: tableCells.map((cell) => stripInlineMarkdown(cell)), rows: [] }
635
+ } else {
636
+ current.table.rows.push(tableCells.map((cell) => stripInlineMarkdown(cell)))
637
+ }
638
+ continue
639
+ }
640
+
641
+ // 金句:`>` 引用块(最后一行 `—— 出处` 识别为署名)
642
+ const quoteMatch = /^>\s?(.*)$/.exec(line)
643
+ if (quoteMatch !== null) {
644
+ const quoted = stripInlineMarkdown(quoteMatch[1])
645
+ if (quoted !== '') {
646
+ if (current === null) current = createSection()
647
+ current.quote.push(quoted)
648
+ }
649
+ continue
650
+ }
651
+
652
+ const paragraph = stripInlineMarkdown(line)
653
+ if (paragraph === '') continue
654
+ if (current === null) current = createSection()
655
+ current.paragraphs.push(paragraph)
656
+ }
657
+ flush()
658
+
659
+ const slides = []
660
+ const coverSource = sections.find((section) => section.coverOnly === true)
661
+ if (coverSource !== null && coverSource !== undefined) {
662
+ const coverText = coverSource.paragraphs[0] ?? coverSource.bullets[0] ?? ''
663
+ if (coverSubtitle === '') {
664
+ coverSubtitle = truncate(coverText, 180)
665
+ coverSubtitleConsumed = true
666
+ }
667
+ }
668
+
669
+ let bodySections = sections.filter((section) => section.coverOnly !== true)
670
+ // 首个 H1 既是封面又把所有要点收在封面节里时,把封面副标题之外的剩余要点
671
+ // 提升为一个无标题节,走下面的要点页生成逻辑,避免丢掉内容。
672
+ if (bodySections.length === 0 && coverSource !== null && coverSource !== undefined) {
673
+ const usedParagraph = coverSource.paragraphs.length > 0
674
+ const extras = [
675
+ ...(usedParagraph ? coverSource.bullets : coverSource.bullets.slice(1)),
676
+ ...coverSource.paragraphs.slice(usedParagraph ? 1 : 0),
677
+ ]
678
+ if (extras.length > 0) {
679
+ const synthetic = createSection()
680
+ synthetic.bullets = extras
681
+ bodySections = [synthetic]
682
+ }
683
+ }
684
+
685
+ // 表格和引用不能只挂在封面节上,否则首个 H1 后没有 H2 时会丢失。
686
+ if (coverSource && (coverSource.table !== null || coverSource.quote.length > 0)) {
687
+ const special = createSection()
688
+ special.table = coverSource.table
689
+ special.quote = coverSource.quote
690
+ special.notes = coverSource.notes
691
+ bodySections.unshift(special)
692
+ }
693
+
694
+ if (bodySections.length === 0) {
695
+ // 一句话 / 无结构输入:封面 + 核心观点 + 结束页(仍是完整的三页演示文稿)
696
+ const allText = coverSource !== null && coverSource !== undefined
697
+ ? [...coverSource.bullets, ...coverSource.paragraphs].join(' ')
698
+ : String(content ?? '').trim()
699
+ if (coverSubtitle === '') coverSubtitle = truncate(splitSentences(allText)[0] ?? '', 180)
700
+ slides.push({ layout: 'cover', kicker: ui.coverKicker, title: coverTitle || 'Untitled', subtitle: coverSubtitle })
701
+ if (coverSubtitle !== '') {
702
+ slides.push({ layout: 'statement', kicker: ui.statementKicker, title: coverSubtitle, subtitle: coverTitle })
703
+ }
704
+ slides.push({ layout: 'closing', title: ui.closingTitle, subtitle: coverTitle || 'Untitled' })
705
+ return { title: coverTitle || 'Untitled', subtitle: coverSubtitle, slides }
706
+ }
707
+
708
+ const hadHeadings = bodySections.some((section) => section.heading !== '')
709
+
710
+ if (!hadHeadings) {
711
+ // 无标题文档:第一段摘要作封面副标题,后续段落拆成要点页
712
+ const ordered = bodySections.map((section) => ({
713
+ section,
714
+ sentences: [...section.bullets, ...section.paragraphs].flatMap((part) => splitSentences(part)),
715
+ }))
716
+ const firstSentence = ordered[0]?.sentences[0] ?? ''
717
+ if (coverSubtitle === '') coverSubtitle = truncate(firstSentence, 180)
718
+ const bodySlides = []
719
+ let pointIndex = 0
720
+ ordered.forEach((group, groupIndex) => {
721
+ const specials = specialSlidesFor(group.section, ui)
722
+ bodySlides.push(...specials)
723
+ const sentences = (groupIndex === 0 && !coverSubtitleConsumed) ? group.sentences.slice(1) : group.sentences
724
+ for (const points of chunk(sentences, 5)) {
725
+ pointIndex += 1
726
+ const slide = {
727
+ layout: 'bullets',
728
+ kicker: ui.pointKicker + ' ' + pointIndex,
729
+ title: truncate(points[0], 40) || ui.pointKicker + ' ' + pointIndex,
730
+ bullets: points,
731
+ }
732
+ if (specials.length === 0 && group.section.notes.length > 0) slide.notes = group.section.notes.join('\n')
733
+ bodySlides.push(slide)
734
+ }
735
+ })
736
+ slides.push({ layout: 'cover', kicker: ui.coverKicker, title: coverTitle || 'Untitled', subtitle: coverSubtitle })
737
+ if (bodySlides.length === 0) {
738
+ if (coverSubtitle !== '') {
739
+ slides.push({ layout: 'statement', kicker: ui.statementKicker, title: coverSubtitle, subtitle: coverTitle || 'Untitled' })
740
+ }
741
+ } else {
742
+ slides.push(...bodySlides)
743
+ }
744
+ slides.push({ layout: 'closing', title: ui.closingTitle, subtitle: coverTitle || 'Untitled' })
745
+ return { title: coverTitle || 'Untitled', subtitle: coverSubtitle, slides }
746
+ }
747
+
748
+ slides.push({ layout: 'cover', kicker: ui.coverKicker, title: coverTitle || 'Untitled', subtitle: coverSubtitle })
749
+ let pointIndex = 0
750
+ for (const section of bodySections) {
751
+ const notes = section.notes.join('\n')
752
+ const specials = specialSlidesFor(section, ui)
753
+ slides.push(...specials)
754
+ if (section.heading === '') {
755
+ const points = [...section.bullets, ...section.paragraphs]
756
+ .flatMap((part) => splitSentences(part))
757
+ // 超过 8 条自动续页,不再静默丢弃;备注只挂在第一页
758
+ for (const [pageIndex, pagePoints] of chunk(points, 8).entries()) {
759
+ pointIndex += 1
760
+ const slide = {
761
+ layout: 'bullets',
762
+ kicker: ui.pointKicker + ' ' + pointIndex,
763
+ title: truncate(pagePoints[0], 40) || ui.pointKicker + ' ' + pointIndex,
764
+ bullets: pagePoints,
765
+ }
766
+ if (pageIndex === 0 && specials.length === 0 && notes !== '') slide.notes = notes
767
+ slides.push(slide)
768
+ }
769
+ continue
770
+ }
771
+ const points = [
772
+ ...section.bullets,
773
+ ...section.paragraphs.flatMap((part) => splitSentences(part)),
774
+ ]
775
+ const pages = chunk(points, 8)
776
+ if (pages.length > 0) {
777
+ // 超过 8 条自动续页,不再静默丢弃;备注只挂在第一页
778
+ pages.forEach((pagePoints, pageIndex) => {
779
+ const label = pageIndex === 0 ? section.heading : section.heading + ui.continuation
780
+ const slide = { layout: 'bullets', kicker: label, title: label, bullets: pagePoints }
781
+ if (pageIndex === 0 && specials.length === 0 && notes !== '') slide.notes = notes
782
+ slides.push(slide)
783
+ })
784
+ } else if (specials.length === 0) {
785
+ const slide = { layout: 'section', kicker: section.heading, title: section.heading }
786
+ if (notes !== '') slide.notes = notes
787
+ slides.push(slide)
788
+ }
789
+ }
790
+ slides.push({ layout: 'closing', title: ui.closingTitle, subtitle: coverTitle || 'Untitled' })
791
+ return { title: coverTitle || 'Untitled', subtitle: coverSubtitle, slides }
792
+ }
793
+
794
+ const SLIDE_LAYOUTS = new Set(['cover', 'section', 'bullets', 'statement', 'closing', 'quote', 'table'])
795
+
796
+ function normalizeSlide(raw, index) {
797
+ const source = (raw !== null && typeof raw === 'object') ? raw : {}
798
+ const layout = SLIDE_LAYOUTS.has(source.layout) ? source.layout : 'bullets'
799
+ const title = stripInlineMarkdown(source.title ?? '')
800
+ const subtitle = stripInlineMarkdown(source.subtitle ?? '')
801
+ const kicker = stripInlineMarkdown(source.kicker ?? '')
802
+ const text = stripInlineMarkdown(source.text ?? '')
803
+ // 备注保留换行(放映面板与备注页都按原文显示),只做转义,不做 Markdown 清洗
804
+ const notes = String(source.notes ?? '').trim()
805
+ let bullets = []
806
+ if (Array.isArray(source.bullets)) {
807
+ bullets = source.bullets.map((item) => stripInlineMarkdown(String(item))).filter(Boolean)
808
+ } else if (typeof source.bullets === 'string' && source.bullets.trim() !== '') {
809
+ bullets = splitSentences(source.bullets)
810
+ }
811
+ if (layout === 'statement' && title === '' && text !== '') {
812
+ return { layout, kicker, title: text, subtitle: subtitle || '', bullets, ...(notes !== '' ? { notes } : {}) }
813
+ }
814
+ if (layout === 'quote') {
815
+ const quoteText = title !== '' ? title : text
816
+ if (quoteText === '') return { layout: 'statement', kicker, title: subtitle, subtitle: '', bullets, ...(notes !== '' ? { notes } : {}) }
817
+ return { layout, kicker, title: truncate(quoteText, 220), subtitle, ...(notes !== '' ? { notes } : {}) }
818
+ }
819
+ if (layout === 'table') {
820
+ let rows = []
821
+ if (Array.isArray(source.rows)) {
822
+ rows = source.rows
823
+ .map((row) => (Array.isArray(row) ? row : [row]).map((cell) => stripInlineMarkdown(String(cell))))
824
+ .filter((row) => row.some((cell) => cell !== ''))
825
+ }
826
+ if (rows.length === 0) {
827
+ // 没有表格数据的 table 页退化成要点页,避免产出空白版式
828
+ return { layout: 'bullets', kicker, title, subtitle, bullets, ...(notes !== '' ? { notes } : {}) }
829
+ }
830
+ return { layout, kicker: kicker || title, title, rows, ...(notes !== '' ? { notes } : {}) }
831
+ }
832
+ return { layout, kicker, title, subtitle, text, bullets, ...(notes !== '' ? { notes } : {}) }
833
+ }
834
+
835
+ function checkSlideLimit(slides, limit) {
836
+ if (slides.length > limit) {
837
+ throw new Error('dsh-ppt:生成后共 ' + slides.length + ' 页,超过 maxSlides=' + limit
838
+ + ',请提高 maxSlides(最多 120)或拆分内容 / generated ' + slides.length + ' slides; raise maxSlides or split the deck')
839
+ }
840
+ }
841
+
842
+ export function normalizeSlides(rawSlides, maxSlides = 60, lang = 'zh') {
843
+ if (!Array.isArray(rawSlides) || rawSlides.length === 0) {
844
+ throw new Error('dsh-ppt:slides 必须是非空数组(每个元素是 { layout, title, subtitle, kicker, bullets } 对象)')
845
+ }
846
+ const limit = clampInt(maxSlides, 60, 1, 120)
847
+ const ui = resolveLanguage(lang).ui
848
+ const slides = rawSlides.map(normalizeSlide).flatMap(slide => slide.layout === 'table'
849
+ ? paginateTable(slide, ui.continuation) : [slide])
850
+ checkSlideLimit(slides, limit)
851
+ if (slides.length === 0) throw new Error('dsh-ppt:slides 规范化后为空')
852
+ return slides
853
+ }
854
+
855
+ // ---------------------------------------------------------------------------
856
+ // 构建入口
857
+ // ---------------------------------------------------------------------------
858
+
859
+ export function normalizeBuildOptions(options = {}) {
860
+ const title = String(options.title ?? '').trim()
861
+ if (title === '') throw new Error('dsh-ppt:title 不能为空')
862
+ const theme = resolveTheme(options.theme)
863
+ const language = resolveLanguage(options.lang)
864
+ const motion = resolveMotion(options.motion)
865
+ const maxSlides = clampInt(options.maxSlides, 60, 3, 120)
866
+ let deck
867
+ if (Array.isArray(options.slides) && options.slides.length > 0) {
868
+ deck = {
869
+ title,
870
+ subtitle: stripInlineMarkdown(options.subtitle ?? ''),
871
+ slides: normalizeSlides(options.slides, maxSlides, language.id),
872
+ }
873
+ } else {
874
+ const content = String(options.content ?? '').trim()
875
+ if (content === '') throw new Error('dsh-ppt:content 不能为空(或用 slides 传结构化幻灯片)')
876
+ deck = parseMarkdownDeck(title, content, language.id)
877
+ checkSlideLimit(deck.slides, maxSlides)
878
+ }
879
+ if (deck.slides.length < 1) throw new Error('dsh-ppt:没有可生成的幻灯片')
880
+ const outputDir = resolvePath(String(options.outputDir ?? '.').trim() || '.')
881
+ const fileName = sanitizeFileName(options.fileName ?? title)
882
+ const overwrite = options.overwrite === true
883
+ return { title, theme, language, motion, deck, outputDir, fileName, overwrite }
884
+ }
885
+
886
+ /**
887
+ * 三件套落盘:三份内容全部先写同目录临时文件,再逐个 rename 提交。
888
+ * 任一步失败都清理临时文件,并把已提交的目标恢复为调用前的内容,
889
+ * 避免出现「json/html 已更新、pptx 还是旧的」这类混版状态。
890
+ */
891
+ function commitDeckArtifacts(artifacts) {
892
+ const stamp = process.pid.toString(36) + '-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8)
893
+ const items = artifacts.map((item, index) => ({ ...item, tempPath: item.path + '.' + stamp + '-' + index + '.tmp' }))
894
+ const removeTemp = (item) => {
895
+ try {
896
+ rmSync(item.tempPath, { force: true })
897
+ } catch {}
898
+ }
899
+
900
+ // 阶段 0:记下已有产物内容用于回滚;读不出来(如被同名目录占用)先报错,不碰任何文件。
901
+ const previous = new Map()
902
+ for (const item of items) {
903
+ if (!existsSync(item.path)) continue
904
+ try {
905
+ previous.set(item.path, readFileSync(item.path))
906
+ } catch (error) {
907
+ throw new Error('dsh-ppt:三件套写入失败(' + item.path + ' 已存在但无法读取),原文件未改动:' + error.message)
908
+ }
909
+ }
910
+
911
+ // 阶段 1:全部写临时文件;这一步失败时目标文件尚未被改动。
912
+ let written = 0
913
+ try {
914
+ for (const item of items) {
915
+ writeFileSync(item.tempPath, item.data, item.encoding)
916
+ written += 1
917
+ }
918
+ } catch (error) {
919
+ for (const item of items.slice(0, written + 1)) removeTemp(item)
920
+ throw new Error('dsh-ppt:写入临时文件失败(' + items[written].path + '),原三件套未改动:' + error.message)
921
+ }
922
+
923
+ // 阶段 2:逐个 rename 提交;中途失败则把已提交的目标回滚成旧内容。
924
+ const committed = []
925
+ try {
926
+ for (const item of items) {
927
+ renameSync(item.tempPath, item.path)
928
+ committed.push(item)
929
+ }
930
+ } catch (error) {
931
+ const failedPath = items[committed.length].path
932
+ for (const item of items) removeTemp(item)
933
+ for (const item of committed) {
934
+ try {
935
+ const previousData = previous.get(item.path)
936
+ if (previousData === undefined) rmSync(item.path, { force: true })
937
+ else writeFileSync(item.path, previousData)
938
+ } catch {}
939
+ }
940
+ throw new Error('dsh-ppt:提交三件套失败(' + failedPath + '),已回滚为原文件:' + error.message)
941
+ }
942
+ }
943
+
944
+ export function buildDeck(options = {}) {
945
+ const normalized = normalizeBuildOptions(options)
946
+ const { title, theme, language, motion, deck, outputDir, overwrite } = normalized
947
+ mkdirSync(outputDir, { recursive: true })
948
+ const fileName = resolveDeckFileName(outputDir, normalized.fileName, overwrite)
949
+
950
+ const manifest = {
951
+ version: DECK_VERSION,
952
+ title,
953
+ theme: theme.id,
954
+ language: language.id,
955
+ motion,
956
+ slideCount: deck.slides.length,
957
+ slides: deck.slides,
958
+ }
959
+ const jsonPath = resolvePath(outputDir, fileName + '.json')
960
+ const htmlPath = resolvePath(outputDir, fileName + '.html')
961
+ const pptxPath = resolvePath(outputDir, fileName + '.pptx')
962
+
963
+ // 先生成三份内容再统一提交:生成阶段抛错时也不会留下半套文件。
964
+ commitDeckArtifacts([
965
+ { path: jsonPath, data: JSON.stringify(manifest, null, 2) + '\n', encoding: 'utf8' },
966
+ { path: htmlPath, data: renderHtml(manifest, theme, language), encoding: 'utf8' },
967
+ { path: pptxPath, data: buildPptx(manifest, theme, language) },
968
+ ])
969
+
970
+ return {
971
+ ok: true,
972
+ title,
973
+ theme: theme.id,
974
+ language: language.id,
975
+ slideCount: deck.slides.length,
976
+ outputDir,
977
+ files: {
978
+ html: htmlPath,
979
+ pptx: pptxPath,
980
+ json: jsonPath,
981
+ },
982
+ htmlPath,
983
+ pptxPath,
984
+ jsonPath,
985
+ }
986
+ }
987
+
988
+ // ---------------------------------------------------------------------------
989
+ // HTML 网页放映
990
+ // ---------------------------------------------------------------------------
991
+
809
992
  export function renderHtml(manifest, theme, language) {
810
993
  const t = theme
811
994
  const lang = language
@@ -820,7 +1003,11 @@ body.motion .bullets li{
820
1003
  }
821
1004
  @keyframes bullet-in{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:none}}`
822
1005
  : ''
823
- const slides = manifest.slides.map((slide, index) => renderHtmlSlide(slide, index, ui, lang.id)).join('\n')
1006
+ const slides = manifest.slides.map((slide, index) => {
1007
+ const label = slide.title || slide.kicker || (ui.slide + ' ' + (index + 1))
1008
+ return '<div class="slide-frame" data-frame="' + (index + 1) + '" tabindex="-1" role="button" aria-label="' + escapeHtml(String(label)) + '">' +
1009
+ renderHtmlSlide(slide, index, ui, lang.id) + '</div>'
1010
+ }).join('\n')
824
1011
  const themeLabel = t.name[lang.id] ?? t.name.en
825
1012
  const total = manifest.slides.length
826
1013
 
@@ -829,6 +1016,7 @@ body.motion .bullets li{
829
1016
  <head>
830
1017
  <meta charset="UTF-8">
831
1018
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1019
+ <link rel="icon" href="data:,">
832
1020
  <title>${escapeHtml(manifest.title)}</title>
833
1021
  <style>
834
1022
  :root{
@@ -848,8 +1036,10 @@ body{
848
1036
  font-family:var(--font-body);overflow:hidden;
849
1037
  -webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility;
850
1038
  }
1039
+ #stage{position:fixed;inset:0}
1040
+ .slide-frame{position:fixed;inset:0}
851
1041
  .slide{
852
- position:fixed;inset:0;display:none;flex-direction:column;justify-content:center;
1042
+ position:absolute;inset:0;display:none;flex-direction:column;justify-content:center;
853
1043
  padding:clamp(34px,7vw,110px);overflow:hidden;
854
1044
  }
855
1045
  .slide::before{
@@ -905,71 +1095,158 @@ h2{font-size:clamp(34px,5vw,82px);max-width:20ch}
905
1095
  }
906
1096
  .quote-attr{color:var(--muted);margin-top:clamp(18px,2.6vw,34px);font-size:clamp(15px,1.8vw,26px);letter-spacing:.04em}
907
1097
  table.deck-table{
908
- border-collapse:collapse;margin-top:clamp(20px,3vw,42px);width:100%;max-width:1120px;
909
- font-size:clamp(13px,1.55vw,23px);
1098
+ border-collapse:collapse;margin-top:clamp(20px,3vw,42px);width:100%;max-width:100%;
1099
+ font-size:clamp(14px,1.55vw,23px);
910
1100
  }
911
1101
  .deck-table th{
912
- background:var(--accent);color:var(--bg);text-align:left;font-weight:700;
913
- padding:.6em .9em;letter-spacing:.02em;
1102
+ background:color-mix(in srgb, var(--accent) 26%, var(--bg));color:var(--fg);
1103
+ text-align:left;font-weight:700;padding:.6em .9em;letter-spacing:.02em;
1104
+ border-bottom:2px solid var(--accent);
914
1105
  }
915
1106
  .deck-table td{
916
- padding:.55em .9em;border-bottom:1px solid color-mix(in srgb, var(--muted) 34%, transparent);
1107
+ padding:.55em .9em;border-bottom:1px solid color-mix(in srgb, var(--muted) 55%, transparent);
917
1108
  color:var(--fg);
918
1109
  }
1110
+ .deck-table .num{text-align:right;font-variant-numeric:tabular-nums}
919
1111
  .deck-table tbody tr:nth-child(even){background:color-mix(in srgb, var(--panel) 62%, transparent)}
920
1112
  #progress{position:fixed;top:0;left:0;height:3px;width:0;background:var(--accent);z-index:30;transition:width .25s}
921
1113
  #hud{
922
- position:fixed;right:22px;bottom:18px;z-index:30;display:flex;gap:14px;align-items:center;
1114
+ position:fixed;right:22px;bottom:18px;z-index:50;display:flex;gap:10px;align-items:center;
923
1115
  color:var(--muted);font-size:13px;letter-spacing:.08em;font-variant-numeric:tabular-nums;
924
1116
  }
925
1117
  #hud button{
926
1118
  background:color-mix(in srgb, var(--panel) 88%, transparent);color:var(--fg);
927
1119
  border:1px solid color-mix(in srgb, var(--muted) 45%, transparent);border-radius:99px;
928
- padding:7px 13px;font:inherit;cursor:pointer;
1120
+ padding:8px 14px;min-height:34px;font:inherit;cursor:pointer;
929
1121
  }
930
1122
  #hud button:hover{border-color:var(--accent);color:var(--accent)}
931
1123
  #notes-panel{
932
- position:fixed;left:0;right:0;bottom:0;z-index:40;display:none;
1124
+ position:fixed;left:0;right:0;bottom:64px;z-index:40;display:none;
933
1125
  background:color-mix(in srgb, var(--panel) 96%, black 4%);
934
1126
  border-top:2px solid var(--accent);
935
- padding:16px clamp(22px,4vw,64px) 20px;max-height:38vh;overflow:auto;
1127
+ padding:14px clamp(22px,4vw,64px) 18px;max-height:38vh;overflow:auto;
936
1128
  }
937
- body.notes-open #notes-panel.has-notes{display:block}
1129
+ body.notes-open #notes-panel{display:block}
1130
+ #notes-panel .notes-head{display:flex;align-items:center;justify-content:space-between;gap:16px}
1131
+ #notes-close{
1132
+ background:transparent;color:var(--muted);border:1px solid color-mix(in srgb, var(--muted) 45%, transparent);
1133
+ border-radius:99px;padding:4px 12px;font:inherit;cursor:pointer;min-height:30px;
1134
+ }
1135
+ #notes-close:hover{color:var(--accent);border-color:var(--accent)}
938
1136
  #notes-panel .notes-label{
939
1137
  color:var(--accent);font-weight:700;letter-spacing:.14em;text-transform:uppercase;
940
1138
  font-size:12px;margin-bottom:8px;
941
1139
  }
942
- #notes-text{white-space:pre-wrap;line-height:1.65;font-size:15px;color:var(--fg)}
943
- body.overview .slide{display:flex !important;position:relative;inset:auto;width:100%;height:100vh}
944
- body.overview{overflow:auto}
945
- body.overview #progress,body.overview #hud{position:fixed}
946
- body.overview #notes-panel{display:none !important}
1140
+ #notes-text{white-space:pre-wrap;line-height:1.65;font-size:clamp(15px,1.5vw,18px);color:var(--fg)}
1141
+ #notes-text.is-empty{color:var(--muted);font-style:italic}
1142
+ #help-panel{
1143
+ position:fixed;right:22px;bottom:64px;z-index:60;max-width:390px;
1144
+ background:color-mix(in srgb, var(--panel) 96%, black 4%);color:var(--fg);
1145
+ border:1px solid color-mix(in srgb, var(--accent) 55%, transparent);border-radius:14px;
1146
+ padding:16px 20px;box-shadow:0 18px 50px rgba(0,0,0,.45);font-size:14px;line-height:1.8;
1147
+ }
1148
+ #help-panel[hidden]{display:none}
1149
+ #help-panel kbd{
1150
+ background:color-mix(in srgb, var(--accent) 22%, transparent);border-radius:5px;
1151
+ padding:1px 6px;font-family:inherit;font-size:12px;
1152
+ }
1153
+ #toast{
1154
+ position:fixed;left:50%;bottom:84px;transform:translateX(-50%);z-index:70;
1155
+ background:color-mix(in srgb, var(--panel) 96%, black 4%);color:var(--fg);
1156
+ border:1px solid color-mix(in srgb, var(--accent) 55%, transparent);border-radius:99px;
1157
+ padding:9px 18px;font-size:13px;
1158
+ }
1159
+ #toast[hidden]{display:none}
1160
+ :focus-visible{outline:2px solid var(--accent);outline-offset:2px}
1161
+ body.overview #stage{
1162
+ display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:18px;
1163
+ padding:18px 18px 92px;position:fixed;inset:0;overflow:auto;align-content:start;
1164
+ }
1165
+ body.overview .slide-frame{
1166
+ position:relative;inset:auto;width:100%;aspect-ratio:16/9;overflow:hidden;
1167
+ border:1px solid color-mix(in srgb, var(--muted) 35%, transparent);border-radius:12px;
1168
+ cursor:pointer;background:var(--bg);outline:none;
1169
+ }
1170
+ body.overview .slide-frame:hover{border-color:var(--accent)}
1171
+ body.overview .slide-frame.is-current{outline:2px solid var(--accent);outline-offset:2px}
1172
+ body.overview .slide-frame:focus-visible{outline:2px solid var(--accent);outline-offset:-3px}
1173
+ body.overview .slide-frame::after{
1174
+ content:attr(data-frame);position:absolute;right:8px;bottom:6px;z-index:2;
1175
+ font-size:12px;color:var(--muted);background:color-mix(in srgb, var(--bg) 84%, transparent);
1176
+ border:1px solid color-mix(in srgb, var(--muted) 40%, transparent);border-radius:6px;
1177
+ padding:1px 7px;font-variant-numeric:tabular-nums;
1178
+ }
1179
+ body.overview .slide{
1180
+ display:flex !important;position:absolute;inset:0;width:100vw;height:100vh;
1181
+ transform:scale(var(--deck-thumb-scale,.25));transform-origin:top left;pointer-events:none;
1182
+ animation:none !important;
1183
+ }
1184
+ body.overview .bullets li{opacity:1 !important;animation:none !important}
1185
+ body.overview #notes-panel,body.presenting #notes-panel{display:none !important}
1186
+ body.presenting #notes-toggle{opacity:.55}
1187
+ body.presenting #hud{opacity:0;pointer-events:none;transition:opacity .25s}
1188
+ body.presenting #hud:hover{opacity:1;pointer-events:auto}
1189
+ @media (max-width:900px){
1190
+ .slide{padding:clamp(22px,5vw,44px)}
1191
+ h1{font-size:clamp(34px,8.5vw,64px)}
1192
+ h2{font-size:clamp(26px,6.5vw,48px)}
1193
+ .statement-title{font-size:clamp(26px,7vw,54px)}
1194
+ .subtitle{font-size:clamp(16px,3.4vw,24px)}
1195
+ .bullets li{font-size:clamp(16px,3.4vw,24px)}
1196
+ .kicker{font-size:13px}
1197
+ .deck-table{font-size:14px}
1198
+ .deck-table th,.deck-table td{padding:.55em .6em}
1199
+ #hud{right:10px;bottom:10px;gap:8px;font-size:12px}
1200
+ #hud button{padding:10px 16px;min-height:44px}
1201
+ #notes-panel{bottom:68px;max-height:45vh}
1202
+ #help-panel{right:10px;bottom:68px;left:10px;max-width:none}
1203
+ }
947
1204
  @media (max-width:640px){
948
- #hud{right:12px;bottom:10px;gap:8px;font-size:11px}
1205
+ #theme-label{display:none}
1206
+ }
1207
+ @media (prefers-reduced-motion: reduce){
1208
+ *,*::before,*::after{animation:none !important;transition:none !important}
949
1209
  }
950
1210
  @media print{
951
1211
  html,body{height:auto;overflow:visible;background:#fff}
1212
+ .slide-frame{position:relative;display:block !important}
952
1213
  .slide{position:relative;display:block !important;height:100vh;page-break-after:always;padding:48px}
953
1214
  ${motion ? 'body.motion .bullets li{opacity:1 !important;animation:none !important}' : ''}
954
- #progress,#hud,#notes-panel{display:none !important}
1215
+ #progress,#hud,#notes-panel,#help-panel,#toast{display:none !important}
955
1216
  }
956
1217
  </style>
957
1218
  </head>
958
1219
  <body class="${motion ? 'motion' : 'no-motion'}">
959
1220
  <div id="progress" aria-hidden="true"></div>
1221
+ <div id="stage">
960
1222
  ${slides}
1223
+ </div>
961
1224
  <div id="hud" aria-live="polite">
962
1225
  <span id="counter">${ui.slide} 1 ${ui.of} ${total}</span>
963
1226
  <span id="theme-label">${ui.theme} · ${escapeHtml(themeLabel)}</span>
964
- <button id="notes-toggle" title="S">${escapeHtml(ui.notesToggle)}</button>
965
- <button id="fullscreen" title="F">⛶</button>
1227
+ <button id="notes-toggle" type="button" title="S · ${escapeHtml(ui.notesToggle)}" aria-controls="notes-panel" aria-expanded="false">${escapeHtml(ui.notesToggle)}</button>
1228
+ <button id="presenter-toggle" type="button" title="V · ${escapeHtml(ui.presenterToggle)}">${escapeHtml(ui.presenterToggle)}</button>
1229
+ <button id="overview-toggle" type="button" title="G · ${escapeHtml(ui.overviewToggle)}" aria-pressed="false">${escapeHtml(ui.overviewToggle)}</button>
1230
+ <button id="help-toggle" type="button" title="?" aria-label="${escapeHtml(ui.helpTitle)}">?</button>
1231
+ <button id="fullscreen" type="button" title="F · Fullscreen" aria-label="Fullscreen">⛶</button>
966
1232
  </div>
967
- <div id="notes-panel" aria-live="polite">
968
- <div class="notes-label">${escapeHtml(ui.notesLabel)}</div>
1233
+ <div id="notes-panel" role="region" aria-label="${escapeHtml(ui.notesLabel)}">
1234
+ <div class="notes-head">
1235
+ <span class="notes-label">${escapeHtml(ui.notesLabel)}</span>
1236
+ <button id="notes-close" type="button" aria-label="${escapeHtml(ui.notesCloseLabel)}">×</button>
1237
+ </div>
969
1238
  <div id="notes-text"></div>
970
1239
  </div>
1240
+ <div id="help-panel" hidden>
1241
+ <div class="notes-label">${escapeHtml(ui.helpTitle)}</div>
1242
+ <p><kbd>←</kbd> <kbd>→</kbd> / <kbd>Space</kbd> 翻页 · <kbd>Home</kbd> / <kbd>End</kbd> 首末页 · <kbd>S</kbd> ${escapeHtml(ui.notesToggle)} · <kbd>V</kbd> ${escapeHtml(ui.presenterToggle)} · <kbd>G</kbd> ${escapeHtml(ui.overviewToggle)} · <kbd>F</kbd> 全屏 · <kbd>P</kbd> 打印 · <kbd>Esc</kbd> ${escapeHtml(ui.closeLabel)} · <kbd>?</kbd> ${escapeHtml(ui.helpTitle)}</p>
1243
+ <p>${escapeHtml(ui.presenterHint)}</p>
1244
+ <p>${escapeHtml(ui.overviewHint)}</p>
1245
+ </div>
1246
+ <div id="toast" role="status" hidden></div>
971
1247
  <script>
972
1248
  (() => {
1249
+ const frames = Array.from(document.querySelectorAll('.slide-frame'));
973
1250
  const slides = Array.from(document.querySelectorAll('.slide'));
974
1251
  const counter = document.getElementById('counter');
975
1252
  const progress = document.getElementById('progress');
@@ -977,52 +1254,208 @@ ${slides}
977
1254
  const notesPanel = document.getElementById('notes-panel');
978
1255
  const notesText = document.getElementById('notes-text');
979
1256
  const notesBtn = document.getElementById('notes-toggle');
1257
+ const notesClose = document.getElementById('notes-close');
1258
+ const presenterBtn = document.getElementById('presenter-toggle');
1259
+ const overviewBtn = document.getElementById('overview-toggle');
1260
+ const helpBtn = document.getElementById('help-toggle');
1261
+ const helpPanel = document.getElementById('help-panel');
1262
+ const toastEl = document.getElementById('toast');
980
1263
  let index = 0;
1264
+ let presenterWin = null;
1265
+ let toastTimer = 0;
981
1266
  const total = slides.length;
982
1267
  const ui = ${JSON.stringify(ui).replace(/</g, '\\u003c')};
983
1268
 
984
- function refreshNotes() {
985
- const notes = slides[index]?.dataset.notes || '';
986
- notesPanel.classList.toggle('has-notes', notes !== '');
987
- notesText.textContent = notes;
1269
+ function notesOf(i) { return slides[i] && slides[i].dataset ? (slides[i].dataset.notes || '') : ''; }
1270
+ function titleOf(i) {
1271
+ const el = slides[i] ? slides[i].querySelector('h1,h2,.statement-title,.quote-text') : null;
1272
+ return el ? el.textContent.trim() : '';
1273
+ }
1274
+ function state() {
1275
+ const next = (index + 1) % total;
1276
+ return { index: index, total: total, title: titleOf(index), notes: notesOf(index), nextTitle: titleOf(next), nextNotes: notesOf(next) };
1277
+ }
1278
+ window.__dshPpt = { go: function (delta) { go(index + delta); }, jump: function (i) { go(i); }, state: state };
1279
+
1280
+ function toast(message) {
1281
+ toastEl.textContent = message;
1282
+ toastEl.hidden = false;
1283
+ clearTimeout(toastTimer);
1284
+ toastTimer = setTimeout(function () { toastEl.hidden = true; }, 2600);
1285
+ }
1286
+
1287
+ function syncNotes() {
1288
+ const notes = notesOf(index);
1289
+ notesText.textContent = notes || ui.noNotes;
1290
+ notesText.classList.toggle('is-empty', notes === '');
1291
+ notesBtn.setAttribute('aria-expanded', document.body.classList.contains('notes-open') ? 'true' : 'false');
1292
+ updatePresenter();
1293
+ }
1294
+
1295
+ function updatePresenter() {
1296
+ if (presenterOpen() && typeof presenterWin.__deckPresenterUpdate === 'function') {
1297
+ try { presenterWin.__deckPresenterUpdate(state()); } catch (_) { /* window closing */ }
1298
+ }
988
1299
  }
989
1300
 
990
1301
  function go(next) {
1302
+ const wrapped = next < 0 || next >= total;
991
1303
  index = (next + total) % total;
992
- slides.forEach((slide, i) => slide.classList.toggle('is-active', i === index));
1304
+ slides.forEach(function (slide, i) {
1305
+ slide.classList.toggle('is-active', i === index);
1306
+ if (frames[i]) frames[i].classList.toggle('is-current', i === index);
1307
+ });
993
1308
  counter.textContent = ui.slide + ' ' + (index + 1) + ' ' + ui.of + ' ' + total;
994
1309
  progress.style.width = ((index + 1) / total * 100) + '%';
995
- refreshNotes();
996
1310
  document.title = (index + 1) + ' / ' + total + ' · ' + ${JSON.stringify(manifest.title).replace(/</g, '\\u003c')};
997
- try { history.replaceState?.(null, '', '#slide-' + (index + 1)); } catch { /* file:// 下个别浏览器可能拒绝 */ }
1311
+ try { history.replaceState?.(null, '', '#slide-' + (index + 1)); } catch (_) { /* file:// 下个别浏览器可能拒绝 */ }
1312
+ if (wrapped) toast(ui.wrapHint + ' ' + (index + 1) + ' / ' + total);
1313
+ syncNotes();
1314
+ }
1315
+
1316
+ function notesOpen() { return document.body.classList.contains('notes-open'); }
1317
+ function presenterOpen() { try { return !!(presenterWin && !presenterWin.closed); } catch (_) { return false; } }
1318
+
1319
+ function setNotes(on) {
1320
+ document.body.classList.toggle('notes-open', on);
1321
+ if (on) setOverview(false);
1322
+ syncNotes();
1323
+ }
1324
+
1325
+ function updateThumbScale() {
1326
+ if (!document.body.classList.contains('overview')) return;
1327
+ requestAnimationFrame(function () {
1328
+ const width = frames[0] ? frames[0].getBoundingClientRect().width : 0;
1329
+ if (width > 0) document.documentElement.style.setProperty('--deck-thumb-scale', String(width / window.innerWidth));
1330
+ });
1331
+ }
1332
+
1333
+ function setOverview(on) {
1334
+ document.body.classList.toggle('overview', on);
1335
+ overviewBtn.setAttribute('aria-pressed', on ? 'true' : 'false');
1336
+ frames.forEach(function (frame) { frame.tabIndex = on ? 0 : -1; });
1337
+ if (on) {
1338
+ document.body.classList.remove('notes-open');
1339
+ helpPanel.hidden = true;
1340
+ syncNotes();
1341
+ updateThumbScale();
1342
+ }
1343
+ }
1344
+
1345
+ function presenterHtml() {
1346
+ const cs = getComputedStyle(document.documentElement);
1347
+ const val = function (name, fallback) { const v = cs.getPropertyValue(name).trim(); return v || fallback; };
1348
+ const css = ':root{--bg:' + val('--bg', '#070B14') + ';--panel:' + val('--panel', '#0D1424') + ';--fg:' + val('--fg', '#E8F1FF') + ';--muted:' + val('--muted', '#7E8BA8') + ';--accent:' + val('--accent', '#7C3AED') + ';--accent2:' + val('--accent2', '#06B6D4') + ';--font-heading:' + val('--font-heading', 'sans-serif') + ';--font-body:' + val('--font-body', 'sans-serif') + '}'
1349
+ + 'body{margin:0;background:var(--bg);color:var(--fg);font-family:var(--font-body);height:100vh;display:flex;flex-direction:column}'
1350
+ + 'header{display:flex;justify-content:space-between;gap:16px;padding:14px 20px;border-bottom:1px solid color-mix(in srgb, var(--muted) 40%, transparent);font-size:14px;color:var(--muted)}'
1351
+ + 'header #ptitle{color:var(--fg);font-weight:700}'
1352
+ + 'main{flex:1;display:grid;grid-template-columns:1.05fr 1fr;gap:18px;padding:18px 20px;min-height:0}'
1353
+ + 'section{background:var(--panel);border:1px solid color-mix(in srgb, var(--muted) 30%, transparent);border-radius:14px;padding:16px 18px;min-height:0;display:flex;flex-direction:column;gap:10px}'
1354
+ + '.lbl{color:var(--accent);font-size:12px;font-weight:700;letter-spacing:.14em;text-transform:uppercase}'
1355
+ + '#pcur{font-family:var(--font-heading);font-size:30px;font-weight:800;line-height:1.2}'
1356
+ + '#pnext{font-size:20px;line-height:1.35}'
1357
+ + '#pnotes{font-size:19px;line-height:1.65;white-space:pre-wrap;overflow:auto;flex:1}'
1358
+ + '.hint{color:var(--muted);font-size:12px;margin-top:auto}'
1359
+ + 'footer{display:flex;align-items:center;gap:16px;padding:12px 20px;border-top:1px solid color-mix(in srgb, var(--muted) 40%, transparent)}'
1360
+ + '#ptimer{font-variant-numeric:tabular-nums;font-size:22px;font-weight:700;color:var(--accent)}'
1361
+ + '.bar{flex:1;height:8px;background:color-mix(in srgb, var(--muted) 28%, transparent);border-radius:99px;overflow:hidden}'
1362
+ + '#pprog{height:100%;width:0;background:var(--accent);transition:width .2s}'
1363
+ + 'body.big #pnotes{font-size:26px}'
1364
+ + '@media (max-width:760px){main{grid-template-columns:1fr}}';
1365
+ const js = 'var started=Date.now(),elapsed=0,paused=false,big=false;'
1366
+ + 'function fmt(ms){var s=Math.max(0,Math.floor(ms/1000));var m=Math.floor(s/60);s=s%60;return (m<10?"0":"")+m+":"+(s<10?"0":"")+s}'
1367
+ + 'function tick(){if(!paused)elapsed=Date.now()-started;document.getElementById("ptimer").textContent=fmt(elapsed);requestAnimationFrame(tick)}'
1368
+ + 'window.__deckPresenterUpdate=function(st){document.getElementById("pcur").textContent=st.title||("Slide "+(st.index+1));document.getElementById("pnext").textContent=st.nextTitle||"\u2014";document.getElementById("pnotes").textContent=st.notes||"' + ui.noNotes.replace(/"/g, '\\"') + '";document.getElementById("pcounter").textContent=(st.index+1)+" / "+st.total;document.getElementById("pprog").style.width=((st.index+1)/st.total*100)+"%"}'
1369
+ + ';document.addEventListener("keydown",function(e){var k=e.key;'
1370
+ + 'if(k==="ArrowRight"||k===" "){e.preventDefault();try{opener.__dshPpt.go(1)}catch(_){}}'
1371
+ + 'else if(k==="ArrowLeft"){e.preventDefault();try{opener.__dshPpt.go(-1)}catch(_){}}'
1372
+ + 'else if(k==="Escape"){window.close()}'
1373
+ + 'else if(k.toLowerCase()==="t"){started=Date.now();elapsed=0;paused=false}'
1374
+ + 'else if(k.toLowerCase()==="p"){paused=!paused;if(!paused)started=Date.now()-elapsed}'
1375
+ + 'else if(k==="+"||k==="="){big=true;document.body.classList.add("big")}'
1376
+ + 'else if(k==="-"){big=false;document.body.classList.remove("big")}});'
1377
+ + 'setInterval(function(){try{if(opener&&!opener.closed&&opener.__dshPpt)window.__deckPresenterUpdate(opener.__dshPpt.state())}catch(_){}},400);'
1378
+ + 'tick();';
1379
+ return '<!DOCTYPE html><html lang="' + ${JSON.stringify(lang.attr)} + '"><head><meta charset="UTF-8"><title>' + ${JSON.stringify(manifest.title + ' · ' + ui.presenterLabel).replace(/</g, '\\u003c')} + '</title><style>' + css + '</style></head><body>'
1380
+ + '<header><div id="ptitle">' + ${JSON.stringify(manifest.title).replace(/</g, '\\u003c')} + '</div><div id="pcounter"></div></header>'
1381
+ + '<main><section><div class="lbl">' + ${JSON.stringify(ui.currentLabel).replace(/</g, '\\u003c')} + '</div><div id="pcur"></div><div class="lbl">' + ${JSON.stringify(ui.nextLabel).replace(/</g, '\\u003c')} + '</div><div id="pnext"></div></section>'
1382
+ + '<section><div class="lbl">' + ${JSON.stringify(ui.notesLabel).replace(/</g, '\\u003c')} + '</div><div id="pnotes"></div><div class="hint">+ / - 字号 · T 重置计时 · P 暂停 · ← → 翻页 · Esc 关闭</div></section></main>'
1383
+ + '<footer><div id="ptimer">00:00</div><div class="bar"><div id="pprog"></div></div></footer>'
1384
+ + '<scr' + 'ipt>' + js + '</scr' + 'ipt></body></html>';
1385
+ }
1386
+
1387
+ function openPresenter() {
1388
+ if (presenterOpen()) { presenterWin.focus(); return; }
1389
+ presenterWin = window.open('', 'dsh-ppt-presenter', 'width=1180,height=760');
1390
+ if (!presenterWin) { toast(ui.popupBlocked); return; }
1391
+ try {
1392
+ presenterWin.document.open();
1393
+ presenterWin.document.write(presenterHtml());
1394
+ presenterWin.document.close();
1395
+ } catch (_) { toast(ui.popupBlocked); return; }
1396
+ document.body.classList.add('presenting');
1397
+ if (document.activeElement && typeof document.activeElement.blur === 'function') document.activeElement.blur();
1398
+ setTimeout(updatePresenter, 150);
998
1399
  }
999
1400
 
1401
+ function closePresenter() {
1402
+ if (presenterOpen()) { try { presenterWin.close(); } catch (_) { /* already gone */ } }
1403
+ document.body.classList.remove('presenting');
1404
+ }
1405
+
1406
+ setInterval(function () {
1407
+ if (!presenterOpen() && document.body.classList.contains('presenting')) document.body.classList.remove('presenting');
1408
+ }, 800);
1409
+
1000
1410
  document.addEventListener('keydown', (event) => {
1001
- if (event.key === 'ArrowRight' || event.key === 'PageDown' || event.key === ' ') {
1411
+ const key = event.key;
1412
+ const lower = key.toLowerCase();
1413
+ const targetEl = event.target;
1414
+ const interactive = targetEl && (targetEl.tagName === 'BUTTON' || targetEl.tagName === 'INPUT' || targetEl.tagName === 'SELECT' || targetEl.tagName === 'TEXTAREA' || targetEl.isContentEditable === true);
1415
+ if (key === ' ' && interactive) return;
1416
+ if (key === 'Escape') {
1417
+ if (!helpPanel.hidden) { helpPanel.hidden = true; return; }
1418
+ if (document.body.classList.contains('overview')) { setOverview(false); return; }
1419
+ if (notesOpen()) { setNotes(false); return; }
1420
+ if (document.fullscreenElement) { document.exitFullscreen?.(); return; }
1421
+ return;
1422
+ }
1423
+ const inOverview = document.body.classList.contains('overview');
1424
+ if (key === 'ArrowRight' || key === 'PageDown' || key === ' ' || (key === 'ArrowDown' && !inOverview)) {
1002
1425
  event.preventDefault(); go(index + 1);
1003
- } else if (event.key === 'ArrowLeft' || event.key === 'PageUp') {
1426
+ } else if (key === 'ArrowLeft' || key === 'PageUp' || (key === 'ArrowUp' && !inOverview)) {
1004
1427
  event.preventDefault(); go(index - 1);
1005
- } else if (event.key === 'Home') {
1428
+ } else if (/^[1-9]$/.test(key) && !inOverview) {
1429
+ const jumped = Number(key);
1430
+ if (jumped <= total) { event.preventDefault(); go(jumped - 1); }
1431
+ } else if (key === 'Home') {
1006
1432
  event.preventDefault(); go(0);
1007
- } else if (event.key === 'End') {
1433
+ } else if (key === 'End') {
1008
1434
  event.preventDefault(); go(total - 1);
1009
- } else if (event.key.toLowerCase() === 'f') {
1435
+ } else if (key === 'Enter' && inOverview) {
1436
+ event.preventDefault(); setOverview(false);
1437
+ } else if (lower === 'f') {
1010
1438
  if (!document.fullscreenElement) document.documentElement.requestFullscreen?.();
1011
1439
  else document.exitFullscreen?.();
1012
- } else if (event.key.toLowerCase() === 'g') {
1013
- document.body.classList.toggle('overview');
1014
- go(index);
1015
- } else if (event.key.toLowerCase() === 's') {
1016
- document.body.classList.toggle('notes-open');
1017
- } else if (event.key.toLowerCase() === 'p') {
1440
+ } else if (lower === 'g') {
1441
+ setOverview(!inOverview);
1442
+ } else if (lower === 's') {
1443
+ if (document.body.classList.contains('presenting')) { toast(ui.presenterHint); }
1444
+ else { document.body.classList.toggle('notes-open'); syncNotes(); }
1445
+ } else if (lower === 'v') {
1446
+ if (presenterOpen()) closePresenter();
1447
+ else openPresenter();
1448
+ } else if (lower === 'p') {
1018
1449
  window.print();
1450
+ } else if (key === '?') {
1451
+ helpPanel.hidden = !helpPanel.hidden;
1019
1452
  }
1020
1453
  });
1021
1454
 
1022
1455
  let wheelLock = 0;
1023
1456
  document.addEventListener('wheel', (event) => {
1024
1457
  const now = Date.now();
1025
- if (now - wheelLock < 550 || document.body.classList.contains('overview')) return;
1458
+ if (now - wheelLock < 550 || document.body.classList.contains('overview') || notesOpen()) return;
1026
1459
  wheelLock = now;
1027
1460
  if (Math.abs(event.deltaY) > 12) go(index + (event.deltaY > 0 ? 1 : -1));
1028
1461
  }, { passive: true });
@@ -1031,17 +1464,31 @@ ${slides}
1031
1464
  document.addEventListener('touchstart', (event) => { touchStartY = event.touches[0].clientY; }, { passive: true });
1032
1465
  document.addEventListener('touchend', (event) => {
1033
1466
  const delta = event.changedTouches[0].clientY - touchStartY;
1034
- if (Math.abs(delta) > 48) go(index + (delta < 0 ? 1 : -1));
1467
+ if (Math.abs(delta) > 48 && !document.body.classList.contains('overview')) go(index + (delta < 0 ? 1 : -1));
1035
1468
  }, { passive: true });
1036
1469
 
1037
1470
  fullscreenBtn.addEventListener('click', () => {
1038
1471
  if (!document.fullscreenElement) document.documentElement.requestFullscreen?.();
1039
1472
  else document.exitFullscreen?.();
1040
1473
  });
1041
-
1042
1474
  notesBtn.addEventListener('click', () => {
1043
- document.body.classList.toggle('notes-open');
1475
+ if (document.body.classList.contains('presenting')) { toast(ui.presenterHint); return; }
1476
+ setNotes(!notesOpen());
1044
1477
  });
1478
+ notesClose.addEventListener('click', () => setNotes(false));
1479
+ presenterBtn.addEventListener('click', () => { if (presenterOpen()) closePresenter(); else openPresenter(); });
1480
+ overviewBtn.addEventListener('click', () => setOverview(!document.body.classList.contains('overview')));
1481
+ helpBtn.addEventListener('click', () => { helpPanel.hidden = !helpPanel.hidden; });
1482
+ frames.forEach((frame, i) => {
1483
+ frame.addEventListener('click', () => {
1484
+ if (document.body.classList.contains('overview')) { go(i); setOverview(false); }
1485
+ });
1486
+ frame.addEventListener('keydown', (event) => {
1487
+ if (event.key === 'Enter' && document.body.classList.contains('overview')) { go(i); setOverview(false); }
1488
+ });
1489
+ });
1490
+ window.addEventListener('resize', updateThumbScale);
1491
+ window.addEventListener('beforeunload', closePresenter);
1045
1492
 
1046
1493
  const start = Number.parseInt(location.hash?.replace('#slide-', ''), 10);
1047
1494
  go(Number.isInteger(start) ? start - 1 : 0);
@@ -1050,690 +1497,692 @@ ${slides}
1050
1497
  </body>
1051
1498
  </html>`
1052
1499
  }
1053
-
1054
- function renderHtmlSlide(slide, index, ui, langId) {
1055
- const kicker = slide.kicker || (slide.layout === 'cover' ? ui.coverKicker : '')
1056
- const title = slide.title || ''
1057
- const subtitle = slide.subtitle || ''
1058
- const bullets = Array.isArray(slide.bullets) ? slide.bullets : []
1059
- const number = String(index + 1).padStart(2, '0')
1060
- let inner = ''
1061
- switch (slide.layout) {
1062
- case 'cover':
1063
- inner = '<div class="kicker">' + escapeHtml(kicker) + '</div>' +
1064
- '<h1>' + escapeHtml(title) + '</h1>' +
1065
- (subtitle !== '' ? '<div class="subtitle">' + escapeHtml(subtitle) + '</div>' : '') +
1066
- '<div class="meta">' + escapeHtml(ui.generatedBy) + '</div>'
1067
- break
1068
- case 'section':
1069
- inner = '<div class="kicker">' + escapeHtml(kicker) + '</div>' +
1070
- '<h2>' + escapeHtml(title) + '</h2>' +
1071
- '<div class="accent-line"></div>' +
1072
- (subtitle !== '' ? '<div class="subtitle">' + escapeHtml(subtitle) + '</div>' : '')
1073
- break
1074
- case 'statement':
1075
- inner = '<div class="kicker">' + escapeHtml(kicker) + '</div>' +
1076
- '<div class="statement-title">' + escapeHtml(title || slide.text || '') + '</div>' +
1077
- (subtitle !== '' ? '<div class="subtitle">' + escapeHtml(subtitle) + '</div>' : '')
1078
- break
1079
- case 'quote':
1080
- inner = '<div class="kicker">' + escapeHtml(kicker || ui.quoteKicker) + '</div>' +
1081
- '<div class="quote-mark" aria-hidden="true">\u201C</div>' +
1082
- '<blockquote class="quote-text">' + escapeHtml(title || slide.text || '') + '</blockquote>' +
1083
- (subtitle !== '' ? '<div class="quote-attr">\u2014\u2014 ' + escapeHtml(subtitle) + '</div>' : '')
1084
- break
1085
- case 'table': {
1086
- const rows = Array.isArray(slide.rows) ? slide.rows : []
1087
- const head = rows[0] ?? []
1088
- const body = rows.slice(1)
1089
- inner = '<div class="kicker">' + escapeHtml(kicker || ui.tableKicker) + '</div>' +
1090
- (title !== '' && title !== kicker ? '<h2>' + escapeHtml(title) + '</h2>' : '') +
1091
- '<table class="deck-table"><thead><tr>' +
1092
- head.map((cell) => '<th>' + escapeHtml(cell) + '</th>').join('') +
1093
- '</tr></thead><tbody>' +
1094
- body.map((row) => '<tr>' + row.map((cell) => '<td>' + escapeHtml(cell) + '</td>').join('') + '</tr>').join('') +
1095
- '</tbody></table>'
1096
- break
1097
- }
1098
- case 'closing':
1099
- inner = '<h1>' + escapeHtml(title || ui.closingTitle) + '</h1>' +
1100
- (subtitle !== '' ? '<div class="subtitle">' + escapeHtml(subtitle) + '</div>' : '') +
1101
- '<div class="meta">' + escapeHtml(ui.generatedBy) + '</div>'
1102
- break
1103
- case 'bullets':
1104
- default:
1105
- inner = '<div class="kicker">' + escapeHtml(kicker) + '</div>' +
1106
- '<h2>' + escapeHtml(title) + '</h2>' +
1107
- '<ul>' + bullets.map((bullet, bulletIndex) => '<li style="--i:' + bulletIndex + '">' + escapeHtml(bullet) + '</li>').join('') + '</ul>'
1108
- break
1109
- }
1110
- const notesAttr = typeof slide.notes === 'string' && slide.notes.trim() !== ''
1111
- ? ' data-notes="' + escapeHtml(slide.notes) + '"'
1112
- : ''
1113
- return '<section class="slide slide--' + escapeHtml(slide.layout || 'bullets') + '" data-index="' + number + '"' + notesAttr + '>' +
1114
- '<div class="slide-inner">' + inner + '</div></section>'
1115
- }
1116
-
1117
- function hexToRgba(hex, alpha) {
1118
- const value = String(hex).replace('#', '')
1119
- const full = value.length === 3 ? value.split('').map((c) => c + c).join('') : value
1120
- const num = Number.parseInt(full, 16)
1121
- const r = (num >> 16) & 255
1122
- const g = (num >> 8) & 255
1123
- const b = num & 255
1124
- return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')'
1125
- }
1126
-
1127
- // ---------------------------------------------------------------------------
1128
- // PPTX(OOXML 手写 + node:zlib zip)
1129
- // ---------------------------------------------------------------------------
1130
-
1131
- const EMU_W = 12192000
1132
- const EMU_H = 6858000
1133
-
1134
- function hex(value) {
1135
- return String(value).replace('#', '').toUpperCase()
1136
- }
1137
-
1138
- function pptxFontName(value) {
1139
- const match = /"?([^",]+)"?/.exec(String(value ?? ''))
1140
- return match?.[1]?.trim() || 'Arial'
1141
- }
1142
-
1143
- function paragraphXml(text, options = {}) {
1144
- const {
1145
- size = 2000,
1146
- color = 'FFFFFF',
1147
- bold = false,
1148
- lang = 'zh-CN',
1149
- align = 'l',
1150
- bullet = false,
1151
- font = 'Arial',
1152
- spaceBefore = 0,
1153
- spaceAfter = 0,
1154
- } = options
1155
- const runFont = pptxFontName(font)
1156
- let pPr = ''
1157
- if (bullet) {
1158
- pPr = '<a:pPr marL="285750" indent="-285750"><a:buFont typeface="Arial" panose="020B0604020202020204"/><a:buChar char="•"/></a:pPr>'
1159
- } else {
1160
- const parts = [] // align 与 spacing 二选一
1161
- if (align !== 'l') parts.push('algn="' + align + '"')
1162
- if (spaceBefore > 0) parts.push('<a:spcBef><a:spcPts val="' + (spaceBefore / 100) + '"/></a:spcBef>')
1163
- if (spaceAfter > 0) parts.push('<a:spcAft><a:spcPts val="' + (spaceAfter / 100) + '"/></a:spcAft>')
1164
- pPr = '<a:pPr' + (parts.length > 0 ? ' ' + parts.join(' ') : '') + '><a:buNone/></a:pPr>'
1165
- }
1166
- return '<a:p>' + pPr +
1167
- '<a:r><a:rPr lang="' + lang + '" sz="' + size + '" b="' + (bold ? 1 : 0) + '" dirty="0">' +
1168
- '<a:solidFill><a:srgbClr val="' + hex(color) + '"/></a:solidFill>' +
1169
- '<a:latin typeface="' + escapeXml(runFont) + '"/><a:ea typeface="' + escapeXml(runFont) + '"/></a:rPr>' +
1170
- '<a:t>' + escapeXml(text) + '</a:t></a:r></a:p>'
1171
- }
1172
-
1173
- function textShapeXml(id, name, box, paragraphs, options = {}) {
1174
- const { x = 0, y = 0, w = EMU_W, h = EMU_H } = box
1175
- return '<p:sp>' +
1176
- '<p:nvSpPr><p:cNvPr id="' + id + '" name="' + escapeXml(name) + '"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>' +
1177
- '<p:spPr><a:xfrm><a:off x="' + x + '" y="' + y + '"/><a:ext cx="' + w + '" cy="' + h + '"/></a:xfrm>' +
1178
- '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln/></p:spPr>' +
1179
- '<p:txBody><a:bodyPr wrap="square" rtlCol="0"><a:normAutofit/></a:bodyPr><a:lstStyle/>' +
1180
- paragraphs.join('') + '</p:txBody></p:sp>'
1181
- }
1182
-
1183
- function accentBarXml(id, name, box, color) {
1184
- const { x = 0, y = 0, w = EMU_W, h = EMU_H } = box
1185
- return '<p:sp>' +
1186
- '<p:nvSpPr><p:cNvPr id="' + id + '" name="' + escapeXml(name) + '"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>' +
1187
- '<p:spPr><a:xfrm><a:off x="' + x + '" y="' + y + '"/><a:ext cx="' + w + '" cy="' + h + '"/></a:xfrm>' +
1188
- '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>' +
1189
- '<a:solidFill><a:srgbClr val="' + hex(color) + '"/></a:solidFill><a:ln/></p:spPr>' +
1190
- '<p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp>'
1191
- }
1192
-
1193
- /** 原生 OOXML 表格(graphicFrame + a:tbl):首行主题色表头,隔行面板色。 */
1194
- function tableGraphicXml(id, name, box, rows, theme, langId) {
1195
- const p = theme.palette
1196
- const lang = langId || 'zh-CN'
1197
- const font = pptxFontName(theme.fonts.body)
1198
- const safeRows = rows.length > 0 ? rows : [['']]
1199
- const cols = Math.max(1, safeRows[0].length)
1200
- const colW = Math.floor(box.w / cols)
1201
- const grid = Array.from({ length: cols }, () => '<a:gridCol w="' + colW + '"/>').join('')
1202
- const rowH = 420000
1203
- const cellXml = (text, fill, color, bold) =>
1204
- '<a:tc><a:txBody><a:bodyPr anchor="ctr"/><a:lstStyle/><a:p><a:pPr algn="l"><a:buNone/></a:pPr>' +
1205
- '<a:r><a:rPr lang="' + lang + '" sz="1400" b="' + (bold ? 1 : 0) + '" dirty="0">' +
1206
- '<a:solidFill><a:srgbClr val="' + hex(color) + '"/></a:solidFill>' +
1207
- '<a:latin typeface="' + escapeXml(font) + '"/><a:ea typeface="' + escapeXml(font) + '"/></a:rPr>' +
1208
- '<a:t>' + escapeXml(text) + '</a:t></a:r></a:p></a:txBody>' +
1209
- '<a:tcPr marL="91440" marR="91440" anchor="ctr">' +
1210
- (fill !== '' ? '<a:solidFill><a:srgbClr val="' + hex(fill) + '"/></a:solidFill>' : '<a:noFill/>') +
1211
- '</a:tcPr></a:tc>'
1212
- const trs = safeRows.map((row, rowIndex) => {
1213
- const padded = Array.from({ length: cols }, (_, i) => row[i] ?? '')
1214
- const cells = rowIndex === 0
1215
- ? padded.map((c) => cellXml(c, p.accent, p.bg, true)).join('')
1216
- : padded.map((c) => cellXml(c, rowIndex % 2 === 1 ? p.panel : '', p.fg, false)).join('')
1217
- return '<a:tr h="' + rowH + '">' + cells + '</a:tr>'
1218
- }).join('')
1219
- const height = Math.max(1, safeRows.length) * rowH
1220
- return '<p:graphicFrame>' +
1221
- '<p:nvGraphicFramePr><p:cNvPr id="' + id + '" name="' + escapeXml(name) + '"/>' +
1222
- '<p:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr>' +
1223
- '<p:xfrm><a:off x="' + box.x + '" y="' + box.y + '"/><a:ext cx="' + box.w + '" cy="' + height + '"/></p:xfrm>' +
1224
- '<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table">' +
1225
- '<a:tbl><a:tblPr firstRow="1" bandRow="1"/>' +
1226
- '<a:tblGrid>' + grid + '</a:tblGrid>' + trs + '</a:tbl>' +
1227
- '</a:graphicData></a:graphic></p:graphicFrame>'
1228
- }
1229
-
1230
- function slideShapeList(slide, index, total, theme, langId) {
1231
- const p = theme.palette
1232
- const font = pptxFontName(theme.fonts.heading)
1233
- const bodyFont = pptxFontName(theme.fonts.body) // 保留:v0.1 后续用于统一正文字体
1234
- const lang = langId || 'zh-CN'
1235
- // PPTX 每个文本 run 的语言跟随 deck.lang(zh-CN / en-US),不再写死中文
1236
- const para = (content, options = {}) => paragraphXml(content, { lang, ...options })
1237
- const shapes = []
1238
- const kicker = slide.kicker || ''
1239
- const title = slide.title || ''
1240
- const subtitle = slide.subtitle || ''
1241
- const bullets = Array.isArray(slide.bullets) ? slide.bullets : []
1242
- const idBase = (index + 1) * 10
1243
- const footer = String(index + 1).padStart(2, '0') + ' / ' + String(total).padStart(2, '0')
1244
-
1245
- if (slide.layout === 'cover') {
1246
- shapes.push(accentBarXml(idBase + 1, 'Accent bar', { x: 914400, y: 2250000, w: 240000, h: 1600000 }, p.accent))
1247
- shapes.push(textShapeXml(idBase + 2, 'Title', { x: 1550000, y: 2160000, w: 9250000, h: 1800000 }, [
1248
- para(title, { size: 4400, color: p.fg, bold: true, font }),
1249
- ]))
1250
- if (subtitle !== '') {
1251
- shapes.push(textShapeXml(idBase + 3, 'Subtitle', { x: 1570000, y: 4150000, w: 9000000, h: 1200000 }, [
1252
- para(subtitle, { size: 2200, color: p.muted, font: theme.fonts.body }),
1253
- ]))
1254
- }
1255
- if (kicker !== '') {
1256
- shapes.push(textShapeXml(idBase + 4, 'Kicker', { x: 1570000, y: 5800000, w: 7000000, h: 500000 }, [
1257
- para(kicker, { size: 1400, color: p.accent, bold: true, font: theme.fonts.body }),
1258
- ]))
1259
- }
1260
- } else if (slide.layout === 'section') {
1261
- if (kicker !== '') {
1262
- shapes.push(textShapeXml(idBase + 1, 'Kicker', { x: 1050000, y: 2250000, w: 9000000, h: 500000 }, [
1263
- para(kicker, { size: 1600, color: p.accent, bold: true, font: theme.fonts.body }),
1264
- ]))
1265
- }
1266
- shapes.push(accentBarXml(idBase + 2, 'Accent bar', { x: 1050000, y: 2850000, w: 1600000, h: 160000 }, p.accent2))
1267
- shapes.push(textShapeXml(idBase + 3, 'Title', { x: 1050000, y: 3150000, w: 10200000, h: 1400000 }, [
1268
- para(title, { size: 4000, color: p.fg, bold: true, font }),
1269
- ]))
1270
- if (subtitle !== '') {
1271
- shapes.push(textShapeXml(idBase + 4, 'Subtitle', { x: 1070000, y: 4750000, w: 9000000, h: 900000 }, [
1272
- para(subtitle, { size: 1800, color: p.muted, font: theme.fonts.body }),
1273
- ]))
1274
- }
1275
- } else if (slide.layout === 'statement') {
1276
- shapes.push(accentBarXml(idBase + 1, 'Accent bar', { x: 914400, y: 1900000, w: 200000, h: 2800000 }, p.accent))
1277
- shapes.push(textShapeXml(idBase + 2, 'Statement', { x: 1500000, y: 1950000, w: 9400000, h: 2700000 }, [
1278
- para(title || slide.text || '', { size: 3600, color: p.fg, bold: true, font }),
1279
- ]))
1280
- if (subtitle !== '') {
1281
- shapes.push(textShapeXml(idBase + 3, 'Subtitle', { x: 1520000, y: 4900000, w: 9000000, h: 800000 }, [
1282
- para(subtitle, { size: 1800, color: p.muted, font: theme.fonts.body }),
1283
- ]))
1284
- }
1285
- } else if (slide.layout === 'quote') {
1286
- shapes.push(textShapeXml(idBase + 1, 'Quote mark', { x: 900000, y: 1050000, w: 1700000, h: 1900000 }, [
1287
- para('\u201C', { size: 9600, color: p.accent, bold: true, font }),
1288
- ]))
1289
- shapes.push(textShapeXml(idBase + 2, 'Quote', { x: 1050000, y: 2550000, w: 10100000, h: 2600000 }, [
1290
- para(title || slide.text || '', { size: 3000, color: p.fg, bold: true, font }),
1291
- ]))
1292
- if (subtitle !== '') {
1293
- shapes.push(textShapeXml(idBase + 3, 'Attribution', { x: 1070000, y: 5300000, w: 9000000, h: 600000 }, [
1294
- para('\u2014\u2014 ' + subtitle, { size: 1600, color: p.muted, font: theme.fonts.body }),
1295
- ]))
1296
- }
1297
- } else if (slide.layout === 'table') {
1298
- const hasTitle = title !== '' && title !== kicker
1299
- if (kicker !== '') {
1300
- shapes.push(textShapeXml(idBase + 1, 'Kicker', { x: 900000, y: 420000, w: 10000000, h: 420000 }, [
1301
- para(kicker, { size: 1400, color: p.accent, bold: true, font: theme.fonts.body }),
1302
- ]))
1303
- }
1304
- if (hasTitle) {
1305
- shapes.push(textShapeXml(idBase + 2, 'Title', { x: 900000, y: 920000, w: 10300000, h: 800000 }, [
1306
- para(title, { size: 3400, color: p.fg, bold: true, font }),
1307
- ]))
1308
- }
1309
- shapes.push(tableGraphicXml(idBase + 3, 'Table', { x: 900000, y: hasTitle ? 1950000 : 900000, w: 10300000 }, Array.isArray(slide.rows) ? slide.rows : [], theme, lang))
1310
- } else if (slide.layout === 'closing') {
1311
- shapes.push(textShapeXml(idBase + 1, 'Title', { x: 1050000, y: 2300000, w: 10200000, h: 1700000 }, [
1312
- para(title || '谢谢', { size: 5200, color: p.fg, bold: true, align: 'ctr', font }),
1313
- ]))
1314
- if (subtitle !== '') {
1315
- shapes.push(textShapeXml(idBase + 2, 'Subtitle', { x: 1050000, y: 4200000, w: 10200000, h: 900000 }, [
1316
- para(subtitle, { size: 2000, color: p.accent, bold: true, align: 'ctr', font: theme.fonts.body }),
1317
- ]))
1318
- }
1319
- } else {
1320
- // bullets(默认布局)
1321
- if (kicker !== '') {
1322
- shapes.push(textShapeXml(idBase + 1, 'Kicker', { x: 900000, y: 420000, w: 10000000, h: 420000 }, [
1323
- para(kicker, { size: 1400, color: p.accent, bold: true, font: theme.fonts.body }),
1324
- ]))
1325
- }
1326
- shapes.push(textShapeXml(idBase + 2, 'Title', { x: 900000, y: 920000, w: 10300000, h: 800000 }, [
1327
- para(title, { size: 3400, color: p.fg, bold: true, font }),
1328
- ]))
1329
- const bodyParagraphs = bullets.length > 0
1330
- ? bullets.map((bullet) => para(bullet, { size: 2000, color: p.fg, bullet: true, font: theme.fonts.body, spaceAfter: 600 }))
1331
- : [para(subtitle || '', { size: 2000, color: p.fg, font: theme.fonts.body })]
1332
- shapes.push(textShapeXml(idBase + 3, 'Body', { x: 1050000, y: 1850000, w: 10100000, h: 4500000 }, bodyParagraphs))
1333
- }
1334
-
1335
- shapes.push(textShapeXml(idBase + 9, 'Page number', { x: 10600000, y: 6250000, w: 1200000, h: 400000 }, [
1336
- para(footer, { size: 1000, color: p.muted, align: 'r', font: theme.fonts.body }),
1337
- ]))
1338
-
1339
- return shapes.join('')
1340
- }
1341
-
1342
- /**
1343
- * 原生逐条点击显现动画(PowerPoint「出现,按段落」的标准时序树):
1344
- * bldP 把正文文本框标记为按段落构建,主序列里每条要点一个点击节点。
1345
- */
1346
- function bulletTimingXml(spid, clicks) {
1347
- let id = 2
1348
- const nextId = () => { id += 1; return String(id) }
1349
- const clickPars = []
1350
- for (let i = 0; i < clicks; i += 1) {
1351
- clickPars.push(
1352
- '<p:par><p:cTn id="' + nextId() + '" fill="hold"><p:stCondLst><p:cond delay="indefinite"/></p:stCondLst><p:childTnLst>' +
1353
- '<p:par><p:cTn id="' + nextId() + '" presetID="1" presetClass="entr" presetSubtype="0" fill="hold" grpId="0" nodeType="clickEffect">' +
1354
- '<p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst>' +
1355
- '<p:set><p:cBhvr><p:cTn id="' + nextId() + '" dur="1" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn>' +
1356
- '<p:tgtEl><p:spTgt spid="' + spid + '"/></p:tgtEl>' +
1357
- '<p:attrNameLst><p:attrName>style.visibility</p:attrName></p:attrNameLst></p:cBhvr>' +
1358
- '<p:to><p:strVal val="visible"/></p:to></p:set>' +
1359
- '</p:childTnLst></p:cTn></p:par>' +
1360
- '</p:childTnLst></p:cTn></p:par>',
1361
- )
1362
- }
1363
- return '<p:timing><p:tnLst><p:par>' +
1364
- '<p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot"><p:childTnLst>' +
1365
- '<p:seq concurrent="1" nextAc="seek"><p:cTn id="2" dur="indefinite" nodeType="mainSeq"><p:childTnLst>' +
1366
- clickPars.join('') +
1367
- '</p:childTnLst></p:cTn>' +
1368
- '<p:prevCondLst><p:cond evt="onPrev" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:prevCondLst>' +
1369
- '<p:nextCondLst><p:cond evt="onNext" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:nextCondLst>' +
1370
- '</p:seq></p:childTnLst></p:cTn></p:par></p:tnLst>' +
1371
- '<p:bldLst><p:bldP spid="' + spid + '" grpId="0"/></p:bldLst></p:timing>'
1372
- }
1373
-
1374
- function slideXml(slide, index, total, theme, langId, motion) {
1375
- const p = theme.palette
1376
- let motionXml = ''
1377
- if (motion) {
1378
- motionXml = '<p:transition spd="med"><p:fade/></p:transition>'
1379
- const bullets = Array.isArray(slide.bullets) ? slide.bullets : []
1380
- if (slide.layout === 'bullets' && bullets.length >= 2) {
1381
- motionXml += bulletTimingXml((index + 1) * 10 + 3, bullets.length)
1382
- }
1383
- }
1384
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1385
- '<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1386
- 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1387
- 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1388
- '<p:cSld><p:bg><p:bgPr><a:solidFill><a:srgbClr val="' + hex(p.bg) + '"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>' +
1389
- '<p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1390
- '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1391
- slideShapeList(slide, index, total, theme, langId) +
1392
- '</p:spTree></p:cSld>' +
1393
- '<p:clrMapOvr><a:overrideClrMapping bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/></p:clrMapOvr>' +
1394
- motionXml +
1395
- '</p:sld>'
1396
- }
1397
-
1398
- function slideRelXml(hasNotes, slideIndex) {
1399
- const notesRel = hasNotes
1400
- ? '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/notesSlide' + slideIndex + '.xml"/>'
1401
- : ''
1402
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1403
- '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1404
- '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>' +
1405
- notesRel +
1406
- '</Relationships>'
1407
- }
1408
-
1409
- function presentationXml(slideCount, hasNotesMaster) {
1410
- const slideIds = Array.from({ length: slideCount }, (_, i) =>
1411
- '<p:sldId id="' + (256 + i) + '" r:id="rId' + (i + 2) + '"/>').join('')
1412
- const notesMasterId = hasNotesMaster
1413
- ? '<p:notesMasterIdLst><p:notesMasterId id="2147483649" r:id="rId' + (slideCount + 2) + '"/></p:notesMasterIdLst>'
1414
- : ''
1415
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1416
- '<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1417
- 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1418
- 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1419
- '<p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst>' +
1420
- '<p:sldIdLst>' + slideIds + '</p:sldIdLst>' +
1421
- notesMasterId +
1422
- '<p:sldSz cx="' + EMU_W + '" cy="' + EMU_H + '" type="screen16x9"/>' +
1423
- '<p:notesSz cx="6858000" cy="9144000"/>' +
1424
- '</p:presentation>'
1425
- }
1426
-
1427
- function presentationRelXml(slideCount, hasNotesMaster) {
1428
- const slideRels = Array.from({ length: slideCount }, (_, i) =>
1429
- '<Relationship Id="rId' + (i + 2) + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide' + (i + 1) + '.xml"/>').join('')
1430
- const notesMasterRel = hasNotesMaster
1431
- ? '<Relationship Id="rId' + (slideCount + 2) + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target="notesMasters/notesMaster1.xml"/>'
1432
- : ''
1433
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1434
- '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1435
- '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/>' +
1436
- slideRels +
1437
- notesMasterRel +
1438
- '</Relationships>'
1439
- }
1440
-
1441
- function notesMasterXml() {
1442
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1443
- '<p:notesMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1444
- 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1445
- 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1446
- '<p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1447
- '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1448
- '</p:spTree></p:cSld>' +
1449
- '<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>' +
1450
- '<p:notesStyle><a:lvl1pPr><a:defRPr sz="1200"/></a:lvl1pPr></p:notesStyle>' +
1451
- '</p:notesMaster>'
1452
- }
1453
-
1454
- function notesMasterRelXml() {
1455
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1456
- '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1457
- '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>' +
1458
- '</Relationships>'
1459
- }
1460
-
1461
- function notesSlideXml(notes, langId) {
1462
- const lang = langId || 'zh-CN'
1463
- const paragraphs = String(notes ?? '').split('\n')
1464
- .filter((line) => line.trim() !== '')
1465
- .map((line) => '<a:p><a:r><a:rPr lang="' + lang + '" sz="1200" dirty="0"/><a:t>' + escapeXml(line) + '</a:t></a:r></a:p>')
1466
- .join('')
1467
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1468
- '<p:notes xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1469
- 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1470
- 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1471
- '<p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1472
- '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1473
- '<p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image Placeholder 1"/><p:cNvSpPr/><p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>' +
1474
- '<p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes Placeholder 2"/><p:cNvSpPr/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/>' +
1475
- '<p:txBody><a:bodyPr/><a:lstStyle/>' + paragraphs + '</p:txBody></p:sp>' +
1476
- '</p:spTree></p:cSld>' +
1477
- '<p:clrMapOvr><a:overrideClrMapping bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/></p:clrMapOvr>' +
1478
- '</p:notes>'
1479
- }
1480
-
1481
- function notesSlideRelXml(slideIndex) {
1482
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1483
- '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1484
- '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="../slides/slide' + slideIndex + '.xml"/>' +
1485
- '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target="../notesMasters/notesMaster1.xml"/>' +
1486
- '</Relationships>'
1487
- }
1488
-
1489
- function slideMasterXml(theme) {
1490
- const p = theme.palette
1491
- const levels = Array.from({ length: 9 }, (_, i) => {
1492
- const sz = Math.max(1100, 2000 - i * 100)
1493
- return '<a:lvl' + (i + 1) + 'pPr marL="' + (342900 + i * 342900) + '" indent="' + (-342900 - i * 0) + '">' +
1494
- '<a:defRPr sz="' + sz + '"><a:solidFill><a:srgbClr val="' + hex(p.fg) + '"/></a:solidFill><a:latin typeface="' + escapeXml(pptxFontName(theme.fonts.body)) + '"/></a:defRPr></a:lvl' + (i + 1) + 'pPr>'
1495
- }).join('')
1496
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1497
- '<p:sldMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1498
- 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1499
- 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1500
- '<p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1501
- '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1502
- '</p:spTree></p:cSld>' +
1503
- '<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>' +
1504
- '<p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst>' +
1505
- '<p:txStyles><p:titleStyle>' + levels + '</p:titleStyle><p:bodyStyle>' + levels + '</p:bodyStyle><p:otherStyle>' + levels + '</p:otherStyle></p:txStyles>' +
1506
- '</p:sldMaster>'
1507
- }
1508
-
1509
- function slideMasterRelXml() {
1510
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1511
- '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1512
- '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>' +
1513
- '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>' +
1514
- '</Relationships>'
1515
- }
1516
-
1517
- function slideLayoutXml(theme) {
1518
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1519
- '<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1520
- 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1521
- 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="blank" preserve="1">' +
1522
- '<p:cSld name="Blank"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1523
- '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1524
- '</p:spTree></p:cSld>' +
1525
- '<p:clrMapOvr><a:overrideClrMapping bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/></p:clrMapOvr>' +
1526
- '</p:sldLayout>'
1527
- }
1528
-
1529
- function slideLayoutRelXml() {
1530
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1531
- '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1532
- '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="../slideMasters/slideMaster1.xml"/>' +
1533
- '</Relationships>'
1534
- }
1535
-
1536
- function themeXml(theme) {
1537
- const p = theme.palette
1538
- const color = (name, value) => '<a:' + name + '><a:srgbClr val="' + hex(value) + '"/></a:' + name + '>'
1539
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1540
- '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="dsh-ppt ' + escapeXml(theme.name.en) + '">' +
1541
- '<a:themeElements>' +
1542
- '<a:clrScheme name="dsh-ppt">' +
1543
- color('dk1', p.fg) + color('lt1', p.bg) + color('dk2', p.muted) + color('lt2', p.panel) +
1544
- color('accent1', p.accent) + color('accent2', p.accent2) + color('accent3', p.fg) +
1545
- color('accent4', p.muted) + color('accent5', p.accent) + color('accent6', p.accent2) +
1546
- color('hlink', p.accent) + color('folHlink', p.accent2) +
1547
- '</a:clrScheme>' +
1548
- '<a:fontScheme name="dsh-ppt">' +
1549
- '<a:majorFont><a:latin typeface="' + escapeXml(pptxFontName(theme.fonts.heading)) + '"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont>' +
1550
- '<a:minorFont><a:latin typeface="' + escapeXml(pptxFontName(theme.fonts.body)) + '"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont>' +
1551
- '</a:fontScheme>' +
1552
- '<a:fmtScheme name="dsh-ppt">' +
1553
- '<a:fillStyleLst>' +
1554
- '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
1555
- '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
1556
- '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
1557
- '</a:fillStyleLst>' +
1558
- '<a:lnStyleLst><a:ln w="6350" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="12700" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="19050" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln></a:lnStyleLst>' +
1559
- '<a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>' +
1560
- '<a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:bgFillStyleLst>' +
1561
- '</a:fmtScheme>' +
1562
- '</a:themeElements>' +
1563
- '<a:objectDefaults/><a:extraClrSchemeLst/>' +
1564
- '</a:theme>'
1565
- }
1566
-
1567
- function contentTypesXml(slideCount, noteIndexes) {
1568
- const overrides = Array.from({ length: slideCount }, (_, i) =>
1569
- '<Override PartName="/ppt/slides/slide' + (i + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>').join('')
1570
- const notesOverrides = noteIndexes.map((index) =>
1571
- '<Override PartName="/ppt/notesSlides/notesSlide' + (index + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"/>').join('')
1572
- const notesMasterOverride = noteIndexes.length > 0
1573
- ? '<Override PartName="/ppt/notesMasters/notesMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"/>'
1574
- : ''
1575
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1576
- '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
1577
- '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
1578
- '<Default Extension="xml" ContentType="application/xml"/>' +
1579
- '<Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/>' +
1580
- '<Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/>' +
1581
- '<Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/>' +
1582
- '<Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>' +
1583
- '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>' +
1584
- '<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>' +
1585
- notesMasterOverride +
1586
- overrides +
1587
- notesOverrides +
1588
- '</Types>'
1589
- }
1590
-
1591
- function rootRelXml() {
1592
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1593
- '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1594
- '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/>' +
1595
- '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>' +
1596
- '<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>' +
1597
- '</Relationships>'
1598
- }
1599
-
1600
- function coreXml(title) {
1601
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1602
- '<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ' +
1603
- 'xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" ' +
1604
- 'xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
1605
- '<dc:title>' + escapeXml(title) + '</dc:title><dc:creator>dsh-ppt</dc:creator>' +
1606
- '<cp:lastModifiedBy>dsh-ppt</cp:lastModifiedBy>' +
1607
- '</cp:coreProperties>'
1608
- }
1609
-
1610
- function appXml(slideCount, notesCount) {
1611
- return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1612
- '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" ' +
1613
- 'xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">' +
1614
- '<Application>dsh-ppt</Application><PresentationFormat>Widescreen</PresentationFormat>' +
1615
- '<Slides>' + slideCount + '</Slides><Notes>' + notesCount + '</Notes><HiddenSlides>0</HiddenSlides>' +
1616
- '</Properties>'
1617
- }
1618
-
1619
- function buildZip(entries) {
1620
- const chunks = []
1621
- const central = []
1622
- let offset = 0
1623
-
1624
- for (const entry of entries) {
1625
- const entryOffset = offset
1626
- const name = Buffer.from(entry.name, 'utf8')
1627
- const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(String(entry.data), 'utf8')
1628
- const crc = crc32(data)
1629
- const compressed = deflateRawSync(data)
1630
- const method = 8
1631
- const nameLength = name.length
1632
- const localHeader = Buffer.alloc(30)
1633
- localHeader.writeUInt32LE(0x04034b50, 0)
1634
- localHeader.writeUInt16LE(20, 4)
1635
- localHeader.writeUInt16LE(0x0800, 6) // UTF-8 文件名
1636
- localHeader.writeUInt16LE(method, 8)
1637
- localHeader.writeUInt16LE(0, 10) // DOS time
1638
- localHeader.writeUInt16LE(0x21, 12) // DOS date 1980-01-01
1639
- localHeader.writeUInt32LE(crc, 14)
1640
- localHeader.writeUInt32LE(compressed.length, 18)
1641
- localHeader.writeUInt32LE(data.length, 22)
1642
- localHeader.writeUInt16LE(nameLength, 26)
1643
- localHeader.writeUInt16LE(0, 28)
1644
-
1645
- chunks.push(localHeader, name, compressed)
1646
- offset += 30 + nameLength + compressed.length
1647
-
1648
- const centralHeader = Buffer.alloc(46)
1649
- centralHeader.writeUInt32LE(0x02014b50, 0)
1650
- centralHeader.writeUInt16LE(20, 4)
1651
- centralHeader.writeUInt16LE(20, 6)
1652
- centralHeader.writeUInt16LE(0x0800, 8)
1653
- centralHeader.writeUInt16LE(method, 10)
1654
- centralHeader.writeUInt16LE(0, 12)
1655
- centralHeader.writeUInt16LE(0x21, 14)
1656
- centralHeader.writeUInt32LE(crc, 16)
1657
- centralHeader.writeUInt32LE(compressed.length, 20)
1658
- centralHeader.writeUInt32LE(data.length, 24)
1659
- centralHeader.writeUInt16LE(nameLength, 28)
1660
- centralHeader.writeUInt16LE(0, 30)
1661
- centralHeader.writeUInt16LE(0, 32)
1662
- centralHeader.writeUInt16LE(0, 34)
1663
- centralHeader.writeUInt16LE(0, 36)
1664
- centralHeader.writeUInt32LE(0, 38)
1665
- centralHeader.writeUInt32LE(entryOffset, 42)
1666
- central.push(centralHeader, name)
1667
- }
1668
-
1669
- const centralOffset = offset
1670
- const centralSize = central.reduce((sum, part) => sum + part.length, 0)
1671
- const end = Buffer.alloc(22)
1672
- end.writeUInt32LE(0x06054b50, 0)
1673
- end.writeUInt16LE(0, 4)
1674
- end.writeUInt16LE(0, 6)
1675
- end.writeUInt16LE(entries.length, 8)
1676
- end.writeUInt16LE(entries.length, 10)
1677
- end.writeUInt32LE(centralSize, 12)
1678
- end.writeUInt32LE(centralOffset, 16)
1679
- end.writeUInt16LE(0, 20)
1680
-
1681
- chunks.push(...central, end)
1682
- return Buffer.concat(chunks)
1683
- }
1684
-
1685
- let CRC_TABLE = null
1686
- function crc32(buffer) {
1687
- if (CRC_TABLE === null) {
1688
- CRC_TABLE = new Int32Array(256)
1689
- for (let n = 0; n < 256; n += 1) {
1690
- let c = n
1691
- for (let k = 0; k < 8; k += 1) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1)
1692
- CRC_TABLE[n] = c
1693
- }
1694
- }
1695
- let crc = 0xffffffff
1696
- for (let i = 0; i < buffer.length; i += 1) {
1697
- crc = CRC_TABLE[(crc ^ buffer[i]) & 0xff] ^ (crc >>> 8)
1698
- }
1699
- return (crc ^ 0xffffffff) >>> 0
1700
- }
1701
-
1702
- export function buildPptx(manifest, themeInput, languageInput) {
1703
- const theme = themeInput?.id ? themeInput : resolveTheme(themeInput)
1704
- const language = languageInput?.id ? languageInput : resolveLanguage(languageInput)
1705
- const motion = manifest.motion !== false
1706
- const slides = manifest.slides
1707
- const noteIndexes = []
1708
- slides.forEach((slide, index) => {
1709
- if (typeof slide.notes === 'string' && slide.notes.trim() !== '') noteIndexes.push(index)
1710
- })
1711
- const hasNotesMaster = noteIndexes.length > 0
1712
- const entries = [
1713
- { name: '[Content_Types].xml', data: contentTypesXml(slides.length, noteIndexes) },
1714
- { name: '_rels/.rels', data: rootRelXml() },
1715
- { name: 'docProps/app.xml', data: appXml(slides.length, noteIndexes.length) },
1716
- { name: 'docProps/core.xml', data: coreXml(manifest.title) },
1717
- { name: 'ppt/presentation.xml', data: presentationXml(slides.length, hasNotesMaster) },
1718
- { name: 'ppt/_rels/presentation.xml.rels', data: presentationRelXml(slides.length, hasNotesMaster) },
1719
- { name: 'ppt/slideMasters/slideMaster1.xml', data: slideMasterXml(theme) },
1720
- { name: 'ppt/slideMasters/_rels/slideMaster1.xml.rels', data: slideMasterRelXml() },
1721
- { name: 'ppt/slideLayouts/slideLayout1.xml', data: slideLayoutXml(theme) },
1722
- { name: 'ppt/slideLayouts/_rels/slideLayout1.xml.rels', data: slideLayoutRelXml() },
1723
- { name: 'ppt/theme/theme1.xml', data: themeXml(theme) },
1724
- ]
1725
- if (hasNotesMaster) {
1726
- entries.push({ name: 'ppt/notesMasters/notesMaster1.xml', data: notesMasterXml() })
1727
- entries.push({ name: 'ppt/notesMasters/_rels/notesMaster1.xml.rels', data: notesMasterRelXml() })
1728
- }
1729
- slides.forEach((slide, index) => {
1730
- const hasNotes = noteIndexes.includes(index)
1731
- entries.push({ name: 'ppt/slides/slide' + (index + 1) + '.xml', data: slideXml(slide, index, slides.length, theme, language.attr, motion) })
1732
- entries.push({ name: 'ppt/slides/_rels/slide' + (index + 1) + '.xml.rels', data: slideRelXml(hasNotes, index + 1) })
1733
- if (hasNotes) {
1734
- entries.push({ name: 'ppt/notesSlides/notesSlide' + (index + 1) + '.xml', data: notesSlideXml(slide.notes, language.attr) })
1735
- entries.push({ name: 'ppt/notesSlides/_rels/notesSlide' + (index + 1) + '.xml.rels', data: notesSlideRelXml(index + 1) })
1736
- }
1737
- })
1738
- return buildZip(entries)
1739
- }
1500
+ function renderHtmlSlide(slide, index, ui, langId) {
1501
+ const kicker = slide.kicker || (slide.layout === 'cover' ? ui.coverKicker : '')
1502
+ const title = slide.title || ''
1503
+ const subtitle = slide.subtitle || ''
1504
+ const bullets = Array.isArray(slide.bullets) ? slide.bullets : []
1505
+ const number = String(index + 1).padStart(2, '0')
1506
+ let inner = ''
1507
+ switch (slide.layout) {
1508
+ case 'cover':
1509
+ inner = '<div class="kicker">' + escapeHtml(kicker) + '</div>' +
1510
+ '<h1>' + escapeHtml(title) + '</h1>' +
1511
+ (subtitle !== '' ? '<div class="subtitle">' + escapeHtml(subtitle) + '</div>' : '') +
1512
+ '<div class="meta">' + escapeHtml(ui.generatedBy) + '</div>'
1513
+ break
1514
+ case 'section':
1515
+ inner = '<div class="kicker">' + escapeHtml(kicker) + '</div>' +
1516
+ '<h2>' + escapeHtml(title) + '</h2>' +
1517
+ '<div class="accent-line"></div>' +
1518
+ (subtitle !== '' ? '<div class="subtitle">' + escapeHtml(subtitle) + '</div>' : '')
1519
+ break
1520
+ case 'statement':
1521
+ inner = '<div class="kicker">' + escapeHtml(kicker) + '</div>' +
1522
+ '<div class="statement-title">' + escapeHtml(title || slide.text || '') + '</div>' +
1523
+ (subtitle !== '' ? '<div class="subtitle">' + escapeHtml(subtitle) + '</div>' : '')
1524
+ break
1525
+ case 'quote':
1526
+ inner = '<div class="kicker">' + escapeHtml(kicker || ui.quoteKicker) + '</div>' +
1527
+ '<div class="quote-mark" aria-hidden="true">\u201C</div>' +
1528
+ '<blockquote class="quote-text">' + escapeHtml(title || slide.text || '') + '</blockquote>' +
1529
+ (subtitle !== '' ? '<div class="quote-attr">\u2014\u2014 ' + escapeHtml(subtitle) + '</div>' : '')
1530
+ break
1531
+ case 'table': {
1532
+ const rows = Array.isArray(slide.rows) ? slide.rows : []
1533
+ const head = rows[0] ?? []
1534
+ const body = rows.slice(1)
1535
+ const isNum = (cell) => /^\s*[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?\s*(?:%|%|次|页|个|人|元|天|小时|分钟)?\s*$/.test(String(cell ?? ''))
1536
+ const headingText = title !== '' ? title : (kicker || ui.tableKicker)
1537
+ const showKicker = kicker !== '' && kicker !== headingText
1538
+ inner = (showKicker ? '<div class="kicker">' + escapeHtml(kicker) + '</div>' : '') +
1539
+ '<h2>' + escapeHtml(headingText) + '</h2>' +
1540
+ '<table class="deck-table"><thead><tr>' +
1541
+ head.map((cell) => '<th' + (isNum(cell) ? ' class="num"' : '') + '>' + escapeHtml(cell) + '</th>').join('') +
1542
+ '</tr></thead><tbody>' +
1543
+ body.map((row) => '<tr>' + row.map((cell) => '<td' + (isNum(cell) ? ' class="num"' : '') + '>' + escapeHtml(cell) + '</td>').join('') + '</tr>').join('') +
1544
+ '</tbody></table>'
1545
+ break
1546
+ }
1547
+ case 'closing':
1548
+ inner = '<h1>' + escapeHtml(title || ui.closingTitle) + '</h1>' +
1549
+ (subtitle !== '' ? '<div class="subtitle">' + escapeHtml(subtitle) + '</div>' : '') +
1550
+ '<div class="meta">' + escapeHtml(ui.generatedBy) + '</div>'
1551
+ break
1552
+ case 'bullets':
1553
+ default:
1554
+ inner = '<div class="kicker">' + escapeHtml(kicker) + '</div>' +
1555
+ '<h2>' + escapeHtml(title) + '</h2>' +
1556
+ '<ul>' + bullets.map((bullet, bulletIndex) => '<li style="--i:' + bulletIndex + '">' + escapeHtml(bullet) + '</li>').join('') + '</ul>'
1557
+ break
1558
+ }
1559
+ const notesAttr = typeof slide.notes === 'string' && slide.notes.trim() !== ''
1560
+ ? ' data-notes="' + escapeHtml(slide.notes) + '"'
1561
+ : ''
1562
+ return '<section class="slide slide--' + escapeHtml(slide.layout || 'bullets') + '" data-index="' + number + '"' + notesAttr + '>' +
1563
+ '<div class="slide-inner">' + inner + '</div></section>'
1564
+ }
1565
+
1566
+ function hexToRgba(hex, alpha) {
1567
+ const value = String(hex).replace('#', '')
1568
+ const full = value.length === 3 ? value.split('').map((c) => c + c).join('') : value
1569
+ const num = Number.parseInt(full, 16)
1570
+ const r = (num >> 16) & 255
1571
+ const g = (num >> 8) & 255
1572
+ const b = num & 255
1573
+ return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')'
1574
+ }
1575
+
1576
+ // ---------------------------------------------------------------------------
1577
+ // PPTX(OOXML 手写 + node:zlib zip)
1578
+ // ---------------------------------------------------------------------------
1579
+
1580
+ const EMU_W = 12192000
1581
+ const EMU_H = 6858000
1582
+
1583
+ function hex(value) {
1584
+ return String(value).replace('#', '').toUpperCase()
1585
+ }
1586
+
1587
+ function pptxFontName(value) {
1588
+ const match = /"?([^",]+)"?/.exec(String(value ?? ''))
1589
+ return match?.[1]?.trim() || 'Arial'
1590
+ }
1591
+
1592
+ function paragraphXml(text, options = {}) {
1593
+ const {
1594
+ size = 2000,
1595
+ color = 'FFFFFF',
1596
+ bold = false,
1597
+ lang = 'zh-CN',
1598
+ align = 'l',
1599
+ bullet = false,
1600
+ font = 'Arial',
1601
+ spaceBefore = 0,
1602
+ spaceAfter = 0,
1603
+ } = options
1604
+ const runFont = pptxFontName(font)
1605
+ let pPr = ''
1606
+ if (bullet) {
1607
+ pPr = '<a:pPr marL="285750" indent="-285750"><a:buFont typeface="Arial" panose="020B0604020202020204"/><a:buChar char="•"/></a:pPr>'
1608
+ } else {
1609
+ const parts = [] // align 与 spacing 二选一
1610
+ if (align !== 'l') parts.push('algn="' + align + '"')
1611
+ if (spaceBefore > 0) parts.push('<a:spcBef><a:spcPts val="' + (spaceBefore / 100) + '"/></a:spcBef>')
1612
+ if (spaceAfter > 0) parts.push('<a:spcAft><a:spcPts val="' + (spaceAfter / 100) + '"/></a:spcAft>')
1613
+ pPr = '<a:pPr' + (parts.length > 0 ? ' ' + parts.join(' ') : '') + '><a:buNone/></a:pPr>'
1614
+ }
1615
+ return '<a:p>' + pPr +
1616
+ '<a:r><a:rPr lang="' + lang + '" sz="' + size + '" b="' + (bold ? 1 : 0) + '" dirty="0">' +
1617
+ '<a:solidFill><a:srgbClr val="' + hex(color) + '"/></a:solidFill>' +
1618
+ '<a:latin typeface="' + escapeXml(runFont) + '"/><a:ea typeface="' + escapeXml(runFont) + '"/></a:rPr>' +
1619
+ '<a:t>' + escapeXml(text) + '</a:t></a:r></a:p>'
1620
+ }
1621
+
1622
+ function textShapeXml(id, name, box, paragraphs, options = {}) {
1623
+ const { x = 0, y = 0, w = EMU_W, h = EMU_H } = box
1624
+ return '<p:sp>' +
1625
+ '<p:nvSpPr><p:cNvPr id="' + id + '" name="' + escapeXml(name) + '"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>' +
1626
+ '<p:spPr><a:xfrm><a:off x="' + x + '" y="' + y + '"/><a:ext cx="' + w + '" cy="' + h + '"/></a:xfrm>' +
1627
+ '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln/></p:spPr>' +
1628
+ '<p:txBody><a:bodyPr wrap="square" rtlCol="0"><a:normAutofit/></a:bodyPr><a:lstStyle/>' +
1629
+ paragraphs.join('') + '</p:txBody></p:sp>'
1630
+ }
1631
+
1632
+ function accentBarXml(id, name, box, color) {
1633
+ const { x = 0, y = 0, w = EMU_W, h = EMU_H } = box
1634
+ return '<p:sp>' +
1635
+ '<p:nvSpPr><p:cNvPr id="' + id + '" name="' + escapeXml(name) + '"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>' +
1636
+ '<p:spPr><a:xfrm><a:off x="' + x + '" y="' + y + '"/><a:ext cx="' + w + '" cy="' + h + '"/></a:xfrm>' +
1637
+ '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>' +
1638
+ '<a:solidFill><a:srgbClr val="' + hex(color) + '"/></a:solidFill><a:ln/></p:spPr>' +
1639
+ '<p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp>'
1640
+ }
1641
+
1642
+ /** 原生 OOXML 表格(graphicFrame + a:tbl):首行主题色表头,隔行面板色。 */
1643
+ function tableGraphicXml(id, name, box, rows, theme, langId) {
1644
+ const p = theme.palette
1645
+ const lang = langId || 'zh-CN'
1646
+ const font = pptxFontName(theme.fonts.body)
1647
+ const safeRows = rows.length > 0 ? rows : [['']]
1648
+ const cols = Math.max(1, safeRows[0].length)
1649
+ const colW = Math.floor(box.w / cols)
1650
+ const grid = Array.from({ length: cols }, () => '<a:gridCol w="' + colW + '"/>').join('')
1651
+ const rowH = 420000
1652
+ const cellXml = (text, fill, color, bold) =>
1653
+ '<a:tc><a:txBody><a:bodyPr anchor="ctr"/><a:lstStyle/><a:p><a:pPr algn="l"><a:buNone/></a:pPr>' +
1654
+ '<a:r><a:rPr lang="' + lang + '" sz="1400" b="' + (bold ? 1 : 0) + '" dirty="0">' +
1655
+ '<a:solidFill><a:srgbClr val="' + hex(color) + '"/></a:solidFill>' +
1656
+ '<a:latin typeface="' + escapeXml(font) + '"/><a:ea typeface="' + escapeXml(font) + '"/></a:rPr>' +
1657
+ '<a:t>' + escapeXml(text) + '</a:t></a:r></a:p></a:txBody>' +
1658
+ '<a:tcPr marL="91440" marR="91440" anchor="ctr">' +
1659
+ (fill !== '' ? '<a:solidFill><a:srgbClr val="' + hex(fill) + '"/></a:solidFill>' : '<a:noFill/>') +
1660
+ '</a:tcPr></a:tc>'
1661
+ const trs = safeRows.map((row, rowIndex) => {
1662
+ const padded = Array.from({ length: cols }, (_, i) => row[i] ?? '')
1663
+ const cells = rowIndex === 0
1664
+ ? padded.map((c) => cellXml(c, p.accent, p.bg, true)).join('')
1665
+ : padded.map((c) => cellXml(c, rowIndex % 2 === 1 ? p.panel : '', p.fg, false)).join('')
1666
+ return '<a:tr h="' + rowH + '">' + cells + '</a:tr>'
1667
+ }).join('')
1668
+ const height = Math.max(1, safeRows.length) * rowH
1669
+ return '<p:graphicFrame>' +
1670
+ '<p:nvGraphicFramePr><p:cNvPr id="' + id + '" name="' + escapeXml(name) + '"/>' +
1671
+ '<p:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr>' +
1672
+ '<p:xfrm><a:off x="' + box.x + '" y="' + box.y + '"/><a:ext cx="' + box.w + '" cy="' + height + '"/></p:xfrm>' +
1673
+ '<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table">' +
1674
+ '<a:tbl><a:tblPr firstRow="1" bandRow="1"/>' +
1675
+ '<a:tblGrid>' + grid + '</a:tblGrid>' + trs + '</a:tbl>' +
1676
+ '</a:graphicData></a:graphic></p:graphicFrame>'
1677
+ }
1678
+
1679
+ function slideShapeList(slide, index, total, theme, langId) {
1680
+ const p = theme.palette
1681
+ const font = pptxFontName(theme.fonts.heading)
1682
+ const bodyFont = pptxFontName(theme.fonts.body) // 保留:v0.1 后续用于统一正文字体
1683
+ const lang = langId || 'zh-CN'
1684
+ // PPTX 每个文本 run 的语言跟随 deck.lang(zh-CN / en-US),不再写死中文
1685
+ const para = (content, options = {}) => paragraphXml(content, { lang, ...options })
1686
+ const shapes = []
1687
+ const kicker = slide.kicker || ''
1688
+ const title = slide.title || ''
1689
+ const subtitle = slide.subtitle || ''
1690
+ const bullets = Array.isArray(slide.bullets) ? slide.bullets : []
1691
+ const idBase = (index + 1) * 10
1692
+ const footer = String(index + 1).padStart(2, '0') + ' / ' + String(total).padStart(2, '0')
1693
+
1694
+ if (slide.layout === 'cover') {
1695
+ shapes.push(accentBarXml(idBase + 1, 'Accent bar', { x: 914400, y: 2250000, w: 240000, h: 1600000 }, p.accent))
1696
+ shapes.push(textShapeXml(idBase + 2, 'Title', { x: 1550000, y: 2160000, w: 9250000, h: 1800000 }, [
1697
+ para(title, { size: 4400, color: p.fg, bold: true, font }),
1698
+ ]))
1699
+ if (subtitle !== '') {
1700
+ shapes.push(textShapeXml(idBase + 3, 'Subtitle', { x: 1570000, y: 4150000, w: 9000000, h: 1200000 }, [
1701
+ para(subtitle, { size: 2200, color: p.muted, font: theme.fonts.body }),
1702
+ ]))
1703
+ }
1704
+ if (kicker !== '') {
1705
+ shapes.push(textShapeXml(idBase + 4, 'Kicker', { x: 1570000, y: 5800000, w: 7000000, h: 500000 }, [
1706
+ para(kicker, { size: 1400, color: p.accent, bold: true, font: theme.fonts.body }),
1707
+ ]))
1708
+ }
1709
+ } else if (slide.layout === 'section') {
1710
+ if (kicker !== '') {
1711
+ shapes.push(textShapeXml(idBase + 1, 'Kicker', { x: 1050000, y: 2250000, w: 9000000, h: 500000 }, [
1712
+ para(kicker, { size: 1600, color: p.accent, bold: true, font: theme.fonts.body }),
1713
+ ]))
1714
+ }
1715
+ shapes.push(accentBarXml(idBase + 2, 'Accent bar', { x: 1050000, y: 2850000, w: 1600000, h: 160000 }, p.accent2))
1716
+ shapes.push(textShapeXml(idBase + 3, 'Title', { x: 1050000, y: 3150000, w: 10200000, h: 1400000 }, [
1717
+ para(title, { size: 4000, color: p.fg, bold: true, font }),
1718
+ ]))
1719
+ if (subtitle !== '') {
1720
+ shapes.push(textShapeXml(idBase + 4, 'Subtitle', { x: 1070000, y: 4750000, w: 9000000, h: 900000 }, [
1721
+ para(subtitle, { size: 1800, color: p.muted, font: theme.fonts.body }),
1722
+ ]))
1723
+ }
1724
+ } else if (slide.layout === 'statement') {
1725
+ shapes.push(accentBarXml(idBase + 1, 'Accent bar', { x: 914400, y: 1900000, w: 200000, h: 2800000 }, p.accent))
1726
+ shapes.push(textShapeXml(idBase + 2, 'Statement', { x: 1500000, y: 1950000, w: 9400000, h: 2700000 }, [
1727
+ para(title || slide.text || '', { size: 3600, color: p.fg, bold: true, font }),
1728
+ ]))
1729
+ if (subtitle !== '') {
1730
+ shapes.push(textShapeXml(idBase + 3, 'Subtitle', { x: 1520000, y: 4900000, w: 9000000, h: 800000 }, [
1731
+ para(subtitle, { size: 1800, color: p.muted, font: theme.fonts.body }),
1732
+ ]))
1733
+ }
1734
+ } else if (slide.layout === 'quote') {
1735
+ shapes.push(textShapeXml(idBase + 1, 'Quote mark', { x: 900000, y: 1050000, w: 1700000, h: 1900000 }, [
1736
+ para('\u201C', { size: 9600, color: p.accent, bold: true, font }),
1737
+ ]))
1738
+ shapes.push(textShapeXml(idBase + 2, 'Quote', { x: 1050000, y: 2550000, w: 10100000, h: 2600000 }, [
1739
+ para(title || slide.text || '', { size: 3000, color: p.fg, bold: true, font }),
1740
+ ]))
1741
+ if (subtitle !== '') {
1742
+ shapes.push(textShapeXml(idBase + 3, 'Attribution', { x: 1070000, y: 5300000, w: 9000000, h: 600000 }, [
1743
+ para('\u2014\u2014 ' + subtitle, { size: 1600, color: p.muted, font: theme.fonts.body }),
1744
+ ]))
1745
+ }
1746
+ } else if (slide.layout === 'table') {
1747
+ const hasTitle = title !== '' && title !== kicker
1748
+ if (kicker !== '') {
1749
+ shapes.push(textShapeXml(idBase + 1, 'Kicker', { x: 900000, y: 420000, w: 10000000, h: 420000 }, [
1750
+ para(kicker, { size: 1400, color: p.accent, bold: true, font: theme.fonts.body }),
1751
+ ]))
1752
+ }
1753
+ if (hasTitle) {
1754
+ shapes.push(textShapeXml(idBase + 2, 'Title', { x: 900000, y: 920000, w: 10300000, h: 800000 }, [
1755
+ para(title, { size: 3400, color: p.fg, bold: true, font }),
1756
+ ]))
1757
+ }
1758
+ shapes.push(tableGraphicXml(idBase + 3, 'Table', { x: 900000, y: hasTitle ? 1950000 : 900000, w: 10300000 }, Array.isArray(slide.rows) ? slide.rows : [], theme, lang))
1759
+ } else if (slide.layout === 'closing') {
1760
+ shapes.push(textShapeXml(idBase + 1, 'Title', { x: 1050000, y: 2300000, w: 10200000, h: 1700000 }, [
1761
+ para(title || '谢谢', { size: 5200, color: p.fg, bold: true, align: 'ctr', font }),
1762
+ ]))
1763
+ if (subtitle !== '') {
1764
+ shapes.push(textShapeXml(idBase + 2, 'Subtitle', { x: 1050000, y: 4200000, w: 10200000, h: 900000 }, [
1765
+ para(subtitle, { size: 2000, color: p.accent, bold: true, align: 'ctr', font: theme.fonts.body }),
1766
+ ]))
1767
+ }
1768
+ } else {
1769
+ // bullets(默认布局)
1770
+ if (kicker !== '') {
1771
+ shapes.push(textShapeXml(idBase + 1, 'Kicker', { x: 900000, y: 420000, w: 10000000, h: 420000 }, [
1772
+ para(kicker, { size: 1400, color: p.accent, bold: true, font: theme.fonts.body }),
1773
+ ]))
1774
+ }
1775
+ shapes.push(textShapeXml(idBase + 2, 'Title', { x: 900000, y: 920000, w: 10300000, h: 800000 }, [
1776
+ para(title, { size: 3400, color: p.fg, bold: true, font }),
1777
+ ]))
1778
+ const bodyParagraphs = bullets.length > 0
1779
+ ? bullets.map((bullet) => para(bullet, { size: 2000, color: p.fg, bullet: true, font: theme.fonts.body, spaceAfter: 600 }))
1780
+ : [para(subtitle || '', { size: 2000, color: p.fg, font: theme.fonts.body })]
1781
+ shapes.push(textShapeXml(idBase + 3, 'Body', { x: 1050000, y: 1850000, w: 10100000, h: 4500000 }, bodyParagraphs))
1782
+ }
1783
+
1784
+ shapes.push(textShapeXml(idBase + 9, 'Page number', { x: 10600000, y: 6250000, w: 1200000, h: 400000 }, [
1785
+ para(footer, { size: 1000, color: p.muted, align: 'r', font: theme.fonts.body }),
1786
+ ]))
1787
+
1788
+ return shapes.join('')
1789
+ }
1790
+
1791
+ /**
1792
+ * 原生逐条点击显现动画(PowerPoint「出现,按段落」的标准时序树):
1793
+ * bldP 把正文文本框标记为按段落构建,主序列里每条要点一个点击节点。
1794
+ */
1795
+ function bulletTimingXml(spid, clicks) {
1796
+ let id = 2
1797
+ const nextId = () => { id += 1; return String(id) }
1798
+ const clickPars = []
1799
+ for (let i = 0; i < clicks; i += 1) {
1800
+ clickPars.push(
1801
+ '<p:par><p:cTn id="' + nextId() + '" fill="hold"><p:stCondLst><p:cond delay="indefinite"/></p:stCondLst><p:childTnLst>' +
1802
+ '<p:par><p:cTn id="' + nextId() + '" presetID="1" presetClass="entr" presetSubtype="0" fill="hold" grpId="0" nodeType="clickEffect">' +
1803
+ '<p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst>' +
1804
+ '<p:set><p:cBhvr><p:cTn id="' + nextId() + '" dur="1" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn>' +
1805
+ '<p:tgtEl><p:spTgt spid="' + spid + '"/></p:tgtEl>' +
1806
+ '<p:attrNameLst><p:attrName>style.visibility</p:attrName></p:attrNameLst></p:cBhvr>' +
1807
+ '<p:to><p:strVal val="visible"/></p:to></p:set>' +
1808
+ '</p:childTnLst></p:cTn></p:par>' +
1809
+ '</p:childTnLst></p:cTn></p:par>',
1810
+ )
1811
+ }
1812
+ return '<p:timing><p:tnLst><p:par>' +
1813
+ '<p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot"><p:childTnLst>' +
1814
+ '<p:seq concurrent="1" nextAc="seek"><p:cTn id="2" dur="indefinite" nodeType="mainSeq"><p:childTnLst>' +
1815
+ clickPars.join('') +
1816
+ '</p:childTnLst></p:cTn>' +
1817
+ '<p:prevCondLst><p:cond evt="onPrev" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:prevCondLst>' +
1818
+ '<p:nextCondLst><p:cond evt="onNext" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:nextCondLst>' +
1819
+ '</p:seq></p:childTnLst></p:cTn></p:par></p:tnLst>' +
1820
+ '<p:bldLst><p:bldP spid="' + spid + '" grpId="0"/></p:bldLst></p:timing>'
1821
+ }
1822
+
1823
+ function slideXml(slide, index, total, theme, langId, motion) {
1824
+ const p = theme.palette
1825
+ let motionXml = ''
1826
+ if (motion) {
1827
+ motionXml = '<p:transition spd="med"><p:fade/></p:transition>'
1828
+ const bullets = Array.isArray(slide.bullets) ? slide.bullets : []
1829
+ if (slide.layout === 'bullets' && bullets.length >= 2) {
1830
+ motionXml += bulletTimingXml((index + 1) * 10 + 3, bullets.length)
1831
+ }
1832
+ }
1833
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1834
+ '<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1835
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1836
+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1837
+ '<p:cSld><p:bg><p:bgPr><a:solidFill><a:srgbClr val="' + hex(p.bg) + '"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>' +
1838
+ '<p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1839
+ '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1840
+ slideShapeList(slide, index, total, theme, langId) +
1841
+ '</p:spTree></p:cSld>' +
1842
+ '<p:clrMapOvr><a:overrideClrMapping bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/></p:clrMapOvr>' +
1843
+ motionXml +
1844
+ '</p:sld>'
1845
+ }
1846
+
1847
+ function slideRelXml(hasNotes, slideIndex) {
1848
+ const notesRel = hasNotes
1849
+ ? '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/notesSlide' + slideIndex + '.xml"/>'
1850
+ : ''
1851
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1852
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1853
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>' +
1854
+ notesRel +
1855
+ '</Relationships>'
1856
+ }
1857
+
1858
+ function presentationXml(slideCount, hasNotesMaster) {
1859
+ const slideIds = Array.from({ length: slideCount }, (_, i) =>
1860
+ '<p:sldId id="' + (256 + i) + '" r:id="rId' + (i + 2) + '"/>').join('')
1861
+ const notesMasterId = hasNotesMaster
1862
+ ? '<p:notesMasterIdLst><p:notesMasterId id="2147483649" r:id="rId' + (slideCount + 2) + '"/></p:notesMasterIdLst>'
1863
+ : ''
1864
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1865
+ '<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1866
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1867
+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1868
+ '<p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst>' +
1869
+ '<p:sldIdLst>' + slideIds + '</p:sldIdLst>' +
1870
+ notesMasterId +
1871
+ '<p:sldSz cx="' + EMU_W + '" cy="' + EMU_H + '" type="screen16x9"/>' +
1872
+ '<p:notesSz cx="6858000" cy="9144000"/>' +
1873
+ '</p:presentation>'
1874
+ }
1875
+
1876
+ function presentationRelXml(slideCount, hasNotesMaster) {
1877
+ const slideRels = Array.from({ length: slideCount }, (_, i) =>
1878
+ '<Relationship Id="rId' + (i + 2) + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide' + (i + 1) + '.xml"/>').join('')
1879
+ const notesMasterRel = hasNotesMaster
1880
+ ? '<Relationship Id="rId' + (slideCount + 2) + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target="notesMasters/notesMaster1.xml"/>'
1881
+ : ''
1882
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1883
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1884
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/>' +
1885
+ slideRels +
1886
+ notesMasterRel +
1887
+ '</Relationships>'
1888
+ }
1889
+
1890
+ function notesMasterXml() {
1891
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1892
+ '<p:notesMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1893
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1894
+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1895
+ '<p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1896
+ '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1897
+ '</p:spTree></p:cSld>' +
1898
+ '<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>' +
1899
+ '<p:notesStyle><a:lvl1pPr><a:defRPr sz="1200"/></a:lvl1pPr></p:notesStyle>' +
1900
+ '</p:notesMaster>'
1901
+ }
1902
+
1903
+ function notesMasterRelXml() {
1904
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1905
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1906
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>' +
1907
+ '</Relationships>'
1908
+ }
1909
+
1910
+ function notesSlideXml(notes, langId) {
1911
+ const lang = langId || 'zh-CN'
1912
+ const paragraphs = String(notes ?? '').split('\n')
1913
+ .filter((line) => line.trim() !== '')
1914
+ .map((line) => '<a:p><a:r><a:rPr lang="' + lang + '" sz="1200" dirty="0"/><a:t>' + escapeXml(line) + '</a:t></a:r></a:p>')
1915
+ .join('')
1916
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1917
+ '<p:notes xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1918
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1919
+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1920
+ '<p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1921
+ '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1922
+ '<p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image Placeholder 1"/><p:cNvSpPr/><p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>' +
1923
+ '<p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes Placeholder 2"/><p:cNvSpPr/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/>' +
1924
+ '<p:txBody><a:bodyPr/><a:lstStyle/>' + paragraphs + '</p:txBody></p:sp>' +
1925
+ '</p:spTree></p:cSld>' +
1926
+ '<p:clrMapOvr><a:overrideClrMapping bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/></p:clrMapOvr>' +
1927
+ '</p:notes>'
1928
+ }
1929
+
1930
+ function notesSlideRelXml(slideIndex) {
1931
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1932
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1933
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="../slides/slide' + slideIndex + '.xml"/>' +
1934
+ '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target="../notesMasters/notesMaster1.xml"/>' +
1935
+ '</Relationships>'
1936
+ }
1937
+
1938
+ function slideMasterXml(theme) {
1939
+ const p = theme.palette
1940
+ const levels = Array.from({ length: 9 }, (_, i) => {
1941
+ const sz = Math.max(1100, 2000 - i * 100)
1942
+ return '<a:lvl' + (i + 1) + 'pPr marL="' + (342900 + i * 342900) + '" indent="' + (-342900 - i * 0) + '">' +
1943
+ '<a:defRPr sz="' + sz + '"><a:solidFill><a:srgbClr val="' + hex(p.fg) + '"/></a:solidFill><a:latin typeface="' + escapeXml(pptxFontName(theme.fonts.body)) + '"/></a:defRPr></a:lvl' + (i + 1) + 'pPr>'
1944
+ }).join('')
1945
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1946
+ '<p:sldMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1947
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1948
+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">' +
1949
+ '<p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1950
+ '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1951
+ '</p:spTree></p:cSld>' +
1952
+ '<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>' +
1953
+ '<p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst>' +
1954
+ '<p:txStyles><p:titleStyle>' + levels + '</p:titleStyle><p:bodyStyle>' + levels + '</p:bodyStyle><p:otherStyle>' + levels + '</p:otherStyle></p:txStyles>' +
1955
+ '</p:sldMaster>'
1956
+ }
1957
+
1958
+ function slideMasterRelXml() {
1959
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1960
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1961
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>' +
1962
+ '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>' +
1963
+ '</Relationships>'
1964
+ }
1965
+
1966
+ function slideLayoutXml(theme) {
1967
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1968
+ '<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
1969
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
1970
+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="blank" preserve="1">' +
1971
+ '<p:cSld name="Blank"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
1972
+ '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>' +
1973
+ '</p:spTree></p:cSld>' +
1974
+ '<p:clrMapOvr><a:overrideClrMapping bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/></p:clrMapOvr>' +
1975
+ '</p:sldLayout>'
1976
+ }
1977
+
1978
+ function slideLayoutRelXml() {
1979
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1980
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
1981
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="../slideMasters/slideMaster1.xml"/>' +
1982
+ '</Relationships>'
1983
+ }
1984
+
1985
+ function themeXml(theme) {
1986
+ const p = theme.palette
1987
+ const color = (name, value) => '<a:' + name + '><a:srgbClr val="' + hex(value) + '"/></a:' + name + '>'
1988
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
1989
+ '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="dsh-ppt ' + escapeXml(theme.name.en) + '">' +
1990
+ '<a:themeElements>' +
1991
+ '<a:clrScheme name="dsh-ppt">' +
1992
+ color('dk1', p.fg) + color('lt1', p.bg) + color('dk2', p.muted) + color('lt2', p.panel) +
1993
+ color('accent1', p.accent) + color('accent2', p.accent2) + color('accent3', p.fg) +
1994
+ color('accent4', p.muted) + color('accent5', p.accent) + color('accent6', p.accent2) +
1995
+ color('hlink', p.accent) + color('folHlink', p.accent2) +
1996
+ '</a:clrScheme>' +
1997
+ '<a:fontScheme name="dsh-ppt">' +
1998
+ '<a:majorFont><a:latin typeface="' + escapeXml(pptxFontName(theme.fonts.heading)) + '"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont>' +
1999
+ '<a:minorFont><a:latin typeface="' + escapeXml(pptxFontName(theme.fonts.body)) + '"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont>' +
2000
+ '</a:fontScheme>' +
2001
+ '<a:fmtScheme name="dsh-ppt">' +
2002
+ '<a:fillStyleLst>' +
2003
+ '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
2004
+ '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
2005
+ '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>' +
2006
+ '</a:fillStyleLst>' +
2007
+ '<a:lnStyleLst><a:ln w="6350" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="12700" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="19050" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln></a:lnStyleLst>' +
2008
+ '<a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>' +
2009
+ '<a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:bgFillStyleLst>' +
2010
+ '</a:fmtScheme>' +
2011
+ '</a:themeElements>' +
2012
+ '<a:objectDefaults/><a:extraClrSchemeLst/>' +
2013
+ '</a:theme>'
2014
+ }
2015
+
2016
+ function contentTypesXml(slideCount, noteIndexes) {
2017
+ const overrides = Array.from({ length: slideCount }, (_, i) =>
2018
+ '<Override PartName="/ppt/slides/slide' + (i + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>').join('')
2019
+ const notesOverrides = noteIndexes.map((index) =>
2020
+ '<Override PartName="/ppt/notesSlides/notesSlide' + (index + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"/>').join('')
2021
+ const notesMasterOverride = noteIndexes.length > 0
2022
+ ? '<Override PartName="/ppt/notesMasters/notesMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"/>'
2023
+ : ''
2024
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
2025
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
2026
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
2027
+ '<Default Extension="xml" ContentType="application/xml"/>' +
2028
+ '<Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/>' +
2029
+ '<Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/>' +
2030
+ '<Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/>' +
2031
+ '<Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>' +
2032
+ '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>' +
2033
+ '<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>' +
2034
+ notesMasterOverride +
2035
+ overrides +
2036
+ notesOverrides +
2037
+ '</Types>'
2038
+ }
2039
+
2040
+ function rootRelXml() {
2041
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
2042
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
2043
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/>' +
2044
+ '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>' +
2045
+ '<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>' +
2046
+ '</Relationships>'
2047
+ }
2048
+
2049
+ function coreXml(title) {
2050
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
2051
+ '<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ' +
2052
+ 'xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" ' +
2053
+ 'xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
2054
+ '<dc:title>' + escapeXml(title) + '</dc:title><dc:creator>dsh-ppt</dc:creator>' +
2055
+ '<cp:lastModifiedBy>dsh-ppt</cp:lastModifiedBy>' +
2056
+ '</cp:coreProperties>'
2057
+ }
2058
+
2059
+ function appXml(slideCount, notesCount) {
2060
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
2061
+ '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" ' +
2062
+ 'xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">' +
2063
+ '<Application>dsh-ppt</Application><PresentationFormat>Widescreen</PresentationFormat>' +
2064
+ '<Slides>' + slideCount + '</Slides><Notes>' + notesCount + '</Notes><HiddenSlides>0</HiddenSlides>' +
2065
+ '</Properties>'
2066
+ }
2067
+
2068
+ function buildZip(entries) {
2069
+ const chunks = []
2070
+ const central = []
2071
+ let offset = 0
2072
+
2073
+ for (const entry of entries) {
2074
+ const entryOffset = offset
2075
+ const name = Buffer.from(entry.name, 'utf8')
2076
+ const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(String(entry.data), 'utf8')
2077
+ const crc = crc32(data)
2078
+ const compressed = deflateRawSync(data)
2079
+ const method = 8
2080
+ const nameLength = name.length
2081
+ const localHeader = Buffer.alloc(30)
2082
+ localHeader.writeUInt32LE(0x04034b50, 0)
2083
+ localHeader.writeUInt16LE(20, 4)
2084
+ localHeader.writeUInt16LE(0x0800, 6) // UTF-8 文件名
2085
+ localHeader.writeUInt16LE(method, 8)
2086
+ localHeader.writeUInt16LE(0, 10) // DOS time
2087
+ localHeader.writeUInt16LE(0x21, 12) // DOS date 1980-01-01
2088
+ localHeader.writeUInt32LE(crc, 14)
2089
+ localHeader.writeUInt32LE(compressed.length, 18)
2090
+ localHeader.writeUInt32LE(data.length, 22)
2091
+ localHeader.writeUInt16LE(nameLength, 26)
2092
+ localHeader.writeUInt16LE(0, 28)
2093
+
2094
+ chunks.push(localHeader, name, compressed)
2095
+ offset += 30 + nameLength + compressed.length
2096
+
2097
+ const centralHeader = Buffer.alloc(46)
2098
+ centralHeader.writeUInt32LE(0x02014b50, 0)
2099
+ centralHeader.writeUInt16LE(20, 4)
2100
+ centralHeader.writeUInt16LE(20, 6)
2101
+ centralHeader.writeUInt16LE(0x0800, 8)
2102
+ centralHeader.writeUInt16LE(method, 10)
2103
+ centralHeader.writeUInt16LE(0, 12)
2104
+ centralHeader.writeUInt16LE(0x21, 14)
2105
+ centralHeader.writeUInt32LE(crc, 16)
2106
+ centralHeader.writeUInt32LE(compressed.length, 20)
2107
+ centralHeader.writeUInt32LE(data.length, 24)
2108
+ centralHeader.writeUInt16LE(nameLength, 28)
2109
+ centralHeader.writeUInt16LE(0, 30)
2110
+ centralHeader.writeUInt16LE(0, 32)
2111
+ centralHeader.writeUInt16LE(0, 34)
2112
+ centralHeader.writeUInt16LE(0, 36)
2113
+ centralHeader.writeUInt32LE(0, 38)
2114
+ centralHeader.writeUInt32LE(entryOffset, 42)
2115
+ central.push(centralHeader, name)
2116
+ }
2117
+
2118
+ const centralOffset = offset
2119
+ const centralSize = central.reduce((sum, part) => sum + part.length, 0)
2120
+ const end = Buffer.alloc(22)
2121
+ end.writeUInt32LE(0x06054b50, 0)
2122
+ end.writeUInt16LE(0, 4)
2123
+ end.writeUInt16LE(0, 6)
2124
+ end.writeUInt16LE(entries.length, 8)
2125
+ end.writeUInt16LE(entries.length, 10)
2126
+ end.writeUInt32LE(centralSize, 12)
2127
+ end.writeUInt32LE(centralOffset, 16)
2128
+ end.writeUInt16LE(0, 20)
2129
+
2130
+ chunks.push(...central, end)
2131
+ return Buffer.concat(chunks)
2132
+ }
2133
+
2134
+ let CRC_TABLE = null
2135
+ function crc32(buffer) {
2136
+ if (CRC_TABLE === null) {
2137
+ CRC_TABLE = new Int32Array(256)
2138
+ for (let n = 0; n < 256; n += 1) {
2139
+ let c = n
2140
+ for (let k = 0; k < 8; k += 1) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1)
2141
+ CRC_TABLE[n] = c
2142
+ }
2143
+ }
2144
+ let crc = 0xffffffff
2145
+ for (let i = 0; i < buffer.length; i += 1) {
2146
+ crc = CRC_TABLE[(crc ^ buffer[i]) & 0xff] ^ (crc >>> 8)
2147
+ }
2148
+ return (crc ^ 0xffffffff) >>> 0
2149
+ }
2150
+
2151
+ export function buildPptx(manifest, themeInput, languageInput) {
2152
+ const theme = themeInput?.id ? themeInput : resolveTheme(themeInput)
2153
+ const language = languageInput?.id ? languageInput : resolveLanguage(languageInput)
2154
+ const motion = manifest.motion !== false
2155
+ const slides = manifest.slides
2156
+ const noteIndexes = []
2157
+ slides.forEach((slide, index) => {
2158
+ if (typeof slide.notes === 'string' && slide.notes.trim() !== '') noteIndexes.push(index)
2159
+ })
2160
+ const hasNotesMaster = noteIndexes.length > 0
2161
+ const entries = [
2162
+ { name: '[Content_Types].xml', data: contentTypesXml(slides.length, noteIndexes) },
2163
+ { name: '_rels/.rels', data: rootRelXml() },
2164
+ { name: 'docProps/app.xml', data: appXml(slides.length, noteIndexes.length) },
2165
+ { name: 'docProps/core.xml', data: coreXml(manifest.title) },
2166
+ { name: 'ppt/presentation.xml', data: presentationXml(slides.length, hasNotesMaster) },
2167
+ { name: 'ppt/_rels/presentation.xml.rels', data: presentationRelXml(slides.length, hasNotesMaster) },
2168
+ { name: 'ppt/slideMasters/slideMaster1.xml', data: slideMasterXml(theme) },
2169
+ { name: 'ppt/slideMasters/_rels/slideMaster1.xml.rels', data: slideMasterRelXml() },
2170
+ { name: 'ppt/slideLayouts/slideLayout1.xml', data: slideLayoutXml(theme) },
2171
+ { name: 'ppt/slideLayouts/_rels/slideLayout1.xml.rels', data: slideLayoutRelXml() },
2172
+ { name: 'ppt/theme/theme1.xml', data: themeXml(theme) },
2173
+ ]
2174
+ if (hasNotesMaster) {
2175
+ entries.push({ name: 'ppt/notesMasters/notesMaster1.xml', data: notesMasterXml() })
2176
+ entries.push({ name: 'ppt/notesMasters/_rels/notesMaster1.xml.rels', data: notesMasterRelXml() })
2177
+ }
2178
+ slides.forEach((slide, index) => {
2179
+ const hasNotes = noteIndexes.includes(index)
2180
+ entries.push({ name: 'ppt/slides/slide' + (index + 1) + '.xml', data: slideXml(slide, index, slides.length, theme, language.attr, motion) })
2181
+ entries.push({ name: 'ppt/slides/_rels/slide' + (index + 1) + '.xml.rels', data: slideRelXml(hasNotes, index + 1) })
2182
+ if (hasNotes) {
2183
+ entries.push({ name: 'ppt/notesSlides/notesSlide' + (index + 1) + '.xml', data: notesSlideXml(slide.notes, language.attr) })
2184
+ entries.push({ name: 'ppt/notesSlides/_rels/notesSlide' + (index + 1) + '.xml.rels', data: notesSlideRelXml(index + 1) })
2185
+ }
2186
+ })
2187
+ return buildZip(entries)
2188
+ }