-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
619 lines (571 loc) · 35.7 KB
/
Copy pathindex.html
File metadata and controls
619 lines (571 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG Animate Editor - 科普动画一站式制作平台</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
darkBg: '#090d16',
panelBg: '#111827',
borderCool: '#1f2937',
accentBlue: '#3b82f6',
accentGreen: '#10b981',
accentPurple: '#8b5cf6',
}
}
}
}
</script>
<style>
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: #090d16; }
::-webkit-scrollbar-thumb { background: #1f2937; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #374151; }
.animate-pulse-slow { animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
</style>
</head>
<body class="bg-darkBg text-gray-100 font-sans min-h-screen flex flex-col overflow-hidden">
<header class="bg-panelBg border-b border-borderCool px-6 py-3 flex items-center justify-between z-10">
<div class="flex items-center space-x-3">
<div class="w-8 h-8 rounded-lg bg-gradient-to-tr from-accentBlue to-accentPurple flex items-center justify-center font-bold text-white shadow-lg">S</div>
<div>
<h1 class="text-lg font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">SVG Animate Studio</h1>
<p class="text-xs text-gray-400">科普视频代码动画一站式生成器</p>
</div>
</div>
<div class="flex items-center space-x-4">
<span class="flex items-center space-x-2 text-xs bg-gray-800 px-3 py-1.5 rounded-full text-gray-300 border border-borderCool">
<span class="w-2 h-2 rounded-full bg-accentGreen animate-ping"></span>
<span>核心驱动正常运行</span>
</span>
<button id="toggleConfigBtn" class="bg-blue-600 hover:bg-blue-500 text-white text-xs px-3 py-1.5 rounded transition font-medium flex items-center space-x-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
<span>API 接口设置</span>
</button>
</div>
</header>
<main class="flex-1 flex overflow-hidden">
<section id="sidebarLeft" class="w-80 bg-panelBg border-r border-borderCool flex flex-col flex-shrink-0">
<div id="apiConfigPanel" class="hidden p-4 border-b border-borderCool bg-gray-900/50">
<div class="flex items-center justify-between mb-3">
<h3 class="text-sm font-semibold text-blue-400">API 接口端点配置</h3>
</div>
<div class="space-y-3 text-xs">
<div>
<label class="block text-gray-400 mb-1">选择服务商</label>
<select id="apiProvider" class="w-full bg-darkBg border border-borderCool p-1.5 rounded text-gray-200">
<option value="deepseek">DeepSeek</option>
<option value="github-models">GitHub Models (免费测试)</option>
<option value="zhipu">智谱清言 (GLM)</option>
<option value="minimax">MiniMax</option>
<option value="openai">OpenAI</option>
<option value="openrouter">OpenRouter</option>
</select>
</div>
<div>
<label class="block text-gray-400 mb-1">API Endpoint URL</label>
<input id="apiEndpoint" type="text" placeholder="https://api.deepseek.com/v1" class="w-full bg-darkBg border border-borderCool p-1.5 rounded text-gray-200">
</div>
<div>
<label class="block text-gray-400 mb-1">API Key / Token</label>
<input id="apiKey" type="password" placeholder="sk-****** 或 ghp_******" class="w-full bg-darkBg border border-borderCool p-1.5 rounded text-gray-200">
</div>
<div>
<label class="block text-gray-400 mb-1">模型名称 (Model)</label>
<input id="apiModel" type="text" placeholder="deepseek-chat" class="w-full bg-darkBg border border-borderCool p-1.5 rounded text-gray-200">
</div>
<button id="saveConfigBtn" class="w-full bg-accentGreen hover:bg-emerald-600 text-white font-semibold py-1 rounded text-xs transition">保存配置</button>
</div>
</div>
<div class="flex-1 flex flex-col p-4 overflow-y-auto space-y-4">
<div>
<h3 class="text-sm font-semibold text-gray-200 mb-1">1. 粘贴视频配音文案</h3>
<textarea id="rawScriptText" placeholder="在此粘贴你的整篇科普视频文案。支持万字长文..." class="w-full h-80 bg-darkBg border border-borderCool p-2.5 rounded text-xs leading-relaxed resize-none"></textarea>
</div>
<button id="chunkScriptBtn" class="w-full bg-accentBlue hover:bg-blue-500 text-white font-semibold py-2 rounded text-xs transition flex items-center justify-center space-x-2">
<span>第一步:开始拆分分镜头</span>
</button>
<div id="processingStatus" class="hidden border border-borderCool bg-gray-900/80 p-3 rounded text-xs space-y-2">
<div class="flex items-center justify-between">
<span class="text-gray-400">分镜脚本解析进度</span>
<span id="progressPercent" class="text-accentBlue font-bold">0%</span>
</div>
<div class="w-full bg-gray-800 h-1.5 rounded-full overflow-hidden">
<div id="progressBar" class="bg-accentBlue h-full w-0 transition-all duration-300"></div>
</div>
<div id="statusLog" class="text-[10px] text-gray-500 italic max-h-16 overflow-y-auto">准备解析文案段落...</div>
</div>
</div>
</section>
<section class="flex-1 flex flex-col border-r border-borderCool overflow-hidden">
<div class="h-1/2 border-b border-borderCool flex flex-col overflow-hidden">
<div class="bg-gray-900 px-4 py-2 border-b border-borderCool flex items-center justify-between">
<h3 class="text-xs font-bold text-gray-400">分镜脚本工作台(双击文本可快速微调修改)</h3>
<span id="sceneCountText" class="text-[10px] text-gray-500">共 0 个分镜</span>
</div>
<div id="sceneCardContainer" class="flex-1 overflow-x-auto flex p-4 space-x-4 items-start bg-darkBg">
<div class="text-xs text-gray-500 text-center w-full py-12">暂无分镜脚本,请在左侧粘贴视频文案并点击“开始拆分分镜头”</div>
</div>
</div>
<div class="h-1/2 flex flex-col overflow-hidden bg-panelBg">
<div class="bg-gray-900 px-4 py-2 border-b border-borderCool flex items-center justify-between">
<h3 class="text-xs font-bold text-gray-400">当前场景代码编辑器 (<span id="editingSceneTitle" class="text-accentBlue">未选中任何场景</span>)</h3>
<button id="updatePreviewBtn" class="bg-accentGreen hover:bg-emerald-600 text-white text-[11px] px-3 py-1 rounded transition font-semibold">更新动画预览</button>
</div>
<div class="flex-1 flex overflow-hidden text-xs">
<div class="w-1/2 border-r border-borderCool flex flex-col">
<div class="bg-gray-900/80 px-3 py-1 text-[10px] text-gray-500 border-b border-borderCool">SVG 结构布局</div>
<textarea id="svgCodeEditor" class="flex-1 w-full bg-darkBg text-emerald-400 font-mono p-3 resize-none border-0"></textarea>
</div>
<div class="w-1/2 flex flex-col">
<div class="bg-gray-900/80 px-3 py-1 text-[10px] text-gray-500 border-b border-borderCool">GSAP 物理轨迹代码 (JavaScript)</div>
<textarea id="gsapCodeEditor" class="flex-1 w-full bg-darkBg text-blue-400 font-mono p-3 resize-none border-0"></textarea>
</div>
</div>
</div>
</section>
<section class="w-[450px] bg-panelBg flex flex-col flex-shrink-0 overflow-hidden">
<div class="p-4 border-b border-borderCool">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-bold text-gray-400">16:9 物理轨迹沙盒窗口</span>
<span class="text-[10px] text-gray-500">1920 × 1080 适配</span>
</div>
<div class="relative w-full aspect-video bg-black rounded border border-borderCool overflow-hidden shadow-2xl">
<iframe id="previewSandbox" class="w-full h-full bg-transparent border-0" sandbox="allow-scripts allow-same-origin"></iframe>
</div>
<div class="mt-3 flex items-center space-x-3 text-xs">
<button id="playAnimationBtn" class="bg-gray-800 hover:bg-gray-700 p-1.5 rounded text-gray-300">播放</button>
<button id="pauseAnimationBtn" class="bg-gray-800 hover:bg-gray-700 p-1.5 rounded text-gray-300">暂停</button>
<div class="flex-1 flex items-center space-x-2">
<input id="animationTimelineScrubber" type="range" min="0" max="100" value="0" class="w-full h-1 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-500">
<span id="durationDisplay" class="text-[10px] text-gray-500 font-mono">0.0s / 0.0s</span>
</div>
</div>
</div>
<div class="flex-1 flex flex-col overflow-hidden border-t border-borderCool">
<div class="bg-gray-900 px-4 py-2 border-b border-borderCool flex items-center justify-between">
<h3 class="text-xs font-bold text-gray-400">AI 伴跑师 (单独调教当前分镜代码)</h3>
</div>
<div id="aiChatBubbleHistory" class="flex-1 p-4 overflow-y-auto space-y-3 text-xs">
<div class="bg-gray-800/40 p-3 rounded-lg border border-borderCool">
<p class="text-gray-300">👋 <b>你好!我是你的高级 SVG-GSAP 动画调教助手。</b></p>
</div>
</div>
<div class="p-3 bg-gray-900 border-t border-borderCool flex items-center space-x-2">
<input id="aiChatInputText" type="text" placeholder="对 AI 说:把核心节点变成蓝色闪烁效果..." class="flex-1 bg-darkBg border border-borderCool px-3 py-2 rounded text-xs">
<button id="sendAiChatBtn" class="bg-accentPurple hover:bg-fuchsia-700 text-white text-xs px-4 py-2 rounded font-semibold">发送</button>
</div>
</div>
</section>
</main>
<div id="toastNotification" class="fixed bottom-6 right-6 z-50 bg-gray-900 border border-borderCool text-gray-200 text-xs px-4 py-3 rounded-lg shadow-2xl hidden max-w-sm">
<div class="flex items-center space-x-3">
<span id="toastIcon">💡</span>
<p id="toastMsg" class="font-medium"></p>
</div>
</div>
<script>
let appState = {
apiConfig: { provider: 'deepseek', endpoint: 'https://api.deepseek.com/v1', key: '', model: 'deepseek-chat' },
storyboard: [],
activeSceneIndex: null
};
// ========== 辅助函数 ==========
function showToast(message, icon = "💡") {
const toast = document.getElementById('toastNotification');
document.getElementById('toastMsg').innerText = message;
document.getElementById('toastIcon').innerText = icon;
toast.classList.remove('hidden');
setTimeout(() => toast.classList.add('hidden'), 4000);
}
function escapeHtml(str) {
if (!str) return '';
return str.replace(/[&<>]/g, function(m) {
if (m === '&') return '&';
if (m === '<') return '<';
if (m === '>') return '>';
return m;
});
}
function updateTimelineProgressLabel(progress) {
if (appState.activeSceneIndex === null) return;
const duration = appState.storyboard[appState.activeSceneIndex].duration;
document.getElementById('durationDisplay').innerText = `${(progress * duration).toFixed(1)}s / ${duration.toFixed(1)}s`;
}
// 进度条更新函数(供 iframe 回调)
window.navigatorUpdateLabel = function(progress) {
const scrubber = document.getElementById('animationTimelineScrubber');
if (scrubber) scrubber.value = Math.round(progress * 100);
updateTimelineProgressLabel(progress);
};
// ========== API 配置相关 ==========
function loadConfigFromLocalStorage() {
const cached = localStorage.getItem('svg_animate_api_config');
if (cached) {
appState.apiConfig = JSON.parse(cached);
document.getElementById('apiProvider').value = appState.apiConfig.provider || 'deepseek';
document.getElementById('apiEndpoint').value = appState.apiConfig.endpoint || '';
document.getElementById('apiKey').value = appState.apiConfig.key || '';
document.getElementById('apiModel').value = appState.apiConfig.model || '';
} else {
updateProviderDefaults('deepseek');
}
}
function saveConfigToLocalStorage() {
appState.apiConfig.provider = document.getElementById('apiProvider').value;
appState.apiConfig.endpoint = document.getElementById('apiEndpoint').value;
appState.apiConfig.key = document.getElementById('apiKey').value;
appState.apiConfig.model = document.getElementById('apiModel').value;
localStorage.setItem('svg_animate_api_config', JSON.stringify(appState.apiConfig));
showToast("✅ API 配置保存成功!", "🟢");
}
function updateProviderDefaults(provider) {
const endpoint = document.getElementById('apiEndpoint');
const model = document.getElementById('apiModel');
switch(provider) {
case 'deepseek':
endpoint.value = "https://api.deepseek.com/v1"; model.value = "deepseek-chat"; break;
case 'github-models':
endpoint.value = "https://models.inference.ai.azure.com"; model.value = "gpt-4o-mini"; break;
case 'zhipu':
endpoint.value = "https://open.bigmodel.cn/api/paas/v4"; model.value = "glm-4-flash"; break;
case 'minimax':
endpoint.value = "https://api.minimax.chat/v1"; model.value = "abab6.5-chat"; break;
case 'openai':
endpoint.value = "https://api.openai.com/v1"; model.value = "gpt-4o-mini"; break;
case 'openrouter':
endpoint.value = "https://openrouter.ai/api/v1"; model.value = "google/gemini-pro-1.5"; break;
}
}
async function fetchChatCompletions(messages) {
const config = appState.apiConfig;
const headers = { "Content-Type": "application/json" };
if (config.key) {
headers["Authorization"] = `Bearer ${config.key}`;
}
let url = config.endpoint;
if (!url.endsWith('/chat/completions')) {
url = url.replace(/\/$/, '') + '/chat/completions';
}
const response = await fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify({
model: config.model,
messages: messages,
temperature: 0.2
})
});
if (!response.ok) throw new Error(`API 请求失败: ${response.status}`);
const data = await response.json();
return data.choices[0].message.content;
}
function cleanJsonMarkdown(text) {
let clean = text.trim();
if (clean.startsWith('```json')) clean = clean.substring(7);
else if (clean.startsWith('```')) clean = clean.substring(3);
if (clean.endsWith('```')) clean = clean.substring(0, clean.length - 3);
return clean.trim();
}
// ========== 分镜处理 ==========
function chunkTextIntoSegments(text, limit = 2000) {
const segments = [];
let remaining = text.trim();
while (remaining.length > 0) {
if (remaining.length <= limit) {
segments.push(remaining);
break;
}
let chunk = remaining.substring(0, limit);
let lastNewline = chunk.lastIndexOf('\n');
if (lastNewline > 0) {
segments.push(remaining.substring(0, lastNewline).trim());
remaining = remaining.substring(lastNewline).trim();
} else {
let lastPunct = Math.max(chunk.lastIndexOf('。'), chunk.lastIndexOf('?'), chunk.lastIndexOf('!'));
if (lastPunct > 0) {
segments.push(remaining.substring(0, lastPunct + 1).trim());
remaining = remaining.substring(lastPunct + 1).trim();
} else {
segments.push(remaining.substring(0, limit).trim());
remaining = remaining.substring(limit).trim();
}
}
}
return segments;
}
async function requestStoryboardFromLLM(textChunk, current, total) {
const sysPrompt = `你是一个顶级科普分镜师。请把这段文案切分为适合科技/理学网格、图表动画的场景卡。必须返回严格的 JSON 数组格式,没有任何 Markdown 标记:
[{"text": "配音原文", "visualDescription": "画面图形运动创意描述"}]
不要返回任何别的东西。以下是文案:\n${textChunk}`;
const messages = [{ role: 'user', content: sysPrompt }];
const res = await fetchChatCompletions(messages);
return cleanJsonMarkdown(res);
}
async function handleScriptChunkingAndParsing() {
const rawText = document.getElementById('rawScriptText').value.trim();
if (!rawText) { showToast("❌ 请先粘贴文案!", "🔴"); return; }
if (!appState.apiConfig.key) { showToast("🔑 请先配置 API Key!", "🟡"); document.getElementById('apiConfigPanel').classList.remove('hidden'); return; }
const chunks = chunkTextIntoSegments(rawText, 2000);
const statusPanel = document.getElementById('processingStatus');
const bar = document.getElementById('progressBar');
const percent = document.getElementById('progressPercent');
const log = document.getElementById('statusLog');
statusPanel.classList.remove('hidden');
appState.storyboard = [];
renderStoryboardList();
for (let i = 0; i < chunks.length; i++) {
let pct = Math.round((i / chunks.length) * 100);
bar.style.width = `${pct}%`;
percent.innerText = `${pct}%`;
log.innerHTML += `<br>[请求中...] 正在解析第 ${i+1}/${chunks.length} 块文案...`;
log.scrollTop = log.scrollHeight;
try {
const sceneJson = await requestStoryboardFromLLM(chunks[i], i+1, chunks.length);
const parsed = JSON.parse(sceneJson);
parsed.forEach(scene => {
let duration = parseFloat(((scene.text || "").length / 3.3).toFixed(1));
appState.storyboard.push({
id: appState.storyboard.length + 1,
text: scene.text || "",
visualDescription: scene.visualDescription || "科技蓝色创意抽象背景",
duration: duration > 2 ? duration : 5,
svg: "",
css: "",
js: "",
chatHistory: []
});
});
renderStoryboardList();
} catch (err) {
log.innerHTML += `<br><span class="text-red-500">[错误] 第 ${i+1} 块解析失败: ${err.message}</span>`;
}
}
bar.style.width = '100%';
percent.innerText = '100%';
log.innerHTML += `<br>🎉 分镜拆分完成!`;
showToast("🎉 脚本分镜切分成功!", "🟢");
}
// ========== 场景卡片渲染与交互 ==========
function renderStoryboardList() {
const container = document.getElementById('sceneCardContainer');
const countSpan = document.getElementById('sceneCountText');
countSpan.innerText = `共 ${appState.storyboard.length} 个分镜`;
if (appState.storyboard.length === 0) {
container.innerHTML = `<div class="text-xs text-gray-500 text-center w-full py-12">暂无分镜脚本</div>`;
return;
}
container.innerHTML = '';
appState.storyboard.forEach((scene, idx) => {
const isActive = (appState.activeSceneIndex === idx);
const card = document.createElement('div');
card.className = `scene-card w-72 flex-shrink-0 bg-panelBg border-2 p-3 rounded-lg flex flex-col justify-between transition-all ${isActive ? 'border-accentBlue ring-2 ring-blue-900/40' : 'border-borderCool'}`;
card.dataset.index = idx;
card.style.height = '210px';
card.innerHTML = `
<div class="flex justify-between items-center text-[10px] font-bold text-gray-400 mb-1">
<span>场景 #${scene.id}</span>
<div><input type="number" step="0.1" value="${scene.duration}" class="duration-input w-10 bg-darkBg border border-borderCool text-center rounded text-[10px]" data-index="${idx}"> 秒</div>
</div>
<div class="flex-1 overflow-y-auto text-[11px] text-gray-300 space-y-1 cursor-pointer select-text" data-select="${idx}">
<div class="scene-text line-clamp-3" data-field="text" data-index="${idx}">${escapeHtml(scene.text)}</div>
<div class="text-gray-400 italic bg-darkBg p-1 rounded line-clamp-2" data-field="visualDescription" data-index="${idx}">🎥 ${escapeHtml(scene.visualDescription)}</div>
</div>
<div class="flex justify-between items-center mt-2 pt-2 border-t border-borderCool">
<span class="text-[9px] ${scene.svg ? 'text-accentGreen':'text-yellow-600'}">${scene.svg ? '● 已有动画':'○ 待生成'}</span>
<button class="generate-btn bg-accentBlue text-white text-[10px] px-2 py-0.5 rounded" data-index="${idx}">生成动画</button>
</div>
`;
container.appendChild(card);
});
}
function updateSceneDuration(index, value) {
if (appState.storyboard[index]) {
appState.storyboard[index].duration = parseFloat(value) || 5;
}
}
function editSceneText(index, field) {
const newVal = prompt(`编辑 ${field === 'text' ? '配音文案' : '画面描述'}`, appState.storyboard[index][field]);
if (newVal !== null && newVal.trim() !== '') {
appState.storyboard[index][field] = newVal.trim();
renderStoryboardList();
if (appState.activeSceneIndex === index) {
document.getElementById('editingSceneTitle').innerText = `分镜场景 #${appState.storyboard[index].id}`;
}
}
}
function selectActiveScene(index) {
if (index < 0 || index >= appState.storyboard.length) return;
appState.activeSceneIndex = index;
const scene = appState.storyboard[index];
document.getElementById('editingSceneTitle').innerText = `分镜场景 #${scene.id}`;
document.getElementById('svgCodeEditor').value = scene.svg || '';
document.getElementById('gsapCodeEditor').value = scene.js || '';
renderStoryboardList();
applyEditorCodeToSandbox();
}
async function generateAnimationForScene(index) {
if (!appState.apiConfig.key) {
showToast("🔑 请先配置 API Key!", "🟡");
document.getElementById('apiConfigPanel').classList.remove('hidden');
return;
}
selectActiveScene(index);
const scene = appState.storyboard[index];
showToast(`🚀 正在让 AI 编写动画代码...`, "🔮");
const prompt = `你是一个精通 SVG 和 GSAP 3 物理动效的专家。请根据以下画面描述,编写能在 16:9 画布自适应的动画包。
描述:${scene.visualDescription}
时长要求:必须在整个动画的持续内均匀播放完毕(持续时长大约为:${scene.duration}秒)。
必须定义且只能定义全局时间轴:window.__timeline = gsap.timeline({ paused: true }); 所有运动Tween追加在此之上。
必须返回以下严格格式的 JSON 字符串:
{"svg": "<svg viewBox=\\"0 0 1920 1080\\">...</svg>", "css": "样式", "js": "window.__timeline = ...;"}
不要返回任何多余文字。`;
try {
const res = await fetchChatCompletions([{ role: 'user', content: prompt }]);
const parsed = JSON.parse(cleanJsonMarkdown(res));
scene.svg = parsed.svg || "";
scene.css = parsed.css || "";
scene.js = parsed.js || "";
document.getElementById('svgCodeEditor').value = scene.svg;
document.getElementById('gsapCodeEditor').value = scene.js;
renderStoryboardList();
applyEditorCodeToSandbox();
showToast("🎉 动画代码已装载!", "🟢");
} catch (err) {
console.error(err);
showToast("❌ 格式解析失败,请点击重新生成", "🔴");
}
}
// ========== 沙盒与预览 ==========
let sandboxTemplate = "";
function initSandboxTemplate() {
sandboxTemplate = `<!DOCTYPE html><html><head><style>html,body{margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#090d16;display:flex;justify-content:center;align-items:center;}{CSS}</style><script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js"><\/script><script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/TextPlugin.min.js"><\/script><script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/MotionPathPlugin.min.js"><\/script></head><body><div style="width:100%;height:100%;">{SVG}</div><script>gsap.registerPlugin(TextPlugin,MotionPathPlugin);window.__timeline=gsap.timeline({paused:true});window.addEventListener('message',(e)=>{const d=e.data;if(d.type==='seek')window.__timeline.progress(d.progress);else if(d.type==='play')window.__timeline.play();else if(d.type==='pause')window.__timeline.pause();});window.__timeline.eventCallback("onUpdate",()=>{window.parent.postMessage({type:'onUpdate',progress:window.__timeline.progress()},'*');});try{{JS}}catch(err){console.error(err);}<\/script></body></html>`;
window.addEventListener('message', (e) => {
if (e.data && e.data.type === 'onUpdate') {
window.navigatorUpdateLabel(e.data.progress);
}
});
}
function applyEditorCodeToSandbox() {
if (appState.activeSceneIndex === null) return;
const scene = appState.storyboard[appState.activeSceneIndex];
const svg = document.getElementById('svgCodeEditor').value;
const js = document.getElementById('gsapCodeEditor').value;
let src = sandboxTemplate.replace('{CSS}', scene.css || "").replace('{SVG}', svg).replace('{JS}', js);
document.getElementById('previewSandbox').srcdoc = src;
updateTimelineProgressLabel(0);
}
function sendToSandbox(msg) {
const frame = document.getElementById('previewSandbox');
if (frame && frame.contentWindow) frame.contentWindow.postMessage(msg, '*');
}
// ========== AI 调教对话 ==========
function appendChatBubble(role, text) {
const container = document.getElementById('aiChatBubbleHistory');
const div = document.createElement('div');
div.className = role === 'user' ? 'bg-blue-900/20 p-2 rounded border border-blue-800/40 ml-4' : 'bg-purple-900/10 p-2 rounded border border-purple-800/40 mr-4';
div.innerHTML = `<b>${role === 'user' ? '我' : 'AI'}:</b> ${text.replace(/\n/g, '<br>')}`;
container.appendChild(div);
container.scrollTop = container.scrollHeight;
return div;
}
async function sendAiChatMessage() {
if (appState.activeSceneIndex === null) {
showToast("👉 请先选中一个分镜场景", "🟡");
return;
}
const input = document.getElementById('aiChatInputText');
const userMsg = input.value.trim();
if (!userMsg) return;
appendChatBubble('user', userMsg);
input.value = "";
const thinkingDiv = appendChatBubble('assistant', '思考修改中...');
const scene = appState.storyboard[appState.activeSceneIndex];
const prompt = `当前SVG:\n${scene.svg}\n当前JS:\n${scene.js}\n用户修改意见:${userMsg}\n请修改并最终在尾部附带 \`\`\`json 格式的完整代码块,包含 svg, css, js 三项。`;
try {
const res = await fetchChatCompletions([{ role: 'user', content: prompt }]);
const jsonMatch = res.match(/```json\s*([\s\S]*?)\s*```/);
if (jsonMatch && jsonMatch[1]) {
const parsed = JSON.parse(jsonMatch[1].trim());
scene.svg = parsed.svg;
scene.css = parsed.css;
scene.js = parsed.js;
document.getElementById('svgCodeEditor').value = scene.svg;
document.getElementById('gsapCodeEditor').value = scene.js;
applyEditorCodeToSandbox();
renderStoryboardList();
thinkingDiv.innerHTML = `<b>AI:</b> ${res.split('```json')[0].replace(/\n/g, '<br>')}`;
} else {
thinkingDiv.innerHTML = `<b>AI:</b> 未能提取代码块,请重试。`;
}
} catch(e) {
console.error(e);
thinkingDiv.innerHTML = `<b>AI:</b> ❌ 调教失败,请再试一次`;
}
}
// ========== 事件绑定 ==========
function setupEventListeners() {
document.getElementById('toggleConfigBtn').addEventListener('click', () => {
document.getElementById('apiConfigPanel').classList.toggle('hidden');
});
document.getElementById('saveConfigBtn').addEventListener('click', saveConfigToLocalStorage);
document.getElementById('apiProvider').addEventListener('change', (e) => updateProviderDefaults(e.target.value));
document.getElementById('chunkScriptBtn').addEventListener('click', handleScriptChunkingAndParsing);
document.getElementById('updatePreviewBtn').addEventListener('click', applyEditorCodeToSandbox);
document.getElementById('playAnimationBtn').addEventListener('click', () => sendToSandbox({type: 'play'}));
document.getElementById('pauseAnimationBtn').addEventListener('click', () => sendToSandbox({type: 'pause'}));
document.getElementById('animationTimelineScrubber').addEventListener('input', (e) => {
const progress = e.target.value / 100;
sendToSandbox({type: 'seek', progress: progress});
updateTimelineProgressLabel(progress);
});
document.getElementById('sendAiChatBtn').addEventListener('click', sendAiChatMessage);
document.getElementById('aiChatInputText').addEventListener('keydown', (e) => {
if (e.key === 'Enter') sendAiChatMessage();
});
// 卡片容器事件委托
const container = document.getElementById('sceneCardContainer');
container.addEventListener('click', (e) => {
const generateBtn = e.target.closest('.generate-btn');
if (generateBtn) {
const idx = parseInt(generateBtn.dataset.index);
if (!isNaN(idx)) generateAnimationForScene(idx);
return;
}
const selectDiv = e.target.closest('[data-select]');
if (selectDiv) {
const idx = parseInt(selectDiv.dataset.select);
if (!isNaN(idx)) selectActiveScene(idx);
return;
}
const textDiv = e.target.closest('[data-field]');
if (textDiv) {
const idx = parseInt(textDiv.dataset.index);
const field = textDiv.dataset.field;
if (!isNaN(idx) && field) editSceneText(idx, field);
return;
}
});
container.addEventListener('change', (e) => {
const durationInput = e.target.closest('.duration-input');
if (durationInput) {
const idx = parseInt(durationInput.dataset.index);
if (!isNaN(idx)) updateSceneDuration(idx, durationInput.value);
}
});
}
// ========== 初始化 ==========
document.addEventListener('DOMContentLoaded', () => {
loadConfigFromLocalStorage();
setupEventListeners();
initSandboxTemplate();
showToast("🚀 平台加载完毕,按钮已就绪!", "🟢");
});
</script>
</body>
</html>