jvs-ppt-ui 0.0.30 → 0.0.33
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.
- package/README.md +152 -0
- package/dist/lib/jvs-ppt-ui.es.js +39270 -34665
- package/dist/lib/jvs-ppt-ui.umd.js +141 -114
- package/dist/lib/style.css +1 -1
- package/package.json +2 -1
- package/src/components/CanvasArea.vue +9 -1
- package/src/components/ChartTypeSelector.vue +69 -29
- package/src/components/Header.vue +228 -29
- package/src/components/PitchImportDialog.vue +482 -0
- package/src/components/PptEditor.vue +53 -1
- package/src/components/SidebarLeft.vue +367 -41
- package/src/components/SidebarRight.vue +75 -35
- package/src/components/StyleBuilderDialog.vue +276 -105
- package/src/components/SvgChart.vue +1242 -833
- package/src/components/canvas/elements/CanvasGroupElement.vue +16 -2
- package/src/components/canvas/elements/CanvasMediaElement.vue +5 -3
- package/src/components/canvas/elements/CanvasShapeElement.vue +6 -4
- package/src/components/sidebar/dialogs/ChartDataEditorDialog.vue +1040 -0
- package/src/components/sidebar/panels/LayoutThumbSvg.vue +9 -6
- package/src/components/sidebar/panels/SidebarChartFormatPanel.vue +1479 -641
- package/src/components/sidebar/panels/SidebarDesignPanel.vue +32 -0
- package/src/composables/presetThemes.ts +49 -1
- package/src/composables/sidebar/useSidebarChart.ts +357 -194
- package/src/composables/useSlides.ts +110 -22
- package/src/configs/slideTemplates.ts +1001 -0
- package/src/style.css +267 -4
- package/src/types/index.ts +37 -1
- package/src/utils/canvas/elementStyles.ts +55 -20
- package/src/utils/muxHlsToMp4.ts +569 -0
- package/src/utils/pitchConverter.ts +1725 -0
- package/dist/lib/templates/index.json +0 -5
|
@@ -0,0 +1,1725 @@
|
|
|
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 装饰图、贴纸、GIF 与版式占位图)
|
|
733
|
+
if (blockType === 'image' || blockType === 'sticker' || blockType === 'gif') {
|
|
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
|
+
const PITCH_S3_BASE = 'https://pitch-assets-ccb95893-de3f-4266-973c-20049231b248.s3.eu-west-1.amazonaws.com'
|
|
1020
|
+
|
|
1021
|
+
// 6. 视频块
|
|
1022
|
+
if (blockType === 'video') {
|
|
1023
|
+
const sources: any[] = Array.isArray(block.sources) ? block.sources : []
|
|
1024
|
+
const playlistSource = sources.find(s => s && s['media-id'])
|
|
1025
|
+
const assetSource = sources.find(s => s && s['asset-id'])
|
|
1026
|
+
const mediaId = playlistSource?.['media-id']
|
|
1027
|
+
const rawMediaAssetIds: any[] = Array.isArray(block['media-asset-ids']) ? block['media-asset-ids'] : []
|
|
1028
|
+
const mediaAssetIds = rawMediaAssetIds.filter(
|
|
1029
|
+
id => typeof id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)
|
|
1030
|
+
)
|
|
1031
|
+
const thumbTime = Number(block['thumbnail-time']) || 0
|
|
1032
|
+
const posterUrl =
|
|
1033
|
+
block['poster-url'] ||
|
|
1034
|
+
block.poster ||
|
|
1035
|
+
(mediaId ? `https://image.mux.com/${mediaId}/thumbnail.jpg?time=${thumbTime}` : '')
|
|
1036
|
+
|
|
1037
|
+
const candidateUrls: string[] = []
|
|
1038
|
+
const addCandidate = (u?: string) => {
|
|
1039
|
+
if (u && typeof u === 'string' && /^https?:\/\//i.test(u.trim()) && !candidateUrls.includes(u.trim())) {
|
|
1040
|
+
candidateUrls.push(u.trim())
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
addCandidate(block.url)
|
|
1044
|
+
for (const s of sources) {
|
|
1045
|
+
addCandidate(s?.url)
|
|
1046
|
+
}
|
|
1047
|
+
for (const id of mediaAssetIds) {
|
|
1048
|
+
addCandidate(`${PITCH_S3_BASE}/${id}`)
|
|
1049
|
+
}
|
|
1050
|
+
if (assetSource?.['asset-id'] && /^[0-9a-f-]{36}$/i.test(String(assetSource['asset-id']))) {
|
|
1051
|
+
addCandidate(`${PITCH_S3_BASE}/${assetSource['asset-id']}`)
|
|
1052
|
+
}
|
|
1053
|
+
if (mediaId) {
|
|
1054
|
+
// Mux 默认关闭静态 MP4 直链 (返回 403),优先通过代理拉取 HLS (.m3u8) 并无损重封装为标准 MP4
|
|
1055
|
+
addCandidate(`https://stream.mux.com/${mediaId}.m3u8`)
|
|
1056
|
+
addCandidate(`https://stream.mux.com/${mediaId}/high.mp4`)
|
|
1057
|
+
addCandidate(`https://stream.mux.com/${mediaId}/capped-1080p.mp4`)
|
|
1058
|
+
addCandidate(`https://stream.mux.com/${mediaId}/medium.mp4`)
|
|
1059
|
+
addCandidate(`https://stream.mux.com/${mediaId}/low.mp4`)
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
const videoUrl = candidateUrls[0] || ''
|
|
1063
|
+
|
|
1064
|
+
return {
|
|
1065
|
+
id: block.id || `pitch-video-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
1066
|
+
type: 'video',
|
|
1067
|
+
content: videoUrl,
|
|
1068
|
+
src: videoUrl,
|
|
1069
|
+
...(posterUrl ? { poster: posterUrl } : {}),
|
|
1070
|
+
...(candidateUrls.length > 0 ? { __candidateUrls: candidateUrls } : {}),
|
|
1071
|
+
autoplay: Boolean(block.autoplay),
|
|
1072
|
+
left,
|
|
1073
|
+
top,
|
|
1074
|
+
width,
|
|
1075
|
+
height,
|
|
1076
|
+
style: {
|
|
1077
|
+
left: `${left}px`,
|
|
1078
|
+
top: `${top}px`,
|
|
1079
|
+
width: `${width}px`,
|
|
1080
|
+
height: `${height}px`,
|
|
1081
|
+
borderRadius: '0px',
|
|
1082
|
+
opacity
|
|
1083
|
+
}
|
|
1084
|
+
} as any
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
// 7. 音频块
|
|
1088
|
+
if (blockType === 'audio') {
|
|
1089
|
+
const sources: any[] = Array.isArray(block.sources) ? block.sources : []
|
|
1090
|
+
const rawMediaAssetIds: any[] = Array.isArray(block['media-asset-ids']) ? block['media-asset-ids'] : []
|
|
1091
|
+
const mediaAssetIds = rawMediaAssetIds.filter(
|
|
1092
|
+
id => typeof id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)
|
|
1093
|
+
)
|
|
1094
|
+
const candidateUrls: string[] = []
|
|
1095
|
+
const addCandidate = (u?: string) => {
|
|
1096
|
+
if (u && typeof u === 'string' && /^https?:\/\//i.test(u.trim()) && !candidateUrls.includes(u.trim())) {
|
|
1097
|
+
candidateUrls.push(u.trim())
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
addCandidate(block.url)
|
|
1101
|
+
for (const s of sources) {
|
|
1102
|
+
addCandidate(s?.url)
|
|
1103
|
+
if (s?.['asset-id'] && /^[0-9a-f-]{36}$/i.test(String(s['asset-id']))) {
|
|
1104
|
+
addCandidate(`${PITCH_S3_BASE}/${s['asset-id']}`)
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
for (const id of mediaAssetIds) {
|
|
1108
|
+
addCandidate(`${PITCH_S3_BASE}/${id}`)
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
const audioUrl = candidateUrls[0] || ''
|
|
1112
|
+
if (!audioUrl) return null
|
|
1113
|
+
|
|
1114
|
+
return {
|
|
1115
|
+
id: block.id || `pitch-audio-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
1116
|
+
type: 'audio',
|
|
1117
|
+
content: audioUrl,
|
|
1118
|
+
src: audioUrl,
|
|
1119
|
+
...(candidateUrls.length > 0 ? { __candidateUrls: candidateUrls } : {}),
|
|
1120
|
+
left,
|
|
1121
|
+
top,
|
|
1122
|
+
width: Math.max(60, width),
|
|
1123
|
+
height: Math.max(60, height),
|
|
1124
|
+
style: {
|
|
1125
|
+
left: `${left}px`,
|
|
1126
|
+
top: `${top}px`,
|
|
1127
|
+
width: `${Math.max(60, width)}px`,
|
|
1128
|
+
height: `${Math.max(60, height)}px`,
|
|
1129
|
+
opacity
|
|
1130
|
+
}
|
|
1131
|
+
} as any
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
return null
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
/**
|
|
1138
|
+
* 将 Pitch 原始模板或版式库数据 (Transit-JSON 或已解码对象/数组) 转换为 jvs-ppt-ui 的完整 DeckData
|
|
1139
|
+
*/
|
|
1140
|
+
export function convertPitchTemplateToDeck(
|
|
1141
|
+
rawInput: any,
|
|
1142
|
+
options?: { categoryFilter?: string }
|
|
1143
|
+
): DeckData & { styleRecipes: StyleRecipe[] } {
|
|
1144
|
+
const decoded = decodeTransitJson(rawInput)
|
|
1145
|
+
const isLayoutLibrary =
|
|
1146
|
+
Array.isArray(decoded) &&
|
|
1147
|
+
decoded.length > 0 &&
|
|
1148
|
+
decoded.some((s: any) => s && (s['entity-type'] === 'slide' || Array.isArray(s.children)))
|
|
1149
|
+
|
|
1150
|
+
const payload = isLayoutLibrary
|
|
1151
|
+
? { slides: decoded }
|
|
1152
|
+
: decoded?.data && Array.isArray(decoded.data.slides)
|
|
1153
|
+
? decoded.data
|
|
1154
|
+
: decoded
|
|
1155
|
+
|
|
1156
|
+
let rawSlides: any[] = Array.isArray(payload?.slides) ? payload.slides : []
|
|
1157
|
+
|
|
1158
|
+
const categoryFilter = options?.categoryFilter
|
|
1159
|
+
if (isLayoutLibrary && categoryFilter && categoryFilter !== 'all') {
|
|
1160
|
+
rawSlides = rawSlides.filter((s: any) => s?.['key-layout-data']?.category === categoryFilter)
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
if (rawSlides.length === 0) {
|
|
1164
|
+
throw new Error('未在数据中找到有效的 Pitch 幻灯片或版式列表 (slides)')
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
const catLabel = categoryFilter && categoryFilter !== 'all' ? CATEGORY_LABEL_MAP[categoryFilter] || categoryFilter : ''
|
|
1168
|
+
const title = isLayoutLibrary
|
|
1169
|
+
? `Pitch 官方版式库${catLabel ? ` - ${catLabel}` : ''} (${rawSlides.length}页)`
|
|
1170
|
+
: payload?.name || payload?.['meta-title'] || 'Pitch 导入模板'
|
|
1171
|
+
|
|
1172
|
+
// 1. 提取并转换所有内嵌主题 (StyleRecipe)
|
|
1173
|
+
const recipeMap = new Map<string, StyleRecipe>()
|
|
1174
|
+
const styleRecipes: StyleRecipe[] = []
|
|
1175
|
+
|
|
1176
|
+
rawSlides.forEach((s, idx) => {
|
|
1177
|
+
const pt = s?.theme
|
|
1178
|
+
if (pt && typeof pt === 'object') {
|
|
1179
|
+
const key = pt.id || pt.name || `theme-${idx}`
|
|
1180
|
+
if (!recipeMap.has(key)) {
|
|
1181
|
+
const recipe = convertPitchThemeToRecipe(pt, styleRecipes.length)
|
|
1182
|
+
recipeMap.set(key, recipe)
|
|
1183
|
+
styleRecipes.push(recipe)
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
})
|
|
1187
|
+
|
|
1188
|
+
if (styleRecipes.length === 0) {
|
|
1189
|
+
const fallbackRecipe = convertPitchThemeToRecipe({}, 0)
|
|
1190
|
+
recipeMap.set('default', fallbackRecipe)
|
|
1191
|
+
styleRecipes.push(fallbackRecipe)
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
const primaryRecipe = styleRecipes[0]
|
|
1195
|
+
|
|
1196
|
+
// 2. 转换每一页幻灯片
|
|
1197
|
+
const convertedSlides: Slide[] = rawSlides.map((s, idx) => {
|
|
1198
|
+
const pt = s?.theme
|
|
1199
|
+
const themeKey = pt?.id || pt?.name || 'default'
|
|
1200
|
+
const recipe = recipeMap.get(themeKey) || primaryRecipe
|
|
1201
|
+
|
|
1202
|
+
const slideBgColor = rgbaObjToHex(
|
|
1203
|
+
s?.['background-color'] || pt?.['background-color'],
|
|
1204
|
+
recipe.backgroundColor || '#FFFFFF'
|
|
1205
|
+
)
|
|
1206
|
+
const bgImgUrl = s?.['background-image']?.url
|
|
1207
|
+
|
|
1208
|
+
let background: any = slideBgColor
|
|
1209
|
+
let bgType = 'color'
|
|
1210
|
+
if (bgImgUrl && typeof bgImgUrl === 'string') {
|
|
1211
|
+
background = {
|
|
1212
|
+
type: 'image',
|
|
1213
|
+
color: slideBgColor,
|
|
1214
|
+
value: bgImgUrl,
|
|
1215
|
+
image: {
|
|
1216
|
+
src: bgImgUrl,
|
|
1217
|
+
size: 'cover',
|
|
1218
|
+
repeat: 'no-repeat'
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
bgType = 'image'
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
const children: any[] = Array.isArray(s?.children) ? s.children : []
|
|
1225
|
+
const elements: SlideElement[] = []
|
|
1226
|
+
for (const child of children) {
|
|
1227
|
+
elements.push(...convertPitchBlockToElements(child, s, recipe, pt))
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
const rawNote = typeof s?.note === 'string' ? s.note.replace(/<[^>]*>/g, '').trim() : ''
|
|
1231
|
+
const layoutMeta = s?.['key-layout-data']
|
|
1232
|
+
const layoutCat = layoutMeta?.category ? CATEGORY_LABEL_MAP[layoutMeta.category] || layoutMeta.category : ''
|
|
1233
|
+
const slideTitle = layoutMeta?.name
|
|
1234
|
+
? `${layoutCat ? `[${layoutCat}] ` : ''}${layoutMeta.name}`
|
|
1235
|
+
: `幻灯片 ${idx + 1}`
|
|
1236
|
+
|
|
1237
|
+
return {
|
|
1238
|
+
id: s?.id || `pitch-slide-${idx + 1}`,
|
|
1239
|
+
title: slideTitle,
|
|
1240
|
+
background,
|
|
1241
|
+
bgType,
|
|
1242
|
+
elements,
|
|
1243
|
+
themeId: recipe.id,
|
|
1244
|
+
themeName: recipe.name,
|
|
1245
|
+
showMasterBackground: false,
|
|
1246
|
+
showMasterElements: false,
|
|
1247
|
+
notes: rawNote
|
|
1248
|
+
} as Slide
|
|
1249
|
+
})
|
|
1250
|
+
|
|
1251
|
+
return {
|
|
1252
|
+
title,
|
|
1253
|
+
width: LOGICAL_WIDTH,
|
|
1254
|
+
height: LOGICAL_HEIGHT,
|
|
1255
|
+
logicalWidth: LOGICAL_WIDTH,
|
|
1256
|
+
logicalHeight: LOGICAL_HEIGHT,
|
|
1257
|
+
ratio: '16:9',
|
|
1258
|
+
slideRatio: '16:9',
|
|
1259
|
+
theme: {
|
|
1260
|
+
fontFamily: primaryRecipe.styleFonts.bodyFont || 'SourceHanSansCN',
|
|
1261
|
+
fontColor: primaryRecipe.textStyles.normalText.color || '#1E293B',
|
|
1262
|
+
backgroundColor: primaryRecipe.backgroundColor || '#FFFFFF',
|
|
1263
|
+
themeColor: primaryRecipe.styleColors
|
|
1264
|
+
},
|
|
1265
|
+
styleRecipes,
|
|
1266
|
+
slides: convertedSlides
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
function inferMimeFromUrl(urlStr: string, fallbackType: 'image' | 'video' | 'audio' = 'image'): string {
|
|
1271
|
+
try {
|
|
1272
|
+
const u = new URL(urlStr)
|
|
1273
|
+
const pitchCt = u.searchParams.get('pitch-content-type')
|
|
1274
|
+
if (pitchCt && !pitchCt.includes('octet-stream')) {
|
|
1275
|
+
return pitchCt.split(';')[0].trim()
|
|
1276
|
+
}
|
|
1277
|
+
} catch {
|
|
1278
|
+
// ignore
|
|
1279
|
+
}
|
|
1280
|
+
const lower = urlStr.split('?')[0].toLowerCase()
|
|
1281
|
+
if (lower.endsWith('.svg')) return 'image/svg+xml'
|
|
1282
|
+
if (lower.endsWith('.png')) return 'image/png'
|
|
1283
|
+
if (lower.endsWith('.jpg') || lower.endsWith('.jpeg')) return 'image/jpeg'
|
|
1284
|
+
if (lower.endsWith('.webp')) return 'image/webp'
|
|
1285
|
+
if (lower.endsWith('.gif')) return 'image/gif'
|
|
1286
|
+
if (lower.endsWith('.mp4')) return 'video/mp4'
|
|
1287
|
+
if (lower.endsWith('.webm')) return 'video/webm'
|
|
1288
|
+
if (lower.endsWith('.mp3')) return 'audio/mpeg'
|
|
1289
|
+
if (lower.endsWith('.wav')) return 'audio/wav'
|
|
1290
|
+
if (lower.endsWith('.ogg')) return 'audio/ogg'
|
|
1291
|
+
if (lower.endsWith('.m4a')) return 'audio/mp4'
|
|
1292
|
+
if (fallbackType === 'video') return 'video/mp4'
|
|
1293
|
+
if (fallbackType === 'audio') return 'audio/mpeg'
|
|
1294
|
+
return 'image/png'
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
function arrayBufferToBase64DataUrl(buffer: ArrayBuffer, mime: string): string {
|
|
1298
|
+
const bytes = new Uint8Array(buffer)
|
|
1299
|
+
const chunkSize = 0x8000
|
|
1300
|
+
let binary = ''
|
|
1301
|
+
for (let i = 0; i < bytes.length; i += chunkSize) {
|
|
1302
|
+
const chunk = bytes.subarray(i, Math.min(i + chunkSize, bytes.length))
|
|
1303
|
+
binary += String.fromCharCode.apply(null, chunk as unknown as number[])
|
|
1304
|
+
}
|
|
1305
|
+
return `data:${mime};base64,${btoa(binary)}`
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
async function fetchMediaAsBase64(
|
|
1309
|
+
primaryUrl: string,
|
|
1310
|
+
mediaType: 'image' | 'video' | 'audio' = 'image',
|
|
1311
|
+
candidates?: string[]
|
|
1312
|
+
): Promise<string> {
|
|
1313
|
+
const trimmed = (primaryUrl || '').trim()
|
|
1314
|
+
if (!trimmed || trimmed.startsWith('data:')) return trimmed
|
|
1315
|
+
|
|
1316
|
+
const allCandidates: string[] = []
|
|
1317
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
1318
|
+
allCandidates.push(trimmed)
|
|
1319
|
+
}
|
|
1320
|
+
if (Array.isArray(candidates)) {
|
|
1321
|
+
for (const c of candidates) {
|
|
1322
|
+
if (typeof c === 'string' && /^https?:\/\//i.test(c.trim()) && !allCandidates.includes(c.trim())) {
|
|
1323
|
+
allCandidates.push(c.trim())
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
if (allCandidates.length === 0) return trimmed
|
|
1328
|
+
|
|
1329
|
+
// 1. 优先通过本地 Vite 媒体代理拉取并转为 Base64(规避 S3 / Mux / Unsplash 跨域限制,并支持 HLS .m3u8 转 MP4)
|
|
1330
|
+
let proxyHandled = false
|
|
1331
|
+
if (import.meta.env.DEV) {
|
|
1332
|
+
try {
|
|
1333
|
+
const qs = new URLSearchParams({
|
|
1334
|
+
url: allCandidates[0],
|
|
1335
|
+
type: mediaType
|
|
1336
|
+
})
|
|
1337
|
+
if (allCandidates.length > 1) {
|
|
1338
|
+
qs.set('candidates', JSON.stringify(allCandidates))
|
|
1339
|
+
}
|
|
1340
|
+
const proxyRes = await fetch(`/__pitch_media_proxy?${qs.toString()}`)
|
|
1341
|
+
const ct = proxyRes.headers.get('content-type') || ''
|
|
1342
|
+
if (ct.includes('application/json')) {
|
|
1343
|
+
proxyHandled = true
|
|
1344
|
+
if (proxyRes.ok) {
|
|
1345
|
+
const payload = await proxyRes.json()
|
|
1346
|
+
if (payload?.dataUrl && typeof payload.dataUrl === 'string' && payload.dataUrl.startsWith('data:')) {
|
|
1347
|
+
return payload.dataUrl
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
} catch {
|
|
1352
|
+
// fallback to browser fetch if proxy not reachable
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
// 如果本地代理已尝试全部候选地址仍未成功,不再在浏览器端重复请求以避免控制台报 403/CORS 红字
|
|
1357
|
+
if (proxyHandled) {
|
|
1358
|
+
return trimmed
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// 2. 浏览器端直连回退(跳过 .m3u8 流及已知会 403 的 stream.mux.com 静态 mp4)
|
|
1362
|
+
for (const candidateUrl of allCandidates) {
|
|
1363
|
+
if (
|
|
1364
|
+
candidateUrl.split('?')[0].toLowerCase().endsWith('.m3u8') ||
|
|
1365
|
+
candidateUrl.includes('stream.mux.com/')
|
|
1366
|
+
) {
|
|
1367
|
+
continue
|
|
1368
|
+
}
|
|
1369
|
+
try {
|
|
1370
|
+
const res = await fetch(candidateUrl, { mode: 'cors' })
|
|
1371
|
+
if (!res.ok) continue
|
|
1372
|
+
const contentType = (res.headers.get('content-type') || '').split(';')[0].trim().toLowerCase()
|
|
1373
|
+
if (contentType.includes('text/html')) continue
|
|
1374
|
+
const buf = await res.arrayBuffer()
|
|
1375
|
+
if (!buf || buf.byteLength === 0) continue
|
|
1376
|
+
const resolvedMime =
|
|
1377
|
+
contentType && contentType !== 'application/octet-stream' && contentType !== 'binary/octet-stream'
|
|
1378
|
+
? contentType
|
|
1379
|
+
: inferMimeFromUrl(candidateUrl, mediaType)
|
|
1380
|
+
return arrayBufferToBase64DataUrl(buf, resolvedMime)
|
|
1381
|
+
} catch {
|
|
1382
|
+
// try next candidate
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
return trimmed
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
// 会话级 Base64 Promise 缓存:同一资源无论出现在多少页幻灯片、或多次点击导入/下载,均只拉取并编码一次
|
|
1390
|
+
const sessionMediaBase64Cache = new Map<string, Promise<string>>()
|
|
1391
|
+
|
|
1392
|
+
/**
|
|
1393
|
+
* 将转换后的 DeckData 中所有图片、视频、音频及背景图外链资源批量拉取并内联为 Base64 DataURL
|
|
1394
|
+
*/
|
|
1395
|
+
export async function convertDeckMediaToBase64(
|
|
1396
|
+
deck: DeckData & { styleRecipes: StyleRecipe[] },
|
|
1397
|
+
onProgress?: (completed: number, total: number) => void
|
|
1398
|
+
): Promise<DeckData & { styleRecipes: StyleRecipe[] }> {
|
|
1399
|
+
if (!deck || !Array.isArray(deck.slides)) return deck
|
|
1400
|
+
|
|
1401
|
+
const getCachedBase64 = (
|
|
1402
|
+
url: string,
|
|
1403
|
+
mediaType: 'image' | 'video' | 'audio',
|
|
1404
|
+
candidates?: string[]
|
|
1405
|
+
): Promise<string> => {
|
|
1406
|
+
const key = `${mediaType}:${url}:${candidates ? candidates.join('|') : ''}`
|
|
1407
|
+
const existing = sessionMediaBase64Cache.get(key)
|
|
1408
|
+
if (existing) return existing
|
|
1409
|
+
|
|
1410
|
+
const promise = fetchMediaAsBase64(url, mediaType, candidates).then(res => {
|
|
1411
|
+
// 如果拉取失败仍返回原始 http 地址,则从缓存移除以便后续可重试
|
|
1412
|
+
if (!res.startsWith('data:')) {
|
|
1413
|
+
sessionMediaBase64Cache.delete(key)
|
|
1414
|
+
}
|
|
1415
|
+
return res
|
|
1416
|
+
})
|
|
1417
|
+
sessionMediaBase64Cache.set(key, promise)
|
|
1418
|
+
return promise
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
// 按唯一资源 Key 聚合所有引用点,保证相同资源只作为一个并发任务拉取一次,转换完成后一次性回填到所有引用元素
|
|
1422
|
+
const resourceTaskMap = new Map<
|
|
1423
|
+
string,
|
|
1424
|
+
{
|
|
1425
|
+
fetch: () => Promise<string>
|
|
1426
|
+
appliers: Array<(dataUrl: string) => void>
|
|
1427
|
+
}
|
|
1428
|
+
>()
|
|
1429
|
+
|
|
1430
|
+
const registerResource = (
|
|
1431
|
+
url: string,
|
|
1432
|
+
mediaType: 'image' | 'video' | 'audio',
|
|
1433
|
+
candidates: string[] | undefined,
|
|
1434
|
+
apply: (dataUrl: string) => void
|
|
1435
|
+
) => {
|
|
1436
|
+
const key = `${mediaType}:${url}:${candidates ? candidates.join('|') : ''}`
|
|
1437
|
+
let entry = resourceTaskMap.get(key)
|
|
1438
|
+
if (!entry) {
|
|
1439
|
+
entry = {
|
|
1440
|
+
fetch: () => getCachedBase64(url, mediaType, candidates),
|
|
1441
|
+
appliers: []
|
|
1442
|
+
}
|
|
1443
|
+
resourceTaskMap.set(key, entry)
|
|
1444
|
+
}
|
|
1445
|
+
entry.appliers.push(apply)
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
const collectElementTasks = (el: any) => {
|
|
1449
|
+
if (!el || typeof el !== 'object') return
|
|
1450
|
+
|
|
1451
|
+
if (el.type === 'image') {
|
|
1452
|
+
const targetUrl = (el.src || el.content || '').trim()
|
|
1453
|
+
if (/^https?:\/\//i.test(targetUrl)) {
|
|
1454
|
+
registerResource(targetUrl, 'image', undefined, dataUrl => {
|
|
1455
|
+
el.content = dataUrl
|
|
1456
|
+
delete el.src
|
|
1457
|
+
delete el.base64
|
|
1458
|
+
})
|
|
1459
|
+
}
|
|
1460
|
+
} else if (el.type === 'video') {
|
|
1461
|
+
const targetUrl = (el.src || el.content || '').trim()
|
|
1462
|
+
const candidateUrls: string[] | undefined = Array.isArray(el.__candidateUrls) ? el.__candidateUrls : undefined
|
|
1463
|
+
delete el.__candidateUrls
|
|
1464
|
+
if (/^https?:\/\//i.test(targetUrl) || (candidateUrls && candidateUrls.length > 0)) {
|
|
1465
|
+
const primary = targetUrl || candidateUrls![0]
|
|
1466
|
+
registerResource(primary, 'video', candidateUrls, dataUrl => {
|
|
1467
|
+
el.content = dataUrl
|
|
1468
|
+
delete el.src
|
|
1469
|
+
delete el.base64
|
|
1470
|
+
})
|
|
1471
|
+
}
|
|
1472
|
+
if (el.poster && typeof el.poster === 'string' && /^https?:\/\//i.test(el.poster.trim())) {
|
|
1473
|
+
const posterUrl = el.poster.trim()
|
|
1474
|
+
registerResource(posterUrl, 'image', undefined, dataUrl => {
|
|
1475
|
+
el.poster = dataUrl
|
|
1476
|
+
})
|
|
1477
|
+
}
|
|
1478
|
+
} else if (el.type === 'audio') {
|
|
1479
|
+
const targetUrl = (el.src || el.content || '').trim()
|
|
1480
|
+
const candidateUrls: string[] | undefined = Array.isArray(el.__candidateUrls) ? el.__candidateUrls : undefined
|
|
1481
|
+
delete el.__candidateUrls
|
|
1482
|
+
if (/^https?:\/\//i.test(targetUrl) || (candidateUrls && candidateUrls.length > 0)) {
|
|
1483
|
+
const primary = targetUrl || candidateUrls![0]
|
|
1484
|
+
registerResource(primary, 'audio', candidateUrls, dataUrl => {
|
|
1485
|
+
el.content = dataUrl
|
|
1486
|
+
delete el.src
|
|
1487
|
+
delete el.base64
|
|
1488
|
+
})
|
|
1489
|
+
}
|
|
1490
|
+
} else if (el.type === 'shape') {
|
|
1491
|
+
const patUrl = (el.pattern || el.style?.pattern || '').trim()
|
|
1492
|
+
if (/^https?:\/\//i.test(patUrl)) {
|
|
1493
|
+
registerResource(patUrl, 'image', undefined, dataUrl => {
|
|
1494
|
+
el.pattern = dataUrl
|
|
1495
|
+
if (el.style) el.style.pattern = dataUrl
|
|
1496
|
+
})
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
if (Array.isArray(el.elements)) {
|
|
1501
|
+
for (const child of el.elements) {
|
|
1502
|
+
collectElementTasks(child)
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
for (const slide of deck.slides) {
|
|
1508
|
+
if (!slide) continue
|
|
1509
|
+
const bg: any = slide.background
|
|
1510
|
+
if (bg && typeof bg === 'object') {
|
|
1511
|
+
const bgSrc = (bg.image?.src || bg.value || '').trim()
|
|
1512
|
+
if (/^https?:\/\//i.test(bgSrc)) {
|
|
1513
|
+
registerResource(bgSrc, 'image', undefined, dataUrl => {
|
|
1514
|
+
delete bg.value
|
|
1515
|
+
if (bg.image && typeof bg.image === 'object') {
|
|
1516
|
+
bg.image.src = dataUrl
|
|
1517
|
+
delete bg.image.base64
|
|
1518
|
+
}
|
|
1519
|
+
})
|
|
1520
|
+
}
|
|
1521
|
+
} else if (typeof bg === 'string') {
|
|
1522
|
+
const urlMatch = bg.match(/url\(['"]?(https?:\/\/[^)'"]+)['"]?\)/i)
|
|
1523
|
+
if (urlMatch && urlMatch[1]) {
|
|
1524
|
+
const rawBgUrl = urlMatch[1]
|
|
1525
|
+
registerResource(rawBgUrl, 'image', undefined, dataUrl => {
|
|
1526
|
+
slide.background = bg.replace(rawBgUrl, dataUrl)
|
|
1527
|
+
})
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
if (Array.isArray(slide.elements)) {
|
|
1532
|
+
for (const el of slide.elements) {
|
|
1533
|
+
collectElementTasks(el)
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
const uniqueEntries = Array.from(resourceTaskMap.values())
|
|
1539
|
+
const total = uniqueEntries.length
|
|
1540
|
+
if (total === 0) return deck
|
|
1541
|
+
|
|
1542
|
+
let completed = 0
|
|
1543
|
+
onProgress?.(0, total)
|
|
1544
|
+
|
|
1545
|
+
const CONCURRENCY = 6
|
|
1546
|
+
let cursor = 0
|
|
1547
|
+
const workers = Array.from({ length: Math.min(CONCURRENCY, total) }, async () => {
|
|
1548
|
+
while (cursor < total) {
|
|
1549
|
+
const currentIdx = cursor++
|
|
1550
|
+
const entry = uniqueEntries[currentIdx]
|
|
1551
|
+
if (entry) {
|
|
1552
|
+
const dataUrl = await entry.fetch()
|
|
1553
|
+
for (const apply of entry.appliers) {
|
|
1554
|
+
apply(dataUrl)
|
|
1555
|
+
}
|
|
1556
|
+
completed++
|
|
1557
|
+
onProgress?.(completed, total)
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
})
|
|
1561
|
+
|
|
1562
|
+
await Promise.all(workers)
|
|
1563
|
+
return deck
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
function stripRedundantElementBase64(el: any): any {
|
|
1567
|
+
if (!el || typeof el !== 'object') return el
|
|
1568
|
+
const cloned: any = { ...el }
|
|
1569
|
+
if (typeof cloned.content === 'string' && cloned.content.startsWith('data:')) {
|
|
1570
|
+
if (cloned.src === cloned.content) delete cloned.src
|
|
1571
|
+
if (cloned.base64 === cloned.content) delete cloned.base64
|
|
1572
|
+
} else if (typeof cloned.src === 'string' && cloned.src.startsWith('data:')) {
|
|
1573
|
+
if (cloned.base64 === cloned.src) delete cloned.base64
|
|
1574
|
+
}
|
|
1575
|
+
if (Array.isArray(cloned.elements)) {
|
|
1576
|
+
cloned.elements = cloned.elements.map(stripRedundantElementBase64)
|
|
1577
|
+
}
|
|
1578
|
+
return cloned
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
function pushPageBlobParts(page: any, parts: BlobPart[], indent = ' ') {
|
|
1582
|
+
if (!page || typeof page !== 'object') {
|
|
1583
|
+
parts.push(indent + JSON.stringify(page))
|
|
1584
|
+
return
|
|
1585
|
+
}
|
|
1586
|
+
const keys = Object.keys(page).filter(k => page[k] !== undefined)
|
|
1587
|
+
parts.push(`${indent}{\n`)
|
|
1588
|
+
keys.forEach((k, idx) => {
|
|
1589
|
+
const isLast = idx === keys.length - 1
|
|
1590
|
+
const val = page[k]
|
|
1591
|
+
const propIndent = indent + ' '
|
|
1592
|
+
if (k === 'elements' && Array.isArray(val)) {
|
|
1593
|
+
if (val.length === 0) {
|
|
1594
|
+
parts.push(`${propIndent}"elements": []${isLast ? '\n' : ',\n'}`)
|
|
1595
|
+
} else {
|
|
1596
|
+
parts.push(`${propIndent}"elements": [\n`)
|
|
1597
|
+
val.forEach((el, elIdx) => {
|
|
1598
|
+
const elComma = elIdx < val.length - 1 ? ',\n' : '\n'
|
|
1599
|
+
parts.push(propIndent + ' ' + JSON.stringify(stripRedundantElementBase64(el)) + elComma)
|
|
1600
|
+
})
|
|
1601
|
+
parts.push(`${propIndent}]${isLast ? '\n' : ',\n'}`)
|
|
1602
|
+
}
|
|
1603
|
+
} else if (k === 'layouts' && Array.isArray(val)) {
|
|
1604
|
+
if (val.length === 0) {
|
|
1605
|
+
parts.push(`${propIndent}"layouts": []${isLast ? '\n' : ',\n'}`)
|
|
1606
|
+
} else {
|
|
1607
|
+
parts.push(`${propIndent}"layouts": [\n`)
|
|
1608
|
+
val.forEach((layout, lIdx) => {
|
|
1609
|
+
pushPageBlobParts(layout, parts, propIndent + ' ')
|
|
1610
|
+
parts.push(lIdx < val.length - 1 ? ',\n' : '\n')
|
|
1611
|
+
})
|
|
1612
|
+
parts.push(`${propIndent}]${isLast ? '\n' : ',\n'}`)
|
|
1613
|
+
}
|
|
1614
|
+
} else {
|
|
1615
|
+
parts.push(`${propIndent}${JSON.stringify(k)}: ${JSON.stringify(val)}${isLast ? '\n' : ',\n'}`)
|
|
1616
|
+
}
|
|
1617
|
+
})
|
|
1618
|
+
parts.push(`${indent}}`)
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
/**
|
|
1622
|
+
* 分块流式构建包含大型 Base64 媒体的 Deck JSON Blob
|
|
1623
|
+
* 按单页/单元素粒度调用 JSON.stringify 并交由浏览器原生 Blob 拼接,彻底规避 V8 单字符串 512MB 长度上限 (RangeError: Invalid string length)
|
|
1624
|
+
*/
|
|
1625
|
+
export function stringifyDeckToBlob(deckObj: Record<string, any>): Blob {
|
|
1626
|
+
const parts: BlobPart[] = ['{\n']
|
|
1627
|
+
const keys = Object.keys(deckObj).filter(k => deckObj[k] !== undefined)
|
|
1628
|
+
keys.forEach((key, keyIdx) => {
|
|
1629
|
+
const isLastKey = keyIdx === keys.length - 1
|
|
1630
|
+
const val = deckObj[key]
|
|
1631
|
+
if ((key === 'slides' || key === 'masters' || key === 'slideMasters') && Array.isArray(val)) {
|
|
1632
|
+
if (val.length === 0) {
|
|
1633
|
+
parts.push(` ${JSON.stringify(key)}: []${isLastKey ? '\n' : ',\n'}`)
|
|
1634
|
+
} else {
|
|
1635
|
+
parts.push(` ${JSON.stringify(key)}: [\n`)
|
|
1636
|
+
val.forEach((item, itemIdx) => {
|
|
1637
|
+
pushPageBlobParts(item, parts, ' ')
|
|
1638
|
+
parts.push(itemIdx < val.length - 1 ? ',\n' : '\n')
|
|
1639
|
+
})
|
|
1640
|
+
parts.push(` ]${isLastKey ? '\n' : ',\n'}`)
|
|
1641
|
+
}
|
|
1642
|
+
} else {
|
|
1643
|
+
const formatted = JSON.stringify(val, null, 2)
|
|
1644
|
+
const indented = formatted ? formatted.replace(/\n/g, '\n ') : 'null'
|
|
1645
|
+
parts.push(` ${JSON.stringify(key)}: ${indented}${isLastKey ? '\n' : ',\n'}`)
|
|
1646
|
+
}
|
|
1647
|
+
})
|
|
1648
|
+
parts.push('}\n')
|
|
1649
|
+
return new Blob(parts, { type: 'application/json;charset=utf-8' })
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
/**
|
|
1653
|
+
* 通过本地开发代理或直接 fetch 拉取 Pitch 模板/版式库并转换为 DeckData(自动将图片/视频/音频资源转换为 Base64)
|
|
1654
|
+
*/
|
|
1655
|
+
export async function fetchAndConvertPitchTemplate(
|
|
1656
|
+
urlOrInput: string,
|
|
1657
|
+
options?: {
|
|
1658
|
+
categoryFilter?: string
|
|
1659
|
+
convertMediaToBase64?: boolean
|
|
1660
|
+
onProgress?: (completed: number, total: number) => void
|
|
1661
|
+
}
|
|
1662
|
+
): Promise<DeckData & { styleRecipes: StyleRecipe[] }> {
|
|
1663
|
+
const trimmed = (urlOrInput || '').trim()
|
|
1664
|
+
if (!trimmed) {
|
|
1665
|
+
throw new Error('请输入 Pitch 模板地址或 JSON 数据')
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
const shouldConvertMedia = options?.convertMediaToBase64 !== false
|
|
1669
|
+
|
|
1670
|
+
// 如果直接粘贴了 JSON 数组或对象文本
|
|
1671
|
+
if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
|
|
1672
|
+
const parsed = JSON.parse(trimmed)
|
|
1673
|
+
const deck = convertPitchTemplateToDeck(parsed, options)
|
|
1674
|
+
return shouldConvertMedia ? await convertDeckMediaToBase64(deck, options?.onProgress) : deck
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
const targetUrl = normalizePitchTemplateUrl(trimmed)
|
|
1678
|
+
let rawData: any = null
|
|
1679
|
+
let proxyErrorMsg = ''
|
|
1680
|
+
|
|
1681
|
+
// 优先走本地 Vite 开发中间件代理 (规避浏览器 CORS 限制)
|
|
1682
|
+
if (import.meta.env.DEV) {
|
|
1683
|
+
try {
|
|
1684
|
+
const proxyRes = await fetch(`/__pitch_proxy?url=${encodeURIComponent(targetUrl)}`)
|
|
1685
|
+
if (proxyRes.ok) {
|
|
1686
|
+
rawData = await proxyRes.json()
|
|
1687
|
+
} else {
|
|
1688
|
+
const errBody = await proxyRes.json().catch(() => null)
|
|
1689
|
+
proxyErrorMsg = errBody?.error || `代理请求返回 HTTP ${proxyRes.status}`
|
|
1690
|
+
}
|
|
1691
|
+
} catch (e: any) {
|
|
1692
|
+
proxyErrorMsg = e?.message || ''
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
// 若请求的是官方版式库 key-layouts.transit 且远程代理失败,自动回退到本地静态缓存备份
|
|
1697
|
+
if (!rawData && targetUrl.includes('key-layouts.transit')) {
|
|
1698
|
+
try {
|
|
1699
|
+
const localRes = await fetch('/templates/key-layouts.transit')
|
|
1700
|
+
if (localRes.ok) {
|
|
1701
|
+
rawData = await localRes.json()
|
|
1702
|
+
}
|
|
1703
|
+
} catch {
|
|
1704
|
+
// ignore local fallback failure
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
if (!rawData) {
|
|
1709
|
+
try {
|
|
1710
|
+
const res = await fetch(targetUrl)
|
|
1711
|
+
if (!res.ok) {
|
|
1712
|
+
throw new Error(`拉取 Pitch 数据失败 (HTTP ${res.status})`)
|
|
1713
|
+
}
|
|
1714
|
+
rawData = await res.json()
|
|
1715
|
+
} catch (err: any) {
|
|
1716
|
+
if (proxyErrorMsg) {
|
|
1717
|
+
throw new Error(`拉取失败:${proxyErrorMsg}(浏览器直连因跨域 CORS 被拦截)`)
|
|
1718
|
+
}
|
|
1719
|
+
throw err
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
const deck = convertPitchTemplateToDeck(rawData, options)
|
|
1724
|
+
return shouldConvertMedia ? await convertDeckMediaToBase64(deck, options?.onProgress) : deck
|
|
1725
|
+
}
|