jvs-ppt-ui 0.0.30 → 0.0.32

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.
@@ -0,0 +1,1226 @@
1
+ import type { Slide, SlideElement } from '../composables/useSlides'
2
+ import type { StyleRecipe } from '../composables/presetThemes'
3
+ import type { DeckData } from '../types'
4
+ import { generateMonoPalette } from './palette'
5
+
6
+ const LOGICAL_WIDTH = 1280
7
+ const LOGICAL_HEIGHT = 720
8
+ // Pitch 1.0 font-size unit corresponds to 40px on a 1920x1080 canvas -> ~26px on 1280x720
9
+ const PITCH_BASE_FONT_PX = 26
10
+
11
+ /**
12
+ * Cognitect Transit-JSON 解码器
13
+ * 将 Pitch.com 的 ["^ ", "~:key", val, "^8", ...] 还原为标准 JS 对象
14
+ */
15
+ export function decodeTransitJson(root: any): any {
16
+ const parsedRoot = typeof root === 'string' ? JSON.parse(root) : root
17
+ // 如果已经是解码后的普通对象/数组且不含 Transit 标记,直接返回
18
+ if (parsedRoot && typeof parsedRoot === 'object') {
19
+ if (!Array.isArray(parsedRoot) && (parsedRoot.data || parsedRoot.slides)) {
20
+ return parsedRoot
21
+ }
22
+ if (
23
+ Array.isArray(parsedRoot) &&
24
+ parsedRoot.length > 0 &&
25
+ typeof parsedRoot[0] === 'object' &&
26
+ !Array.isArray(parsedRoot[0]) &&
27
+ (parsedRoot[0]['entity-type'] === 'slide' || Array.isArray(parsedRoot[0].children))
28
+ ) {
29
+ return parsedRoot
30
+ }
31
+ }
32
+
33
+ const cache: string[] = []
34
+ let cacheIdx = 0
35
+
36
+ function isCacheable(str: string, asMapKey: boolean): boolean {
37
+ if (typeof str !== 'string' || str.length <= 3) return false
38
+ if (asMapKey) return true
39
+ const c0 = str[0]
40
+ const c1 = str[1]
41
+ return c0 === '~' && (c1 === ':' || c1 === '$' || c1 === '#')
42
+ }
43
+
44
+ function codeToIndex(str: string): number {
45
+ if (str.length === 2) return str.charCodeAt(1) - 48
46
+ if (str.length === 3) return (str.charCodeAt(1) - 48) * 44 + (str.charCodeAt(2) - 48)
47
+ return -1
48
+ }
49
+
50
+ function parseScalar(str: string): any {
51
+ if (typeof str !== 'string') return str
52
+ if (str.startsWith('~:')) return str.slice(2)
53
+ if (str.startsWith('~$')) return str.slice(2)
54
+ if (str.startsWith('~u')) return str.slice(2)
55
+ if (str.startsWith('~m')) {
56
+ const n = Number(str.slice(2))
57
+ return isNaN(n) ? str.slice(2) : n
58
+ }
59
+ if (str.startsWith('~f') || str.startsWith('~i') || str.startsWith('~n')) {
60
+ const n = Number(str.slice(2))
61
+ return isNaN(n) ? str.slice(2) : n
62
+ }
63
+ if (str.startsWith('~~')) return str.slice(1)
64
+ if (str.startsWith('~^')) return str.slice(1)
65
+ if (str.startsWith('~`')) return str.slice(1)
66
+ return str
67
+ }
68
+
69
+ function decodeStr(str: string, asMapKey: boolean): any {
70
+ if (typeof str !== 'string') return str
71
+ if (str[0] === '^' && str !== '^ ') {
72
+ const ci = codeToIndex(str)
73
+ const cached = ci >= 0 ? cache[ci] : undefined
74
+ return parseScalar(cached !== undefined ? cached : str)
75
+ }
76
+ if (isCacheable(str, asMapKey)) {
77
+ cache[cacheIdx] = str
78
+ cacheIdx = (cacheIdx + 1) % 1936
79
+ }
80
+ return parseScalar(str)
81
+ }
82
+
83
+ function walk(node: any, asMapKey = false): any {
84
+ if (typeof node === 'string') {
85
+ return decodeStr(node, asMapKey)
86
+ }
87
+ if (Array.isArray(node)) {
88
+ if (node.length === 0) return []
89
+ if (node[0] === '^ ') {
90
+ const obj: Record<string, any> = {}
91
+ for (let i = 1; i < node.length; i += 2) {
92
+ const k = walk(node[i], true)
93
+ const v = walk(node[i + 1], false)
94
+ obj[String(k)] = v
95
+ }
96
+ return obj
97
+ }
98
+ const firstRaw =
99
+ typeof node[0] === 'string' && node[0][0] === '^' && node[0] !== '^ '
100
+ ? cache[codeToIndex(node[0])] || node[0]
101
+ : node[0]
102
+ if (typeof firstRaw === 'string' && firstRaw.startsWith('~#')) {
103
+ // 消费 tag 保证缓存索引同步
104
+ walk(node[0], false)
105
+ return walk(node[1], false)
106
+ }
107
+ return node.map(item => walk(item, false))
108
+ }
109
+ if (node && typeof node === 'object') {
110
+ const obj: Record<string, any> = {}
111
+ for (const [k, v] of Object.entries(node)) {
112
+ const dk = walk(k, true)
113
+ obj[String(dk)] = walk(v, false)
114
+ }
115
+ return obj
116
+ }
117
+ return node
118
+ }
119
+
120
+ return walk(parsedRoot, false)
121
+ }
122
+
123
+ export const PITCH_LAYOUT_CATEGORIES: { key: string; label: string }[] = [
124
+ { key: 'all', label: '全部版式 (All)' },
125
+ { key: 'simple-slides', label: '基础图文 (Simple slides)' },
126
+ { key: 'charts-and-data', label: '图表与数据 (Charts and data)' },
127
+ { key: 'grids', label: '网格布局 (Grids)' },
128
+ { key: 'timelines-and-project-plans', label: '时间轴与计划 (Timelines)' },
129
+ { key: 'quotes-and-testimonials', label: '金句与证言 (Quotes)' },
130
+ { key: 'people-and-teams', label: '人物与团队 (People & teams)' },
131
+ { key: 'agenda', label: '目录与议程 (Agenda)' },
132
+ { key: 'pricing', label: '价格方案 (Pricing)' },
133
+ { key: 'device-frames', label: '设备样机 (Device frames)' }
134
+ ]
135
+
136
+ const CATEGORY_LABEL_MAP: Record<string, string> = {
137
+ 'simple-slides': '基础版式',
138
+ 'charts-and-data': '图表与数据',
139
+ 'grids': '网格布局',
140
+ 'timelines-and-project-plans': '时间轴与计划',
141
+ 'quotes-and-testimonials': '金句与证言',
142
+ 'people-and-teams': '人物与团队',
143
+ 'agenda': '目录与议程',
144
+ 'pricing': '价格方案',
145
+ 'device-frames': '设备样机'
146
+ }
147
+
148
+ /**
149
+ * 判断输入对象是否为 Pitch Transit-JSON 或 Pitch 模板/版式库结构
150
+ */
151
+ export function isPitchTemplateData(data: any): boolean {
152
+ if (!data) return false
153
+ if (Array.isArray(data)) {
154
+ if (data[0] === '^ ') return true
155
+ // key-layouts.transit 顶层是 Transit Map 的数组: [["^ ", "~:children", ...], ...]
156
+ if (Array.isArray(data[0]) && data[0][0] === '^ ') return true
157
+ // 已解码的 Slide 数组
158
+ if (typeof data[0] === 'object' && data[0] && (data[0]['entity-type'] === 'slide' || Array.isArray(data[0].children))) {
159
+ return true
160
+ }
161
+ }
162
+ if (typeof data === 'object' && data.data && Array.isArray(data.data.slides)) {
163
+ return data.data.slides.some((s: any) => s && (s['entity-type'] === 'slide' || Array.isArray(s.children)))
164
+ }
165
+ return false
166
+ }
167
+
168
+ /**
169
+ * 将用户输入的 Pitch URL / UUID 标准化为可拉取的接口地址
170
+ */
171
+ export function normalizePitchTemplateUrl(inputUrl: string): string {
172
+ const trimmed = (inputUrl || '').trim()
173
+ if (!trimmed) return ''
174
+ // 纯 UUID
175
+ const uuidRegex = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
176
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {
177
+ return `https://cdn.backend.services.pitch.com/templates/${trimmed.toLowerCase()}`
178
+ }
179
+ // 已经是 cdn.backend.services.pitch.com 地址,或者是 .transit / .json / /static/ 静态资源地址(如 key-layouts.transit)
180
+ if (
181
+ trimmed.includes('cdn.backend.services.pitch.com/templates/') ||
182
+ trimmed.includes('/static/') ||
183
+ /\.(transit|json)(\?.*)?$/i.test(trimmed)
184
+ ) {
185
+ return trimmed
186
+ }
187
+ // 如果包含 UUID(如 pitch.com/templates/xxx-2017ca60-c167-4153-893b-c8bd5b63c914)
188
+ const match = trimmed.match(uuidRegex)
189
+ if (match && match[1]) {
190
+ return `https://cdn.backend.services.pitch.com/templates/${match[1].toLowerCase()}`
191
+ }
192
+ return trimmed
193
+ }
194
+
195
+ function clampByte(n: any, fallback = 0): number {
196
+ const v = Number(n)
197
+ if (isNaN(v)) return fallback
198
+ return Math.max(0, Math.min(255, Math.round(v)))
199
+ }
200
+
201
+ export function rgbaObjToHex(colorObj: any, fallback = '#000000'): string {
202
+ if (!colorObj) return fallback
203
+ if (typeof colorObj === 'string') return colorObj
204
+ if (colorObj.color && typeof colorObj.color === 'object') {
205
+ return rgbaObjToHex(colorObj.color, fallback)
206
+ }
207
+ if (colorObj.r === undefined || colorObj.g === undefined || colorObj.b === undefined) {
208
+ return fallback
209
+ }
210
+ const r = clampByte(colorObj.r).toString(16).padStart(2, '0')
211
+ const g = clampByte(colorObj.g).toString(16).padStart(2, '0')
212
+ const b = clampByte(colorObj.b).toString(16).padStart(2, '0')
213
+ return `#${r}${g}${b}`.toUpperCase()
214
+ }
215
+
216
+ export function rgbaObjToCss(colorObj: any, fallback = ''): string {
217
+ if (!colorObj) return fallback
218
+ if (typeof colorObj === 'string') return colorObj
219
+ if (colorObj.color && typeof colorObj.color === 'object') {
220
+ return rgbaObjToCss(colorObj.color, fallback)
221
+ }
222
+ if (colorObj.r === undefined || colorObj.g === undefined || colorObj.b === undefined) {
223
+ return fallback
224
+ }
225
+ const r = clampByte(colorObj.r)
226
+ const g = clampByte(colorObj.g)
227
+ const b = clampByte(colorObj.b)
228
+ const a = colorObj.a !== undefined ? Number(colorObj.a) : 1
229
+ if (a <= 0) return 'transparent'
230
+ if (a < 0.98) {
231
+ return `rgba(${r}, ${g}, ${b}, ${Math.round(a * 100) / 100})`
232
+ }
233
+ return rgbaObjToHex(colorObj, fallback)
234
+ }
235
+
236
+ function hexToRgba(hex: string, alpha: number): string {
237
+ const clean = (hex || '#000000').replace(/^#/, '')
238
+ if (clean.length !== 6) return `rgba(0, 0, 0, ${alpha})`
239
+ const r = parseInt(clean.slice(0, 2), 16) || 0
240
+ const g = parseInt(clean.slice(2, 4), 16) || 0
241
+ const b = parseInt(clean.slice(4, 6), 16) || 0
242
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`
243
+ }
244
+
245
+ /**
246
+ * 将 Pitch 的内嵌 theme 转换为 jvs-ppt-ui 的 StyleRecipe
247
+ */
248
+ export function convertPitchThemeToRecipe(pitchTheme: any, index = 0): StyleRecipe {
249
+ const rawId = pitchTheme?.id || `custom-${index + 1}`
250
+ const id = rawId.startsWith('pitch-') ? rawId : `pitch-${rawId}`
251
+ const name = pitchTheme?.name || `Pitch 主题 ${index + 1}`
252
+
253
+ const bgColor = rgbaObjToHex(pitchTheme?.['background-color'], '#FFFFFF')
254
+ const baseTextColor = rgbaObjToHex(pitchTheme?.['text-color'], '#1E293B')
255
+ const accentColor = rgbaObjToHex(pitchTheme?.['accent-color'], baseTextColor)
256
+ const bulletColor = rgbaObjToHex(pitchTheme?.bullets?.color, accentColor)
257
+ const linkColor = rgbaObjToHex(pitchTheme?.link?.color || pitchTheme?.link, '#2563EB')
258
+
259
+ const textScale = Number(pitchTheme?.['text-size']) || 1
260
+ const baseUnit = PITCH_BASE_FONT_PX * textScale
261
+ const blocks = pitchTheme?.blocks || {}
262
+
263
+ const resolveTextConfig = (
264
+ blockKey: string,
265
+ defaultRelSize: number,
266
+ defaultWeight: string,
267
+ defaultLineHeight: number
268
+ ) => {
269
+ const b = blocks[blockKey] || {}
270
+ const relSize = Number(b['font-size']) || defaultRelSize
271
+ const fontSize = Math.max(10, Math.round(relSize * baseUnit))
272
+ const color = rgbaObjToHex(b.color || pitchTheme?.['text-color'], baseTextColor)
273
+ const fwRaw = b['font-weight']
274
+ const fontWeight = fwRaw
275
+ ? (Number(fwRaw) >= 600 || fwRaw === 'bold' ? 'bold' : String(fwRaw))
276
+ : defaultWeight
277
+ const lineHeight = Number(b['line-height']) || defaultLineHeight
278
+ const relLetterSpacing = Number(b['letter-spacing']) || 0
279
+ const letterSpacing = Math.round(relLetterSpacing * fontSize * 10) / 10
280
+ const paragraphSpacing = Number(b['paragraph-spacing'])
281
+ ? Math.round(Number(b['paragraph-spacing']) * fontSize * 0.45)
282
+ : 0
283
+ const uppercase = b['text-transform'] === 'uppercase'
284
+ return {
285
+ color,
286
+ fontSize,
287
+ fontWeight,
288
+ letterSpacing,
289
+ lineHeight,
290
+ paragraphSpacing,
291
+ uppercase
292
+ }
293
+ }
294
+
295
+ const titleCfg = resolveTextConfig('headline-big', 4.15, 'bold', 1.05)
296
+ const headlineCfg = resolveTextConfig('headline-medium', 2.1, 'bold', 1.1)
297
+ const subheadlineCfg = resolveTextConfig('headline-small', 1.15, 'normal', 1.25)
298
+ const normalTextCfg = resolveTextConfig('paragraph', 0.8, 'normal', 1.35)
299
+ const smallTextCfg = resolveTextConfig('paragraph-small', 0.5, 'bold', 1.25)
300
+
301
+ const tableBlock = blocks.table || {}
302
+ const tableHeaderBg = rgbaObjToHex(
303
+ tableBlock['header-background-color'] || pitchTheme?.['accent-color'],
304
+ accentColor
305
+ )
306
+ const tableHeaderText = rgbaObjToHex(
307
+ tableBlock['header-text-color'] || pitchTheme?.['background-color'],
308
+ '#FFFFFF'
309
+ )
310
+ const tableBorder = rgbaObjToHex(tableBlock['border-color'], '#CBD5E1')
311
+ const tableAltRowBg = tableBlock['alt-row-background-color']
312
+ ? rgbaObjToCss(tableBlock['alt-row-background-color'], hexToRgba(accentColor, 0.08))
313
+ : hexToRgba(accentColor, 0.08)
314
+ const tableText = rgbaObjToHex(tableBlock.color || blocks.paragraph?.color, normalTextCfg.color)
315
+
316
+ const shapeBlock = blocks.shape || {}
317
+ const shapeFill = rgbaObjToHex(shapeBlock.color, accentColor)
318
+ const shapeStroke = rgbaObjToHex(shapeBlock['stroke-color'], shapeFill)
319
+ const shapeText = rgbaObjToHex(shapeBlock['text-color'], '#FFFFFF')
320
+
321
+ const chartBlock = blocks.chart || {}
322
+ const chartBaseColor = rgbaObjToHex(chartBlock.color, shapeFill || accentColor)
323
+ const chartLabelColor = rgbaObjToHex(chartBlock['text-color'], normalTextCfg.color)
324
+ const chartGridColor = rgbaObjToHex(chartBlock['axis-color'], tableBorder)
325
+ const chartPalette = generateMonoPalette(chartBaseColor, 8)
326
+
327
+ const styleColors = Array.from(
328
+ new Set([
329
+ titleCfg.color,
330
+ accentColor,
331
+ shapeFill,
332
+ bgColor,
333
+ tableBorder,
334
+ linkColor,
335
+ bulletColor,
336
+ chartBaseColor
337
+ ])
338
+ )
339
+ while (styleColors.length < 6) {
340
+ styleColors.push(chartPalette[styleColors.length % chartPalette.length] || '#64748B')
341
+ }
342
+
343
+ return {
344
+ id,
345
+ name,
346
+ styleColors: styleColors.slice(0, 8),
347
+ styleFonts: {
348
+ titleFont: 'SourceHanSansCN',
349
+ bodyFont: 'SourceHanSansCN'
350
+ },
351
+ backgroundColor: bgColor,
352
+ bulletPointsColor: bulletColor,
353
+ linkColor,
354
+ linkUnderline: true,
355
+ textStyles: {
356
+ title: titleCfg,
357
+ headline: headlineCfg,
358
+ subheadline: subheadlineCfg,
359
+ normalText: normalTextCfg,
360
+ smallText: smallTextCfg
361
+ },
362
+ table: {
363
+ fontSize: Math.max(12, Math.round((Number(tableBlock['font-size']) || 0.8) * baseUnit)),
364
+ bgColor,
365
+ textColor: tableText,
366
+ headerBg: tableHeaderBg,
367
+ headerTextColor: tableHeaderText,
368
+ alternateRowBg: tableAltRowBg,
369
+ alternateTextColor: tableText,
370
+ borderColor: tableBorder
371
+ },
372
+ chart: {
373
+ fontSize: Math.max(11, Math.round((Number(chartBlock['font-size']) || 0.55) * baseUnit)),
374
+ textColor: chartLabelColor,
375
+ chartColor: chartBaseColor,
376
+ paletteName: `${name} Palette`,
377
+ palette: chartPalette,
378
+ labelColor: chartLabelColor,
379
+ gridColor: chartGridColor
380
+ },
381
+ shape: {
382
+ fillColor: shapeFill,
383
+ borderColor: shapeStroke,
384
+ textColor: shapeText
385
+ }
386
+ }
387
+ }
388
+
389
+ function mapPitchTextType(pitchTextType?: string): 'title' | 'headline' | 'subheadline' | 'normalText' | 'smallText' {
390
+ switch (pitchTextType) {
391
+ case 'headline-big':
392
+ return 'title'
393
+ case 'headline-medium':
394
+ return 'headline'
395
+ case 'headline-small':
396
+ return 'subheadline'
397
+ case 'paragraph-small':
398
+ return 'smallText'
399
+ case 'paragraph':
400
+ default:
401
+ return 'normalText'
402
+ }
403
+ }
404
+
405
+ function formatPitchTextHtml(
406
+ rawHtml: string,
407
+ options: {
408
+ textAlign: string
409
+ color: string
410
+ bulletColor: string
411
+ uppercase: boolean
412
+ paragraphSpacingPx: number
413
+ fontSizePx: number
414
+ }
415
+ ): string {
416
+ if (!rawHtml || typeof rawHtml !== 'string') return '<p style="margin: 0;"><br></p>'
417
+ let html = rawHtml.trim()
418
+
419
+ // 将空的 <p></p> 替换为 <p><br></p>,保证空行在画布和缩略图中不坍塌
420
+ html = html.replace(/<p(\s[^>]*)?>\s*<\/p>/gi, '<p$1><br></p>')
421
+
422
+ const upperCss = options.uppercase ? 'text-transform: uppercase; ' : ''
423
+ const alignCss = options.textAlign ? `text-align: ${options.textAlign}; ` : ''
424
+
425
+ // 处理列表 <ul> / <ol> / <li>
426
+ const hasList = /<(ul|ol)\b/i.test(html)
427
+ if (hasList) {
428
+ const liGap = Math.max(8, options.paragraphSpacingPx || Math.round(options.fontSizePx * 0.45))
429
+ html = html
430
+ .replace(/<ul(\s[^>]*)?>/gi, `<ul style="margin: 0; padding-left: 1.25em; list-style-type: disc; color: ${options.bulletColor}; ${alignCss}">`)
431
+ .replace(/<ol(\s[^>]*)?>/gi, `<ol style="margin: 0; padding-left: 1.25em; list-style-type: decimal; color: ${options.bulletColor}; ${alignCss}">`)
432
+ .replace(/<li(\s[^>]*)?>/gi, `<li style="margin: 0 0 ${liGap}px 0; padding: 0;">`)
433
+ .replace(/<p(\s[^>]*)?>/gi, `<p style="margin: 0; color: ${options.color}; ${upperCss}${alignCss}">`)
434
+ return html
435
+ }
436
+
437
+ // 普通段落:检查是否已经包含空行 <p><br></p> 作为段落间距
438
+ const hasExplicitEmptyLine = /<p[^>]*><br\s*\/?><\/p>/i.test(html)
439
+ const pMarginBottom = !hasExplicitEmptyLine && options.paragraphSpacingPx > 0 ? `${options.paragraphSpacingPx}px` : '0'
440
+
441
+ html = html.replace(/<p(\s+style="([^"]*)")?(\s[^>]*)?>/gi, (_m, _sFull, existingStyle) => {
442
+ const baseStyle = `margin: 0 0 ${pMarginBottom} 0; ${alignCss}${upperCss}`
443
+ if (existingStyle) {
444
+ return `<p style="${baseStyle}${existingStyle}">`
445
+ }
446
+ return `<p style="${baseStyle}">`
447
+ })
448
+
449
+ return html
450
+ }
451
+
452
+ function convertPitchTableBlock(
453
+ block: any,
454
+ recipe: StyleRecipe,
455
+ boxCoords: { left: number; top: number; width: number; height: number }
456
+ ): SlideElement {
457
+ const rowsData: string[][] = Array.isArray(block['table-data']) ? block['table-data'] : [['<p><br></p>']]
458
+ const rowCount = Math.max(1, rowsData.length)
459
+ const colCount = Math.max(1, rowsData[0]?.length || 1)
460
+ const hasHeaders = block['table-headers?'] !== false
461
+ const hasAltRows = block['alternating-rows?'] !== false
462
+
463
+ const layoutCols: number[] = Array.isArray(block.layout?.cols) ? block.layout.cols : []
464
+ const totalColWeight = layoutCols.reduce((acc, v) => acc + (Number(v) || 0), 0) || colCount
465
+
466
+ const headerBg = recipe.table.headerBg || '#391C1C'
467
+ const headerTextColor = recipe.table.headerTextColor || '#FFFFFF'
468
+ const altRowBg = recipe.table.alternateRowBg || 'rgba(0,0,0,0.05)'
469
+ const borderColor = recipe.table.borderColor || '#CBD5E1'
470
+ const bodyTextColor = recipe.table.textColor || recipe.textStyles.normalText.color || '#1E293B'
471
+ const fontSizePx = recipe.table.fontSize || 18
472
+ const rowPct = (100 / rowCount).toFixed(2)
473
+ const vAlign = block['text-align-vertical'] === 'top' ? 'top' : block['text-align-vertical'] === 'bottom' ? 'bottom' : 'middle'
474
+
475
+ let tableHtml = `<table style="width:100%; height:100%; table-layout:fixed; border-collapse:collapse; border:1px solid ${borderColor}; font-family:SourceHanSansCN, sans-serif; font-size:${fontSizePx}px;"><tbody>`
476
+
477
+ for (let r = 0; r < rowCount; r++) {
478
+ tableHtml += `<tr style="height:${rowPct}%;">`
479
+ for (let c = 0; c < colCount; c++) {
480
+ const colWeight = layoutCols[c] !== undefined ? Number(layoutCols[c]) : 1
481
+ const colPct = ((colWeight / totalColWeight) * 100).toFixed(2)
482
+ const isHeader = hasHeaders && r === 0
483
+ const bg = isHeader
484
+ ? headerBg
485
+ : hasAltRows && r % 2 === 1
486
+ ? altRowBg
487
+ : 'transparent'
488
+ const textColor = isHeader ? headerTextColor : bodyTextColor
489
+ const fontWeight = isHeader ? 'font-weight:bold;' : ''
490
+ const rawCell = (rowsData[r] && rowsData[r][c]) ? String(rowsData[r][c]) : '<p><br></p>'
491
+ const cleanCell = rawCell
492
+ .replace(/<p(\s[^>]*)?>\s*<\/p>/gi, '<p><br></p>')
493
+ .replace(/<p(\s[^>]*)?>/gi, `<p style="margin:0; color:${textColor};">`)
494
+
495
+ const cellStyle = `border:1px solid ${borderColor}; padding:10px 14px; text-align:left; background:${bg}; color:${textColor}; ${fontWeight} width:${colPct}%; height:${rowPct}%; vertical-align:${vAlign}; word-break:break-word; box-sizing:border-box;`
496
+ tableHtml += `<td contenteditable="false" style="${cellStyle}">${cleanCell}</td>`
497
+ }
498
+ tableHtml += '</tr>'
499
+ }
500
+ tableHtml += '</tbody></table>'
501
+
502
+ return {
503
+ id: block.id || `pitch-table-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
504
+ type: 'text',
505
+ content: tableHtml,
506
+ left: boxCoords.left,
507
+ top: boxCoords.top,
508
+ width: boxCoords.width,
509
+ height: boxCoords.height,
510
+ style: {
511
+ left: `${boxCoords.left}px`,
512
+ top: `${boxCoords.top}px`,
513
+ width: `${boxCoords.width}px`,
514
+ height: `${boxCoords.height}px`,
515
+ padding: '0px',
516
+ fontSize: `${fontSizePx}px`,
517
+ color: bodyTextColor
518
+ }
519
+ }
520
+ }
521
+
522
+ function convertPitchChartBlock(
523
+ block: any,
524
+ recipe: StyleRecipe,
525
+ boxCoords: { left: number; top: number; width: number; height: number }
526
+ ): SlideElement {
527
+ const rawType = String(block['chart-type'] || 'bar').toLowerCase()
528
+ let chartType: 'bar' | 'horizontal-bar' | 'line' | 'area' | 'scatter' | 'pie' | 'donut' | 'radar' = 'bar'
529
+ if (rawType.includes('line')) chartType = 'line'
530
+ else if (rawType.includes('area')) chartType = 'area'
531
+ else if (rawType.includes('donut') || rawType.includes('doughnut')) chartType = 'donut'
532
+ else if (rawType.includes('pie')) {
533
+ // Pitch 中的 pie 图表默认带内圈半径与 pad-angle(即环形图 Donut chart)
534
+ chartType = block['pad-angle'] !== undefined || (block['svg-string'] || '').includes('A110,110') ? 'donut' : 'pie'
535
+ } else if (rawType.includes('radar')) chartType = 'radar'
536
+ else if (rawType.includes('horizontal') || rawType.includes('row')) chartType = 'horizontal-bar'
537
+
538
+ const rows: any[][] = Array.isArray(block.content) ? block.content : []
539
+ const colLabels: string[] = Array.isArray(block['column-labels']) ? block['column-labels'] : []
540
+ const labels: string[] = []
541
+ const seriesCount = Math.max(1, colLabels.length || ((rows[0]?.length || 2) - 1))
542
+ const datasets: { label: string; data: number[] }[] = Array.from({ length: seriesCount }, (_, i) => ({
543
+ label: (colLabels[i] || `系列 ${i + 1}`).trim(),
544
+ data: []
545
+ }))
546
+
547
+ for (const row of rows) {
548
+ if (!Array.isArray(row) || row.length === 0) continue
549
+ labels.push(String(row[0] ?? ''))
550
+ for (let s = 0; s < seriesCount; s++) {
551
+ const num = parseFloat(String(row[s + 1] ?? '0').replace(/,/g, ''))
552
+ datasets[s].data.push(isNaN(num) ? 0 : num)
553
+ }
554
+ }
555
+
556
+ const colorRange = Array.isArray(block['color-range'])
557
+ ? block['color-range'].map((c: any) => rgbaObjToHex(c, '')).filter(Boolean)
558
+ : []
559
+ const chartColors = colorRange.length > 0 ? colorRange : recipe.chart.palette
560
+
561
+ // 如果存在独立图例坐标 chart-legend/coords,将图表顶部扩展以包含图例区域
562
+ const legendCoords = block['chart-legend/coords']
563
+ let finalTop = boxCoords.top
564
+ let finalHeight = boxCoords.height
565
+ if (legendCoords && typeof legendCoords['y-start'] === 'number') {
566
+ const legTop = Math.round(legendCoords['y-start'] * LOGICAL_HEIGHT * 100) / 100
567
+ if (legTop < finalTop) {
568
+ finalHeight = Math.round((finalHeight + (finalTop - legTop)) * 100) / 100
569
+ finalTop = legTop
570
+ }
571
+ }
572
+
573
+ return {
574
+ id: block.id || `pitch-chart-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
575
+ type: 'chart',
576
+ chartType,
577
+ content: '',
578
+ data: {
579
+ labels,
580
+ datasets
581
+ },
582
+ themeColors: chartColors,
583
+ showLegend: block['chart-legend/enabled?'] !== false,
584
+ legendPosition: 'top',
585
+ showAxes: true,
586
+ showGridlines: true,
587
+ showDataLabels: Boolean(block['show-value-labels?']),
588
+ labelColor: recipe.chart.labelColor,
589
+ gridColor: recipe.chart.gridColor,
590
+ textColor: recipe.chart.textColor,
591
+ left: boxCoords.left,
592
+ top: finalTop,
593
+ width: boxCoords.width,
594
+ height: finalHeight,
595
+ style: {
596
+ left: `${boxCoords.left}px`,
597
+ top: `${finalTop}px`,
598
+ width: `${boxCoords.width}px`,
599
+ height: `${finalHeight}px`,
600
+ chartColors,
601
+ color: recipe.chart.labelColor,
602
+ textColor: recipe.chart.labelColor,
603
+ labelColor: recipe.chart.labelColor,
604
+ gridColor: recipe.chart.gridColor
605
+ }
606
+ }
607
+ }
608
+
609
+ function convertPitchBlockToElements(
610
+ block: any,
611
+ slide: any,
612
+ recipe: StyleRecipe,
613
+ pitchTheme: any,
614
+ groupOffset: { x: number; y: number } = { x: 0, y: 0 }
615
+ ): SlideElement[] {
616
+ if (!block || typeof block !== 'object') return []
617
+
618
+ // 处理 group 组合容器 (例如 key-layouts.transit 中的时间轴节点组合)
619
+ if (block['entity-type'] === 'group' && Array.isArray(block.children)) {
620
+ const gCoords = block.coords || {}
621
+ const gx = groupOffset.x + Number(gCoords['x-start'] ?? 0)
622
+ const gy = groupOffset.y + Number(gCoords['y-start'] ?? 0)
623
+ const res: SlideElement[] = []
624
+ for (const child of block.children) {
625
+ res.push(...convertPitchBlockToElements(child, slide, recipe, pitchTheme, { x: gx, y: gy }))
626
+ }
627
+ return res
628
+ }
629
+
630
+ const single = convertPitchBlockToElement(block, slide, recipe, pitchTheme, groupOffset)
631
+ return single ? [single] : []
632
+ }
633
+
634
+ function convertPitchBlockToElement(
635
+ block: any,
636
+ slide: any,
637
+ recipe: StyleRecipe,
638
+ pitchTheme: any,
639
+ groupOffset: { x: number; y: number } = { x: 0, y: 0 }
640
+ ): SlideElement | null {
641
+ if (!block || typeof block !== 'object') return null
642
+ const bgImgId = slide?.['background-image']?.id
643
+ if (bgImgId && block.id === bgImgId) {
644
+ // 过滤掉 Pitch 同时塞在 children 里的重复背景图块
645
+ return null
646
+ }
647
+
648
+ const coords = block.coords
649
+ if (!coords || typeof coords !== 'object') return null
650
+
651
+ const xStart = groupOffset.x + Number(coords['x-start'] ?? 0)
652
+ const xEnd = groupOffset.x + Number(coords['x-end'] ?? 1)
653
+ const yStart = groupOffset.y + Number(coords['y-start'] ?? 0)
654
+ const yEnd = groupOffset.y + Number(coords['y-end'] ?? 1)
655
+
656
+ const left = Math.round(xStart * LOGICAL_WIDTH * 100) / 100
657
+ const top = Math.round(yStart * LOGICAL_HEIGHT * 100) / 100
658
+ const width = Math.max(2, Math.round(Math.abs(xEnd - xStart) * LOGICAL_WIDTH * 100) / 100)
659
+ const height = Math.max(2, Math.round(Math.abs(yEnd - yStart) * LOGICAL_HEIGHT * 100) / 100)
660
+ const boxCoords = { left, top, width, height }
661
+
662
+ const blockType = block['block-type']
663
+ const opacity = block.opacity !== undefined ? Number(block.opacity) : 1
664
+
665
+ // 1. 文本块
666
+ if (blockType === 'text') {
667
+ const pitchTextType = block['text-type'] || 'paragraph'
668
+ const textType = mapPitchTextType(pitchTextType)
669
+ const styleCfg = recipe.textStyles[textType] || recipe.textStyles.normalText
670
+
671
+ const textScale = Number(pitchTheme?.['text-size']) || 1
672
+ const baseUnit = PITCH_BASE_FONT_PX * textScale
673
+ const fontSizePx = block['font-size']
674
+ ? Math.max(10, Math.round(Number(block['font-size']) * baseUnit))
675
+ : styleCfg.fontSize
676
+
677
+ const lineHeight = block['line-height'] !== undefined
678
+ ? Number(block['line-height'])
679
+ : styleCfg.lineHeight
680
+
681
+ const letterSpacingPx = block['letter-spacing'] !== undefined
682
+ ? Math.round(Number(block['letter-spacing']) * fontSizePx * 10) / 10
683
+ : styleCfg.letterSpacing
684
+
685
+ const paragraphSpacingPx = block['paragraph-spacing'] !== undefined
686
+ ? Math.round(Number(block['paragraph-spacing']) * fontSizePx * 0.45)
687
+ : styleCfg.paragraphSpacing
688
+
689
+ const textAlign = block['text-align'] || block['auto-align-default'] || 'left'
690
+ const verticalAlign = block['text-align-vertical'] || block['auto-vertical-align-default'] || 'top'
691
+ const textColor = styleCfg.color || recipe.textStyles.normalText.color || '#1E293B'
692
+
693
+ const formattedHtml = formatPitchTextHtml(block.body || '', {
694
+ textAlign,
695
+ color: textColor,
696
+ bulletColor: recipe.bulletPointsColor || textColor,
697
+ uppercase: Boolean(styleCfg.uppercase),
698
+ paragraphSpacingPx,
699
+ fontSizePx
700
+ })
701
+
702
+ return {
703
+ id: block.id || `pitch-text-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
704
+ type: 'text',
705
+ textType,
706
+ content: formattedHtml,
707
+ left,
708
+ top,
709
+ width,
710
+ height,
711
+ verticalAlign,
712
+ style: {
713
+ left: `${left}px`,
714
+ top: `${top}px`,
715
+ width: `${width}px`,
716
+ height: `${height}px`,
717
+ padding: '0px',
718
+ color: textColor,
719
+ textColor,
720
+ fontSize: `${fontSizePx}px`,
721
+ fontFamily: recipe.styleFonts.bodyFont || 'SourceHanSansCN',
722
+ fontWeight: styleCfg.fontWeight || 'normal',
723
+ lineHeight: lineHeight || 1.25,
724
+ letterSpacing: letterSpacingPx ? `${letterSpacingPx}px` : '0px',
725
+ textAlign,
726
+ verticalAlign,
727
+ opacity
728
+ }
729
+ }
730
+ }
731
+
732
+ // 2. 图片块 (含 SVG 装饰图与版式占位图)
733
+ if (blockType === 'image') {
734
+ const url = block.url || ''
735
+ if (!url) return null
736
+
737
+ const roundnessPx =
738
+ block['corner-roundness-px'] === 'round'
739
+ ? Math.round(Math.min(width, height) / 2)
740
+ : block['corner-roundness-px']
741
+ ? Math.round(Number(block['corner-roundness-px']) * (LOGICAL_WIDTH / 1920))
742
+ : block['corner-roundness']
743
+ ? Math.round(Number(block['corner-roundness']) * Math.min(width, height) * 0.5)
744
+ : 0
745
+
746
+ const hasBorder = block['border?'] === true && Number(block['border-width']) > 0
747
+ const borderWidth = hasBorder ? Math.max(1, Math.round(Number(block['border-width']) * (LOGICAL_WIDTH / 1920))) : 0
748
+ const borderColor = hasBorder ? rgbaObjToCss(block['border-color'], '#000000') : 'transparent'
749
+
750
+ // 根据 image-aspect-ratio 与容器宽高比计算裁切偏移 (保证人像不被拉伸且对焦位置一致)
751
+ let clip: SlideElement['clip'] | undefined
752
+ const imgAspect = Number(block['image-aspect-ratio'])
753
+ const boxAspect = width / Math.max(1, height)
754
+ const isSvg = url.includes('image%2Fsvg') || url.includes('image/svg') || url.endsWith('.svg')
755
+ const hasScaleCrop = Number(block['image-scale-x']) > 1.05
756
+ if (!isSvg && imgAspect > 0 && isFinite(imgAspect) && Math.abs(imgAspect - boxAspect) / Math.max(imgAspect, boxAspect) > 0.04) {
757
+ const posX = block['image-position']?.x !== undefined ? Number(block['image-position'].x) : 50
758
+ const posY = block['image-position']?.y !== undefined ? Number(block['image-position'].y) : 50
759
+ if (boxAspect > imgAspect) {
760
+ // 容器更宽,上下裁切
761
+ const visH = (imgAspect / boxAspect) * 100
762
+ const y0 = Math.max(0, Math.min(100 - visH, (100 - visH) * (posY / 100)))
763
+ clip = {
764
+ range: [
765
+ [0, Math.round(y0 * 100) / 100],
766
+ [100, Math.round((y0 + visH) * 100) / 100]
767
+ ]
768
+ }
769
+ } else {
770
+ // 容器更高,左右裁切
771
+ const visW = (boxAspect / imgAspect) * 100
772
+ const x0 = Math.max(0, Math.min(100 - visW, (100 - visW) * (posX / 100)))
773
+ clip = {
774
+ range: [
775
+ [Math.round(x0 * 100) / 100, 0],
776
+ [Math.round((x0 + visW) * 100) / 100, 100]
777
+ ]
778
+ }
779
+ }
780
+ }
781
+
782
+ return {
783
+ id: block.id || `pitch-img-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
784
+ type: 'image',
785
+ content: url,
786
+ src: url,
787
+ left,
788
+ top,
789
+ width,
790
+ height,
791
+ ...(clip ? { clip } : {}),
792
+ style: {
793
+ left: `${left}px`,
794
+ top: `${top}px`,
795
+ width: `${width}px`,
796
+ height: `${height}px`,
797
+ borderRadius: roundnessPx > 0 ? `${roundnessPx}px` : '0px',
798
+ borderWidth: borderWidth > 0 ? `${borderWidth}px` : '0px',
799
+ borderStyle: borderWidth > 0 ? 'solid' : 'none',
800
+ borderColor,
801
+ opacity,
802
+ ...(!isSvg || hasScaleCrop ? { objectFit: 'cover' as any } : {})
803
+ }
804
+ }
805
+ }
806
+
807
+ // 3. 形状与线条块
808
+ if (blockType === 'shape') {
809
+ const shapeType = block['shape-type'] || 'rectangle'
810
+ const fillColorObj = block['fill-color']
811
+ const fillGradient = block['fill-gradient']
812
+ const hasBorder = block['border?'] === true && Number(block['border-width']) > 0
813
+ const bodyText = (block.body || '').replace(/<[^>]*>/g, '').trim()
814
+
815
+ // 过滤透明占位辅助框 (a === 0 且无渐变、无边框、无文字)
816
+ if (
817
+ shapeType === 'rectangle' &&
818
+ fillColorObj &&
819
+ Number(fillColorObj.a) === 0 &&
820
+ !fillGradient &&
821
+ !hasBorder &&
822
+ !bodyText
823
+ ) {
824
+ return null
825
+ }
826
+
827
+ // 线条 (marker-line / plain-line2 / arrow-line2 / plain-line)
828
+ if (
829
+ shapeType === 'marker-line' ||
830
+ shapeType === 'plain-line2' ||
831
+ shapeType === 'arrow-line2' ||
832
+ shapeType === 'plain-line'
833
+ ) {
834
+ const rawLeft = xStart * LOGICAL_WIDTH
835
+ const rawRight = xEnd * LOGICAL_WIDTH
836
+ const rawTop = yStart * LOGICAL_HEIGHT
837
+ const rawBottom = yEnd * LOGICAL_HEIGHT
838
+
839
+ let x1: number
840
+ let y1: number
841
+ let x2: number
842
+ let y2: number
843
+
844
+ if (shapeType === 'plain-line' && block.rotation === undefined) {
845
+ x1 = rawLeft
846
+ y1 = rawTop
847
+ x2 = rawRight
848
+ y2 = rawBottom
849
+ } else {
850
+ const cx = (rawLeft + rawRight) / 2
851
+ const cy = (rawTop + rawBottom) / 2
852
+ const halfW = Math.abs(rawRight - rawLeft) / 2
853
+ const rotDeg = Number(block.rotation) || 0
854
+ const rad = (rotDeg * Math.PI) / 180
855
+ x1 = cx - halfW * Math.cos(rad)
856
+ y1 = cy - halfW * Math.sin(rad)
857
+ x2 = cx + halfW * Math.cos(rad)
858
+ y2 = cy + halfW * Math.sin(rad)
859
+ }
860
+
861
+ const lineLeft = Math.round(Math.min(x1, x2) * 100) / 100
862
+ const lineTop = Math.round(Math.min(y1, y2) * 100) / 100
863
+ const lineWidth = Math.max(2, Math.round(Math.abs(x2 - x1) * 100) / 100)
864
+ const lineHeight = Math.max(2, Math.round(Math.abs(y2 - y1) * 100) / 100)
865
+
866
+ const startPt: [number, number] = [
867
+ Math.round((x1 - lineLeft) * 100) / 100,
868
+ Math.round((y1 - lineTop) * 100) / 100
869
+ ]
870
+ const endPt: [number, number] = [
871
+ Math.round((x2 - lineLeft) * 100) / 100,
872
+ Math.round((y2 - lineTop) * 100) / 100
873
+ ]
874
+
875
+ const strokeColor = rgbaObjToCss(
876
+ fillColorObj || block['border-color'] || pitchTheme?.blocks?.shape?.['stroke-color'] || pitchTheme?.['text-color'],
877
+ recipe.textStyles.normalText.color || '#391C1C'
878
+ )
879
+ const isDashed = block['dash-styling'] === 'dashed' || block['dash-styling'] === 'dotted'
880
+ const markerStart = block['marker-start'] && block['marker-start'] !== 'none' ? 'arrow' : ''
881
+ const markerEnd =
882
+ (block['marker-end'] && block['marker-end'] !== 'none') || shapeType === 'arrow-line2'
883
+ ? 'arrow'
884
+ : ''
885
+
886
+ return {
887
+ id: block.id || `pitch-line-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
888
+ type: 'line',
889
+ content: `M ${startPt[0]} ${startPt[1]} L ${endPt[0]} ${endPt[1]}`,
890
+ start: startPt,
891
+ end: endPt,
892
+ lineStyle: isDashed ? 'dashed' : 'solid',
893
+ points: [markerStart, markerEnd],
894
+ left: lineLeft,
895
+ top: lineTop,
896
+ width: lineWidth,
897
+ height: lineHeight,
898
+ style: {
899
+ left: `${lineLeft}px`,
900
+ top: `${lineTop}px`,
901
+ width: `${lineWidth}px`,
902
+ height: `${lineHeight}px`,
903
+ color: strokeColor,
904
+ strokeWidth: block['border-width'] ? Math.max(1, Number(block['border-width'])) : 1.5,
905
+ opacity
906
+ }
907
+ }
908
+ }
909
+
910
+ // 矩形 / 椭圆 / 三角形 / 菱形等常规形状
911
+ const isEllipse = shapeType === 'ellipse' || shapeType === 'circle'
912
+ const isTriangle = shapeType === 'triangle'
913
+ const isDiamond = shapeType === 'diamond'
914
+
915
+ const roundnessPx =
916
+ block['corner-roundness-px'] === 'round'
917
+ ? Math.round(Math.min(width, height) / 2)
918
+ : block['corner-roundness-px']
919
+ ? Math.round(Number(block['corner-roundness-px']) * (LOGICAL_WIDTH / 1920))
920
+ : block['corner-roundness']
921
+ ? Math.round(Number(block['corner-roundness']) * Math.min(width, height) * 0.5)
922
+ : 0
923
+
924
+ let gradient: any = undefined
925
+ const defaultShapeFill = rgbaObjToCss(
926
+ pitchTheme?.blocks?.shape?.color,
927
+ recipe.shape?.fillColor || '#E5E7F0'
928
+ )
929
+ let fillCss = rgbaObjToCss(fillColorObj, defaultShapeFill)
930
+
931
+ if (fillGradient && fillGradient.start && fillGradient.stop) {
932
+ const startColor = rgbaObjToCss(fillGradient.start, '#FF8995')
933
+ const stopColor = rgbaObjToCss(fillGradient.stop, '#FFAD5A')
934
+ const cssAngle = Number(fillGradient.angle ?? 180)
935
+ const pptRot = ((cssAngle - 90) % 360 + 360) % 360
936
+ gradient = {
937
+ type: 'linear',
938
+ path: 'line',
939
+ rot: pptRot,
940
+ rotate: pptRot,
941
+ colors: [
942
+ { pos: '0%', color: startColor },
943
+ { pos: '100%', color: stopColor }
944
+ ],
945
+ css: `linear-gradient(${cssAngle}deg, ${startColor} 0%, ${stopColor} 100%)`
946
+ }
947
+ fillCss = startColor
948
+ }
949
+
950
+ const borderWidth = hasBorder ? Math.max(1, Math.round(Number(block['border-width']) * (LOGICAL_WIDTH / 1920))) : 0
951
+ const defaultBorderColor = rgbaObjToCss(
952
+ pitchTheme?.blocks?.shape?.['stroke-color'] || pitchTheme?.['text-color'],
953
+ recipe.shape?.borderColor || '#2B2A35'
954
+ )
955
+ const borderColor = hasBorder ? rgbaObjToCss(block['border-color'], defaultBorderColor) : 'transparent'
956
+ const shapeTextColor = rgbaObjToCss(
957
+ pitchTheme?.blocks?.shape?.['text-color'] || pitchTheme?.['text-color'],
958
+ recipe.shape?.textColor || '#2B2A35'
959
+ )
960
+
961
+ let shapType = 'rect'
962
+ let shapeContent = 'rect'
963
+ if (isEllipse) {
964
+ shapType = 'ellipse'
965
+ shapeContent = 'circle'
966
+ } else if (isTriangle) {
967
+ shapType = 'triangle'
968
+ shapeContent = 'triangle'
969
+ } else if (isDiamond) {
970
+ shapType = 'diamond'
971
+ shapeContent = `M ${width / 2} 0 L ${width} ${height / 2} L ${width / 2} ${height} L 0 ${height / 2} Z`
972
+ } else if (roundnessPx > 0) {
973
+ shapType = 'roundRect'
974
+ shapeContent = 'rect'
975
+ }
976
+
977
+ const rotDeg = Number(block.rotation) || 0
978
+
979
+ return {
980
+ id: block.id || `pitch-shape-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
981
+ type: 'shape',
982
+ shapType,
983
+ content: shapeContent,
984
+ ...(isDiamond ? { viewBox: [width, height] as [number, number] } : {}),
985
+ ...(rotDeg ? { rotate: rotDeg } : {}),
986
+ text: bodyText ? block.body : '',
987
+ left,
988
+ top,
989
+ width,
990
+ height,
991
+ ...(gradient ? { gradient } : {}),
992
+ style: {
993
+ left: `${left}px`,
994
+ top: `${top}px`,
995
+ width: `${width}px`,
996
+ height: `${height}px`,
997
+ fill: fillCss,
998
+ borderRadius: roundnessPx > 0 ? `${roundnessPx}px` : '0px',
999
+ borderWidth: borderWidth > 0 ? `${borderWidth}px` : '0px',
1000
+ borderStyle: borderWidth > 0 ? 'solid' : 'none',
1001
+ borderColor,
1002
+ color: shapeTextColor,
1003
+ textColor: shapeTextColor,
1004
+ opacity
1005
+ }
1006
+ }
1007
+ }
1008
+
1009
+ // 4. 表格块
1010
+ if (blockType === 'table') {
1011
+ return convertPitchTableBlock(block, recipe, boxCoords)
1012
+ }
1013
+
1014
+ // 5. 图表块
1015
+ if (blockType === 'chart') {
1016
+ return convertPitchChartBlock(block, recipe, boxCoords)
1017
+ }
1018
+
1019
+ // 6. 视频块
1020
+ if (blockType === 'video') {
1021
+ const sources: any[] = Array.isArray(block.sources) ? block.sources : []
1022
+ const playlistSource = sources.find(s => s && s['media-id'])
1023
+ const mediaId = playlistSource?.['media-id']
1024
+ const thumbTime = Number(block['thumbnail-time']) || 0
1025
+ const posterUrl = mediaId ? `https://image.mux.com/${mediaId}/thumbnail.jpg?time=${thumbTime}` : ''
1026
+ const videoUrl = block.url || (mediaId ? `https://stream.mux.com/${mediaId}/high.mp4` : '')
1027
+
1028
+ return {
1029
+ id: block.id || `pitch-video-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
1030
+ type: 'video',
1031
+ content: videoUrl,
1032
+ ...(posterUrl ? { poster: posterUrl } : {}),
1033
+ autoplay: Boolean(block.autoplay),
1034
+ left,
1035
+ top,
1036
+ width,
1037
+ height,
1038
+ style: {
1039
+ left: `${left}px`,
1040
+ top: `${top}px`,
1041
+ width: `${width}px`,
1042
+ height: `${height}px`,
1043
+ borderRadius: '0px',
1044
+ opacity
1045
+ }
1046
+ } as any
1047
+ }
1048
+
1049
+ return null
1050
+ }
1051
+
1052
+ /**
1053
+ * 将 Pitch 原始模板或版式库数据 (Transit-JSON 或已解码对象/数组) 转换为 jvs-ppt-ui 的完整 DeckData
1054
+ */
1055
+ export function convertPitchTemplateToDeck(
1056
+ rawInput: any,
1057
+ options?: { categoryFilter?: string }
1058
+ ): DeckData & { styleRecipes: StyleRecipe[] } {
1059
+ const decoded = decodeTransitJson(rawInput)
1060
+ const isLayoutLibrary =
1061
+ Array.isArray(decoded) &&
1062
+ decoded.length > 0 &&
1063
+ decoded.some((s: any) => s && (s['entity-type'] === 'slide' || Array.isArray(s.children)))
1064
+
1065
+ const payload = isLayoutLibrary
1066
+ ? { slides: decoded }
1067
+ : decoded?.data && Array.isArray(decoded.data.slides)
1068
+ ? decoded.data
1069
+ : decoded
1070
+
1071
+ let rawSlides: any[] = Array.isArray(payload?.slides) ? payload.slides : []
1072
+
1073
+ const categoryFilter = options?.categoryFilter
1074
+ if (isLayoutLibrary && categoryFilter && categoryFilter !== 'all') {
1075
+ rawSlides = rawSlides.filter((s: any) => s?.['key-layout-data']?.category === categoryFilter)
1076
+ }
1077
+
1078
+ if (rawSlides.length === 0) {
1079
+ throw new Error('未在数据中找到有效的 Pitch 幻灯片或版式列表 (slides)')
1080
+ }
1081
+
1082
+ const catLabel = categoryFilter && categoryFilter !== 'all' ? CATEGORY_LABEL_MAP[categoryFilter] || categoryFilter : ''
1083
+ const title = isLayoutLibrary
1084
+ ? `Pitch 官方版式库${catLabel ? ` - ${catLabel}` : ''} (${rawSlides.length}页)`
1085
+ : payload?.name || payload?.['meta-title'] || 'Pitch 导入模板'
1086
+
1087
+ // 1. 提取并转换所有内嵌主题 (StyleRecipe)
1088
+ const recipeMap = new Map<string, StyleRecipe>()
1089
+ const styleRecipes: StyleRecipe[] = []
1090
+
1091
+ rawSlides.forEach((s, idx) => {
1092
+ const pt = s?.theme
1093
+ if (pt && typeof pt === 'object') {
1094
+ const key = pt.id || pt.name || `theme-${idx}`
1095
+ if (!recipeMap.has(key)) {
1096
+ const recipe = convertPitchThemeToRecipe(pt, styleRecipes.length)
1097
+ recipeMap.set(key, recipe)
1098
+ styleRecipes.push(recipe)
1099
+ }
1100
+ }
1101
+ })
1102
+
1103
+ if (styleRecipes.length === 0) {
1104
+ const fallbackRecipe = convertPitchThemeToRecipe({}, 0)
1105
+ recipeMap.set('default', fallbackRecipe)
1106
+ styleRecipes.push(fallbackRecipe)
1107
+ }
1108
+
1109
+ const primaryRecipe = styleRecipes[0]
1110
+
1111
+ // 2. 转换每一页幻灯片
1112
+ const convertedSlides: Slide[] = rawSlides.map((s, idx) => {
1113
+ const pt = s?.theme
1114
+ const themeKey = pt?.id || pt?.name || 'default'
1115
+ const recipe = recipeMap.get(themeKey) || primaryRecipe
1116
+
1117
+ const slideBgColor = rgbaObjToHex(
1118
+ s?.['background-color'] || pt?.['background-color'],
1119
+ recipe.backgroundColor || '#FFFFFF'
1120
+ )
1121
+ const bgImgUrl = s?.['background-image']?.url
1122
+
1123
+ let background: any = slideBgColor
1124
+ let bgType = 'color'
1125
+ if (bgImgUrl && typeof bgImgUrl === 'string') {
1126
+ background = {
1127
+ type: 'image',
1128
+ color: slideBgColor,
1129
+ image: {
1130
+ src: bgImgUrl,
1131
+ size: 'cover',
1132
+ repeat: 'no-repeat'
1133
+ }
1134
+ }
1135
+ bgType = 'image'
1136
+ }
1137
+
1138
+ const children: any[] = Array.isArray(s?.children) ? s.children : []
1139
+ const elements: SlideElement[] = []
1140
+ for (const child of children) {
1141
+ elements.push(...convertPitchBlockToElements(child, s, recipe, pt))
1142
+ }
1143
+
1144
+ const rawNote = typeof s?.note === 'string' ? s.note.replace(/<[^>]*>/g, '').trim() : ''
1145
+ const layoutMeta = s?.['key-layout-data']
1146
+ const layoutCat = layoutMeta?.category ? CATEGORY_LABEL_MAP[layoutMeta.category] || layoutMeta.category : ''
1147
+ const slideTitle = layoutMeta?.name
1148
+ ? `${layoutCat ? `[${layoutCat}] ` : ''}${layoutMeta.name}`
1149
+ : `幻灯片 ${idx + 1}`
1150
+
1151
+ return {
1152
+ id: s?.id || `pitch-slide-${idx + 1}`,
1153
+ title: slideTitle,
1154
+ background,
1155
+ bgType,
1156
+ elements,
1157
+ themeId: recipe.id,
1158
+ themeName: recipe.name,
1159
+ showMasterBackground: false,
1160
+ showMasterElements: false,
1161
+ notes: rawNote
1162
+ } as Slide
1163
+ })
1164
+
1165
+ return {
1166
+ title,
1167
+ width: LOGICAL_WIDTH,
1168
+ height: LOGICAL_HEIGHT,
1169
+ logicalWidth: LOGICAL_WIDTH,
1170
+ logicalHeight: LOGICAL_HEIGHT,
1171
+ ratio: '16:9',
1172
+ slideRatio: '16:9',
1173
+ theme: {
1174
+ fontFamily: primaryRecipe.styleFonts.bodyFont || 'SourceHanSansCN',
1175
+ fontColor: primaryRecipe.textStyles.normalText.color || '#1E293B',
1176
+ backgroundColor: primaryRecipe.backgroundColor || '#FFFFFF',
1177
+ themeColor: primaryRecipe.styleColors
1178
+ },
1179
+ styleRecipes,
1180
+ slides: convertedSlides
1181
+ }
1182
+ }
1183
+
1184
+ /**
1185
+ * 通过本地开发代理或直接 fetch 拉取 Pitch 模板/版式库并转换为 DeckData
1186
+ */
1187
+ export async function fetchAndConvertPitchTemplate(
1188
+ urlOrInput: string,
1189
+ options?: { categoryFilter?: string }
1190
+ ): Promise<DeckData & { styleRecipes: StyleRecipe[] }> {
1191
+ const trimmed = (urlOrInput || '').trim()
1192
+ if (!trimmed) {
1193
+ throw new Error('请输入 Pitch 模板地址或 JSON 数据')
1194
+ }
1195
+
1196
+ // 如果直接粘贴了 JSON 数组或对象文本
1197
+ if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
1198
+ const parsed = JSON.parse(trimmed)
1199
+ return convertPitchTemplateToDeck(parsed, options)
1200
+ }
1201
+
1202
+ const targetUrl = normalizePitchTemplateUrl(trimmed)
1203
+ let rawData: any = null
1204
+
1205
+ // 优先走本地 Vite 开发中间件代理 (规避浏览器 CORS 限制)
1206
+ if (import.meta.env.DEV) {
1207
+ try {
1208
+ const proxyRes = await fetch(`/__pitch_proxy?url=${encodeURIComponent(targetUrl)}`)
1209
+ if (proxyRes.ok) {
1210
+ rawData = await proxyRes.json()
1211
+ }
1212
+ } catch {
1213
+ // fallback to direct fetch
1214
+ }
1215
+ }
1216
+
1217
+ if (!rawData) {
1218
+ const res = await fetch(targetUrl)
1219
+ if (!res.ok) {
1220
+ throw new Error(`拉取 Pitch 数据失败 (HTTP ${res.status})`)
1221
+ }
1222
+ rawData = await res.json()
1223
+ }
1224
+
1225
+ return convertPitchTemplateToDeck(rawData, options)
1226
+ }