@lumesync/studio 0.0.0-stage → 1.0.0

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/ui/app.js ADDED
@@ -0,0 +1,2671 @@
1
+ // 浏览器 Studio:场景树 + 沙箱预览 + 可编辑属性面板 + 实时事件。
2
+ // 会话凭证由入口页下发 HttpOnly Cookie 并在内存中读取会话状态,不写 URL 或 localStorage。
3
+
4
+ import {
5
+ buildCoursewarePatch, buildInteractionPatch, buildScenePatch, nextOperationId,
6
+ } from '/ui/shared/edit-model.js';
7
+
8
+ const SUBJECTS = ['信息科技', '信息技术', '人工智能', '通用技术', '跨学科'];
9
+ // 组件说明表:用于结构 tab 的下半部分,回答“它是什么、干什么用、能配置什么”。
10
+ // props 是 manifest 中的静态配置,具体字段由各组件自己的 propsSchema 校验。
11
+ const COMPONENT_CATALOG = {
12
+ 'lume-code': { label: '代码编辑器', purpose: '编写、高亮与对比代码,适合讲解语法和改错。', props: ['lang 语言', 'run 运行入口', 'lineNumbers 行号', 'readOnly 只读'] },
13
+ 'lume-run': { label: '代码运行器', purpose: '在本机执行 Python 等代码并展示输出。', props: ['runtime 运行时', 'entry 入口', 'showOutput 输出区'] },
14
+ 'lume-blocks': { label: '积木编程', purpose: '用图形化积木搭建程序,降低语法门槛。', props: ['toolbox 积木分类', 'workspace 初始积木'] },
15
+ 'lume-vars': { label: '变量盒', purpose: '逐步展示循环或递归中变量的变化。', props: ['code 关联代码 cid', 'watch 观察变量'] },
16
+ 'lume-sheet': { label: '表格', purpose: '录入、计算与分析数据,练习公式和统计。', props: ['data 初始数据', 'editableRange 可编辑区域'] },
17
+ 'lume-doc': { label: '文档', purpose: '阅读或编辑文字材料,完成写作类任务。', props: ['content 初始内容', 'editable 可编辑'] },
18
+ 'lume-board': { label: '板书', purpose: '画流程图、思维导图或开展协作板书。', props: ['template 画板模板', 'readOnly 只读'] },
19
+ 'lume-chart': { label: '图表', purpose: '把数据画成折线、柱状等图表并观察趋势。', props: ['chartType 图表类型', 'data 数据', 'xField / yField 轴字段'] },
20
+ 'lume-graph': { label: '图网络', purpose: '展示节点与连线,如网络拓扑和图结构。', props: ['nodes 节点', 'edges 连边', 'layout 布局'] },
21
+ 'lume-3d': { label: '三维场景', purpose: '查看三维模型或物联网设备结构。', props: ['model 模型资源', 'camera 初始视角'] },
22
+ 'lume-sim': { label: '参数仿真', purpose: '调节参数并观察过程与结果如何变化。', props: ['model 仿真内核', 'params 可调参数', 'range 取值范围'] },
23
+ 'lume-quiz': { label: '题目', purpose: '承载选择、填空等练习并自动判分。', props: ['ref 关联题目 id', 'mode 作答模式'] },
24
+ 'lume-hotspot': { label: '热区标注', purpose: '在界面上点选区域,完成识别或标注。', props: ['image 底图', 'hotspots 热区定义'] },
25
+ 'lume-terminal': { label: '终端', purpose: '练习命令行操作并解读输出。', props: ['cwd 工作目录', 'commands 允许命令', 'readOnly 只读'] },
26
+ 'lume-timer': { label: '计时器', purpose: '为讨论或限时活动提供计时。', props: ['durationSec 时长', 'autoStart 自动开始', 'mode 计时/倒计时'] },
27
+ 'lume-ai': { label: 'AI 助教', purpose: '在场景内回答与当前内容相关的问题。', props: ['prompt 场景提示词', 'scope 可回答范围'] },
28
+ };
29
+ const ROLE_LABELS = { primary: '主要交互', support: '辅助', reference: '参考资料' };
30
+ const COLLECT_LABELS = { none: '不采集', onDemand: '按需', onSubmit: '提交时', periodic: '周期性' };
31
+ const ASPECT_RATIOS = ['16:9', '4:3', '16:10', '21:9', '1:1'];
32
+
33
+ const state = {
34
+ session: null,
35
+ document: null,
36
+ sceneIndex: 0,
37
+ socket: null,
38
+ lastRenderedRevision: null,
39
+ pendingStates: {},
40
+ lastCapturedStates: {},
41
+ frameSignature: '',
42
+ frameSceneId: null,
43
+ frameLoadToken: 0,
44
+ sceneHashes: new Map(),
45
+ sceneItems: new Map(),
46
+ dragSceneId: null,
47
+ staleScenes: new Set(),
48
+ forceRebuild: false,
49
+ previewClients: 0,
50
+ confirmation: null,
51
+ connected: false,
52
+ pendingImport: null,
53
+ inspectorCollapsed: false,
54
+ inspectorTab: 'structure',
55
+ sourceMode: false,
56
+ sourceSceneId: null,
57
+ sourceOriginal: '',
58
+ sourceRequest: 0,
59
+ sourceSaving: false,
60
+ sourceQueued: false,
61
+ sourceDrafts: new Map(),
62
+ sourceCache: new Map(),
63
+ structureCache: new Map(),
64
+ structurePending: new Set(),
65
+ structureErrors: new Map(),
66
+ undoStack: [],
67
+ redoStack: [],
68
+ editBusy: false,
69
+ chatOpen: false,
70
+ chatMessages: [],
71
+ chatIds: new Set(),
72
+ chatClaimed: new Set(),
73
+ chatCursor: 0,
74
+ chatSelection: null,
75
+ chatPicking: false,
76
+ chatSending: false,
77
+ chatTimer: null,
78
+ chatUnread: 0,
79
+ };
80
+
81
+ const el = (id) => document.getElementById(id);
82
+
83
+ // 浏览器冒烟使用:?debug=1 时暴露只读状态钩子,便于断言状态恢复。
84
+ if (new URLSearchParams(location.search).has('debug')) {
85
+ window.__lumeStudioDebug = state;
86
+ // 供冒烟测试触发一次强制重建(原先由“重载场景”按钮提供)。
87
+ window.__lumeStudioRebuild = () => renderScene({ force: true });
88
+ }
89
+
90
+ async function api(path, options = {}) {
91
+ const headers = { ...(options.headers ?? {}) };
92
+ if (options.body !== undefined) headers['content-type'] = 'application/json';
93
+ const response = await fetch(path, { ...options, headers, credentials: 'same-origin' });
94
+ const text = await response.text();
95
+ let value = null;
96
+ try {
97
+ value = text ? JSON.parse(text) : null;
98
+ } catch {
99
+ value = { error: { code: 'BAD_RESPONSE', message: text.slice(0, 200) } };
100
+ }
101
+ if (!response.ok) {
102
+ const error = new Error(value?.error?.message ?? `HTTP ${response.status}`);
103
+ error.code = value?.error?.code;
104
+ error.details = value?.error?.details;
105
+ throw error;
106
+ }
107
+ return value;
108
+ }
109
+
110
+ async function boot() {
111
+ bindControls();
112
+ applyInspectorState();
113
+ observePreviewSize();
114
+ state.session = await api('/api/session');
115
+ await loadDocument();
116
+ connectSocket();
117
+ loadChat().catch(() => {});
118
+ setInterval(() => {
119
+ if (state.socket) state.socket.send(JSON.stringify({ type: 'ping' }));
120
+ }, 25000);
121
+ }
122
+
123
+ // 右侧属性区可收起为窄条,把宽度让给预览。
124
+ function toggleInspector() {
125
+ state.inspectorCollapsed = !state.inspectorCollapsed;
126
+ applyInspectorState();
127
+ }
128
+
129
+ function applyInspectorState() {
130
+ const layout = document.querySelector('.layout');
131
+ if (!layout) return;
132
+ layout.classList.toggle('inspector-collapsed', state.inspectorCollapsed);
133
+ const button = el('toggleInspector');
134
+ const label = state.inspectorCollapsed ? '展开面板' : '收起面板';
135
+ button.title = label;
136
+ button.setAttribute('aria-label', label);
137
+ button.setAttribute('aria-expanded', String(!state.inspectorCollapsed));
138
+ }
139
+
140
+ function setInspectorTab(tab) {
141
+ if (state.inspectorTab === tab) return;
142
+ state.inspectorTab = tab;
143
+ renderInspector();
144
+ }
145
+
146
+ // 左侧幻灯片栏与预览之间的竖线即拖拽手柄。
147
+ // 宽度只保存在当前页面样式里,不写入浏览器存储。
148
+ const PANEL_LIMITS = {
149
+ scene: { min: 160, max: 420 },
150
+ inspector: { min: 240, max: 460 },
151
+ };
152
+
153
+ // 左右两侧的分隔线共用同一套拖拽逻辑。
154
+ // invert 为真表示手柄在面板左侧:向左拖动才是变宽。
155
+ function setupPanelResizers() {
156
+ setupPanelResizer({
157
+ resizer: el('sceneResizer'), panel: el('scenePanel'), cssVar: '--scene-width', ...PANEL_LIMITS.scene, invert: false,
158
+ });
159
+ setupPanelResizer({
160
+ resizer: el('inspectorResizer'), panel: el('inspectorPanel'), cssVar: '--inspector-width', ...PANEL_LIMITS.inspector, invert: true,
161
+ });
162
+ }
163
+
164
+ function setupPanelResizer({ resizer, panel, cssVar, min, max, invert }) {
165
+ const layout = document.querySelector('.layout');
166
+ if (!layout || !panel || !resizer) return;
167
+
168
+ const setWidth = (width) => {
169
+ const next = Math.max(min, Math.min(max, Math.round(width)));
170
+ layout.style.setProperty(cssVar, `${next}px`);
171
+ layoutThumbnails();
172
+ layoutPreview();
173
+ };
174
+
175
+ // 双击恢复默认:清掉内联变量,让响应式断点的默认值重新生效。
176
+ const resetWidth = () => {
177
+ layout.style.removeProperty(cssVar);
178
+ layoutThumbnails();
179
+ layoutPreview();
180
+ };
181
+
182
+ resizer.addEventListener('pointerdown', (event) => {
183
+ if (event.button !== 0) return;
184
+ event.preventDefault();
185
+ const startX = event.clientX;
186
+ const startWidth = panel.getBoundingClientRect().width;
187
+ const sign = invert ? -1 : 1;
188
+ resizer.setPointerCapture(event.pointerId);
189
+ resizer.classList.add('is-dragging');
190
+ document.body.classList.add('is-resizing');
191
+
192
+ const onMove = (moveEvent) => setWidth(startWidth + (moveEvent.clientX - startX) * sign);
193
+ const onEnd = () => {
194
+ resizer.classList.remove('is-dragging');
195
+ document.body.classList.remove('is-resizing');
196
+ resizer.removeEventListener('pointermove', onMove);
197
+ resizer.removeEventListener('pointerup', onEnd);
198
+ resizer.removeEventListener('pointercancel', onEnd);
199
+ };
200
+ resizer.addEventListener('pointermove', onMove);
201
+ resizer.addEventListener('pointerup', onEnd);
202
+ resizer.addEventListener('pointercancel', onEnd);
203
+ });
204
+
205
+ resizer.addEventListener('dblclick', resetWidth);
206
+
207
+ resizer.addEventListener('keydown', (event) => {
208
+ const step = event.shiftKey ? 48 : 16;
209
+ const direction = invert ? -1 : 1;
210
+ const current = panel.getBoundingClientRect().width;
211
+ if (event.key === 'ArrowLeft') setWidth(current - step * direction);
212
+ else if (event.key === 'ArrowRight') setWidth(current + step * direction);
213
+ else if (event.key === 'Home') setWidth(min);
214
+ else if (event.key === 'End') setWidth(max);
215
+ else return;
216
+ // 方向键已被分隔线消费,不能再触发全局切换场景。
217
+ event.preventDefault();
218
+ event.stopPropagation();
219
+ });
220
+ }
221
+
222
+ // 预览画布区域、缩略图栏或窗口变化时重新计算缩放,避免预览被裁切。
223
+ function observePreviewSize() {
224
+ if (typeof ResizeObserver !== 'function') return;
225
+ const observer = new ResizeObserver(() => layoutPreview());
226
+ const viewport = el('frameViewport');
227
+ if (viewport) observer.observe(viewport);
228
+ const list = el('sceneList');
229
+ if (list) new ResizeObserver(() => layoutThumbnails()).observe(list);
230
+ }
231
+
232
+ async function loadDocument({ rebuild = true } = {}) {
233
+ const payload = await api('/api/document');
234
+ state.document = payload.document;
235
+ state.lastRenderedRevision = payload.revision;
236
+ state.forceRebuild = rebuild;
237
+ rememberSceneHashes();
238
+ renderAll();
239
+ }
240
+
241
+ function rememberSceneHashes() {
242
+ for (const scene of state.document?.scenes ?? []) {
243
+ state.sceneHashes.set(scene.id, scene.contentHash);
244
+ }
245
+ }
246
+
247
+ function renderAll() {
248
+ const documentView = state.document;
249
+ if (!documentView?.exists) {
250
+ el('coursewareTitle').textContent = '未加载课件';
251
+ el('coursewareTitle').removeAttribute('title');
252
+ el('revisionBadge').textContent = 'rev —';
253
+ el('sceneList').replaceChildren();
254
+ state.sceneItems.clear();
255
+ setFrameVisible(false);
256
+ renderNotes();
257
+ el('validationLine').textContent = '当前目录没有可预览课件';
258
+ el('sourceToggle').disabled = true;
259
+ updateEditButtons();
260
+ return;
261
+ }
262
+ const meta = documentView.meta;
263
+ el('coursewareTitle').textContent = `${meta.title} · ${meta.grade} · ${meta.durationMin} 分钟`;
264
+ el('coursewareTitle').title = documentView.root;
265
+ el('revisionBadge').textContent = `rev ${documentView.revision}`;
266
+ el('sceneCount').textContent = `${documentView.scenes.length} 场景`;
267
+ el('validationLine').textContent = documentView.report.valid
268
+ ? `校验通过 · ${documentView.report.warnings} 条提示`
269
+ : `校验失败 · ${documentView.report.errors} 个错误`;
270
+ el('validationLine').className = documentView.report.valid ? 'muted' : 'badge badge-danger';
271
+
272
+ if (state.sceneIndex >= documentView.scenes.length) state.sceneIndex = Math.max(0, documentView.scenes.length - 1);
273
+ if (!documentView.scenes.some((scene) => scene.id === state.frameSceneId)) state.frameSceneId = null;
274
+ renderSceneList();
275
+ renderInspector();
276
+ renderScene({ force: state.forceRebuild });
277
+ state.forceRebuild = false;
278
+ el('sourceToggle').disabled = false;
279
+ updateStatusBadge();
280
+ updateEditButtons();
281
+ }
282
+
283
+ // 左侧缩略图复用同一批 iframe:只有内容哈希变化的场景才重载,
284
+ // 切换场景或重排顺序不会让整列缩略图重新加载。
285
+ function renderSceneList() {
286
+ const list = el('sceneList');
287
+ const scenes = state.document.scenes;
288
+ const seen = new Set();
289
+ for (const [index, scene] of scenes.entries()) {
290
+ seen.add(scene.id);
291
+ let entry = state.sceneItems.get(scene.id);
292
+ if (!entry) {
293
+ entry = createSceneItem(scene, index);
294
+ state.sceneItems.set(scene.id, entry);
295
+ }
296
+ updateSceneItem(entry, scene, index);
297
+ // append 会把已有节点移到末尾,既完成排序又不会让 iframe 脱离文档。
298
+ list.append(entry.item);
299
+ }
300
+ for (const [id, entry] of state.sceneItems) {
301
+ if (seen.has(id)) continue;
302
+ entry.item.remove();
303
+ state.sceneItems.delete(id);
304
+ }
305
+ el('prevScene').disabled = state.sceneIndex <= 0;
306
+ el('nextScene').disabled = state.sceneIndex >= scenes.length - 1;
307
+ layoutThumbnails();
308
+ }
309
+
310
+ function createSceneItem(scene, index = 0) {
311
+ const item = document.createElement('li');
312
+ item.dataset.sceneId = scene.id;
313
+ const button = document.createElement('button');
314
+ button.type = 'button';
315
+ button.className = 'scene-item';
316
+ const thumb = document.createElement('div');
317
+ thumb.className = 'scene-thumb';
318
+ const frame = document.createElement('iframe');
319
+ frame.setAttribute('sandbox', 'allow-scripts');
320
+ // 首屏缩略图立即渲染,后续交给浏览器按滚动位置加载。
321
+ frame.setAttribute('loading', index < 6 ? 'eager' : 'lazy');
322
+ frame.setAttribute('tabindex', '-1');
323
+ frame.setAttribute('aria-hidden', 'true');
324
+ frame.setAttribute('scrolling', 'no');
325
+ frame.title = `${scene.title} 缩略图`;
326
+ // 页码与更新标记直接叠在缩略图角上,不再包一层卡片。
327
+ const ordinal = document.createElement('span');
328
+ ordinal.className = 'ordinal';
329
+ const stale = document.createElement('span');
330
+ stale.className = 'chip chip-warn stale-chip';
331
+ stale.textContent = '已更新';
332
+ stale.hidden = true;
333
+ thumb.append(frame, ordinal, stale);
334
+ button.append(thumb);
335
+ button.addEventListener('click', () => selectScene(scene.id));
336
+
337
+ // 直接拖动左侧缩略图调整场景顺序。
338
+ item.draggable = true;
339
+ item.addEventListener('dragstart', (event) => {
340
+ state.dragSceneId = scene.id;
341
+ item.classList.add('dragging');
342
+ event.dataTransfer.effectAllowed = 'move';
343
+ event.dataTransfer.setData('text/plain', scene.id);
344
+ });
345
+ item.addEventListener('dragend', () => {
346
+ state.dragSceneId = null;
347
+ item.classList.remove('dragging');
348
+ clearDropMarks();
349
+ });
350
+ item.addEventListener('dragover', (event) => {
351
+ if (!state.dragSceneId || state.dragSceneId === scene.id) return;
352
+ event.preventDefault();
353
+ event.dataTransfer.dropEffect = 'move';
354
+ const after = isDropAfter(event, item);
355
+ item.classList.toggle('drop-before', !after);
356
+ item.classList.toggle('drop-after', after);
357
+ });
358
+ item.addEventListener('dragleave', (event) => {
359
+ if (item.contains(event.relatedTarget)) return;
360
+ item.classList.remove('drop-before', 'drop-after');
361
+ });
362
+ item.addEventListener('drop', (event) => {
363
+ if (!state.dragSceneId) return;
364
+ event.preventDefault();
365
+ const after = isDropAfter(event, item);
366
+ const fromId = state.dragSceneId;
367
+ state.dragSceneId = null;
368
+ clearDropMarks();
369
+ applySceneDrop(fromId, scene.id, after);
370
+ });
371
+
372
+ item.append(button);
373
+ return { item, button, thumb, frame, ordinal, stale };
374
+ }
375
+
376
+ function clearDropMarks() {
377
+ for (const entry of state.sceneItems.values()) {
378
+ entry.item.classList.remove('drop-before', 'drop-after');
379
+ }
380
+ }
381
+
382
+ function isDropAfter(event, item) {
383
+ const rect = item.getBoundingClientRect();
384
+ return event.clientY > rect.top + rect.height / 2;
385
+ }
386
+
387
+ function applySceneDrop(fromId, targetId, after) {
388
+ const scenes = state.document?.scenes ?? [];
389
+ const fromIndex = scenes.findIndex((scene) => scene.id === fromId);
390
+ const targetIndex = scenes.findIndex((scene) => scene.id === targetId);
391
+ if (fromIndex < 0 || targetIndex < 0 || fromIndex === targetIndex) return;
392
+ let toIndex = targetIndex + (after ? 1 : 0);
393
+ if (fromIndex < toIndex) toIndex -= 1;
394
+ if (toIndex === fromIndex) return;
395
+ moveSceneOperation(scenes[fromIndex], toIndex);
396
+ }
397
+
398
+ function updateSceneItem(entry, scene, index) {
399
+ const active = index === state.sceneIndex;
400
+ entry.button.className = `scene-item${active ? ' active' : ''}`;
401
+ entry.ordinal.textContent = String(index + 1).padStart(2, '0');
402
+ entry.stale.hidden = !state.staleScenes.has(scene.id);
403
+ const hash = String(scene.contentHash ?? state.document.revision);
404
+ if (entry.frame.dataset.hash !== hash) {
405
+ entry.frame.dataset.hash = hash;
406
+ entry.frame.src = `${scene.contentUrl}?v=${encodeURIComponent(hash)}&thumb=1`;
407
+ }
408
+ const ratio = previewRatioOf(state.document?.meta?.aspectRatio);
409
+ entry.thumb.style.aspectRatio = `${ratio.width} / ${ratio.height}`;
410
+ }
411
+
412
+ function previewRatioOf(aspectRatio) {
413
+ const match = /^(\d{1,2}):(\d{1,2})$/.exec(String(aspectRatio ?? '').trim());
414
+ return { width: match ? Number(match[1]) : 16, height: match ? Number(match[2]) : 9 };
415
+ }
416
+
417
+ function layoutThumbnails() {
418
+ const ratio = previewRatioOf(state.document?.meta?.aspectRatio);
419
+ const height = Math.round((PREVIEW_LOGICAL_WIDTH * ratio.height) / ratio.width);
420
+ for (const entry of state.sceneItems.values()) {
421
+ const width = entry.thumb.clientWidth;
422
+ if (!width) continue;
423
+ entry.frame.style.width = `${PREVIEW_LOGICAL_WIDTH}px`;
424
+ entry.frame.style.height = `${height}px`;
425
+ entry.frame.style.transform = `scale(${width / PREVIEW_LOGICAL_WIDTH})`;
426
+ }
427
+ }
428
+
429
+ async function selectScene(sceneId) {
430
+ // 源码模式下切换场景前先提交当前草稿,避免尚未自动保存的内容丢失。
431
+ if (state.sourceMode) await flushSource();
432
+ if (state.chatPicking) setPicking(false);
433
+ const index = state.document?.scenes?.findIndex((scene) => scene.id === sceneId) ?? -1;
434
+ if (index < 0) return;
435
+ state.sceneIndex = index;
436
+ state.staleScenes.delete(sceneId);
437
+ state.pendingStates = {};
438
+ renderSceneList();
439
+ renderInspector();
440
+ renderScene({ force: true });
441
+ if (state.sourceMode) {
442
+ stashSourceDraft();
443
+ loadSourceForScene(currentScene());
444
+ }
445
+ }
446
+
447
+ function currentScene() {
448
+ return state.document?.scenes?.[state.sceneIndex] ?? null;
449
+ }
450
+
451
+ function setFrameVisible(visible) {
452
+ el('slideFit').classList.toggle('is-hidden', !visible);
453
+ for (const frame of document.querySelectorAll('.preview-frame')) {
454
+ frame.classList.toggle('is-hidden', !visible);
455
+ }
456
+ el('frameEmpty').classList.toggle('is-hidden', visible);
457
+ }
458
+
459
+ // 预览固定按 1280 宽的逻辑画布渲染,再整体缩放到可用区域。
460
+ // 切换比例时场景会在新画布上重新排版,而不是被预览框裁掉。
461
+ const PREVIEW_LOGICAL_WIDTH = 1280;
462
+ const previewCanvas = { width: PREVIEW_LOGICAL_WIDTH, height: 720 };
463
+
464
+ function applyPreviewRatio(aspectRatio) {
465
+ const ratio = previewRatioOf(aspectRatio);
466
+ previewCanvas.width = PREVIEW_LOGICAL_WIDTH;
467
+ previewCanvas.height = Math.round((PREVIEW_LOGICAL_WIDTH * ratio.height) / ratio.width);
468
+ layoutPreview();
469
+ }
470
+
471
+ function layoutPreview() {
472
+ const viewport = el('frameViewport');
473
+ const fit = el('slideFit');
474
+ if (!viewport || !fit) return;
475
+ const style = getComputedStyle(viewport);
476
+ const paddingX = (Number.parseFloat(style.paddingLeft) || 0) + (Number.parseFloat(style.paddingRight) || 0);
477
+ const paddingY = (Number.parseFloat(style.paddingTop) || 0) + (Number.parseFloat(style.paddingBottom) || 0);
478
+ const boxWidth = viewport.clientWidth - paddingX;
479
+ const boxHeight = viewport.clientHeight - paddingY;
480
+ if (boxWidth <= 0 || boxHeight <= 0) return;
481
+ const scale = Math.min(boxWidth / previewCanvas.width, boxHeight / previewCanvas.height, 1);
482
+ if (!(scale > 0)) return;
483
+ fit.style.width = `${Math.floor(previewCanvas.width * scale)}px`;
484
+ fit.style.height = `${Math.floor(previewCanvas.height * scale)}px`;
485
+ // 两份 iframe 同步尺寸,后台帧加载时就能按正确画布排版。
486
+ for (const frame of document.querySelectorAll('.preview-frame')) {
487
+ frame.style.width = `${previewCanvas.width}px`;
488
+ frame.style.height = `${previewCanvas.height}px`;
489
+ frame.style.transform = `scale(${scale})`;
490
+ }
491
+ }
492
+
493
+ async function renderScene({ force = false } = {}) {
494
+ const scene = currentScene();
495
+ if (!scene) {
496
+ setFrameVisible(false);
497
+ renderNotes();
498
+ return;
499
+ }
500
+ renderNotes();
501
+ applyPreviewRatio(state.document?.meta?.aspectRatio);
502
+ setFrameVisible(true);
503
+
504
+ const signature = `${scene.id}:${scene.contentHash ?? ''}:${scene.file}`;
505
+ if (force || state.frameSignature !== signature || state.frameSceneId !== scene.id) {
506
+ const states = state.frameSceneId ? await captureStates() : {};
507
+ state.pendingStates = states;
508
+ state.frameSignature = signature;
509
+ state.frameSceneId = scene.id;
510
+ await loadSceneIntoBuffer(scene);
511
+ } else {
512
+ syncFrame();
513
+ }
514
+ }
515
+
516
+ // 双缓冲:先在隐藏帧里加载新场景,加载完成后再交换,旧画面一直保留到新画面可绘制。
517
+ async function loadSceneIntoBuffer(scene) {
518
+ const token = state.frameLoadToken + 1;
519
+ state.frameLoadToken = token;
520
+ const next = el('previewFrameBackup');
521
+ next.dataset.revision = String(state.document.revision);
522
+ next.dataset.scene = scene.id;
523
+ const url = `${scene.contentUrl}?v=${encodeURIComponent(scene.contentHash ?? state.document.revision)}&rev=${state.document.revision}&pick=1`;
524
+ const loaded = await waitForFrameLoad(next, url);
525
+ if (!loaded || token !== state.frameLoadToken) return;
526
+
527
+ // 交换 id 而不是重建节点:所有 #previewFrame 查询始终指向当前活动帧。
528
+ const current = el('previewFrame');
529
+ current.id = 'previewFrameBackup';
530
+ current.classList.remove('is-active');
531
+ next.id = 'previewFrame';
532
+ next.classList.add('is-active');
533
+ syncFrame();
534
+ if (state.chatPicking) postPickMode(true);
535
+ }
536
+
537
+ function waitForFrameLoad(frame, url) {
538
+ return new Promise((resolve) => {
539
+ let settled = false;
540
+ const finish = (ok) => {
541
+ if (settled) return;
542
+ settled = true;
543
+ frame.removeEventListener('load', onLoad);
544
+ clearTimeout(timer);
545
+ resolve(ok);
546
+ };
547
+ const onLoad = () => finish(true);
548
+ // 本地课件通常很快;超时后仍切换,避免一直停留在旧画面。
549
+ const timer = setTimeout(() => finish(true), 1500);
550
+ frame.addEventListener('load', onLoad);
551
+ frame.src = url;
552
+ });
553
+ }
554
+
555
+ // 重建 iframe 前向 SDK 请求完整组件状态;超时按现有缓存继续。
556
+ function captureStates() {
557
+ const frame = el('previewFrame');
558
+ if (!frame.contentWindow || frame.classList.contains('is-hidden')) return Promise.resolve({ ...state.pendingStates });
559
+ return new Promise((resolve) => {
560
+ const collected = { ...state.pendingStates };
561
+ const onMessage = (event) => {
562
+ if (event.source !== frame.contentWindow) return;
563
+ const data = event.data;
564
+ if (!data || data.source !== 'lume-courseware') return;
565
+ if (data.type === 'state' && typeof data.cid === 'string') {
566
+ collected[data.cid] = { state: data.state, seq: Number.isFinite(data.seq) ? data.seq : 0 };
567
+ state.pendingStates[data.cid] = collected[data.cid];
568
+ }
569
+ };
570
+ window.addEventListener('message', onMessage);
571
+ try {
572
+ frame.contentWindow.postMessage({ source: 'lume-host', type: 'state-request' }, '*');
573
+ } catch {
574
+ // 忽略跨域限制。
575
+ }
576
+ setTimeout(() => {
577
+ window.removeEventListener('message', onMessage);
578
+ state.lastCapturedStates = { ...collected };
579
+ resolve(collected);
580
+ }, 160);
581
+ });
582
+ }
583
+
584
+ function syncFrame() {
585
+ const scene = currentScene();
586
+ const frame = el('previewFrame');
587
+ if (!scene || !frame.contentWindow || frame.classList.contains('is-hidden')) return;
588
+ frame.contentWindow.postMessage({
589
+ source: 'lume-host',
590
+ type: 'sync',
591
+ role: 'preview',
592
+ lessonId: state.document.coursewareId,
593
+ coursewareId: state.document.coursewareId,
594
+ sceneId: scene.id,
595
+ revision: state.document.revision,
596
+ playbackMode: 'free',
597
+ canNavigate: true,
598
+ }, '*');
599
+ if (Object.keys(state.pendingStates).length > 0) {
600
+ frame.contentWindow.postMessage({
601
+ source: 'lume-host',
602
+ type: 'scene-state',
603
+ lessonId: state.document.coursewareId,
604
+ sceneId: scene.id,
605
+ states: state.pendingStates,
606
+ }, '*');
607
+ }
608
+ }
609
+
610
+ // 演讲稿固定在预览下方,切换场景时同步为当前场景的讲稿。
611
+ function renderNotes() {
612
+ const scene = currentScene();
613
+ const input = el('notesInput');
614
+ input.disabled = !scene;
615
+ input.value = scene?.notes ?? '';
616
+ el('notesState').textContent = scene ? '' : '—';
617
+ }
618
+
619
+ async function saveNotes() {
620
+ const scene = currentScene();
621
+ if (!scene) return;
622
+ const patch = buildScenePatch(scene, { notes: el('notesInput').value });
623
+ if (!patch.hasChanges) {
624
+ el('notesState').textContent = '没有改动';
625
+ return;
626
+ }
627
+ const result = await saveOperations({
628
+ summary: `更新场景 ${scene.id} 的讲稿`,
629
+ operations: [{ op: 'scene.patch', sceneId: scene.id, set: patch.set }],
630
+ });
631
+ el('notesState').textContent = describeSave(result);
632
+ }
633
+
634
+ async function onSaveNotes() {
635
+ const button = el('saveNotes');
636
+ button.disabled = true;
637
+ el('notesState').textContent = '提交中…';
638
+ try {
639
+ await saveNotes();
640
+ } catch (error) {
641
+ el('notesState').textContent = `${error.code ?? '失败'}:${error.message}`;
642
+ } finally {
643
+ button.disabled = false;
644
+ }
645
+ }
646
+
647
+ // 每次成功提交都把提交前的修订记入撤销栈;新提交会清空重做栈。
648
+ function recordUndo(revision) {
649
+ if (!Number.isInteger(revision) || revision < 0) return;
650
+ state.undoStack.push(revision);
651
+ if (state.undoStack.length > 50) state.undoStack.shift();
652
+ state.redoStack = [];
653
+ }
654
+
655
+ function updateEditButtons() {
656
+ const undo = el('undoButton');
657
+ const redo = el('redoButton');
658
+ if (!undo || !redo) return;
659
+ const revision = state.document?.revision ?? 0;
660
+ undo.disabled = state.editBusy || !(revision > 0);
661
+ redo.disabled = state.editBusy || state.redoStack.length === 0;
662
+ }
663
+
664
+ // 撤销与重做都通过恢复历史修订实现:每次恢复会产生一个新修订。
665
+ async function restoreRevision(target) {
666
+ const baseRevision = state.document?.revision;
667
+ if (!Number.isInteger(target) || target < 0) return null;
668
+ if (!Number.isInteger(baseRevision) || target >= baseRevision) return null;
669
+ try {
670
+ const payload = await api('/api/undo', {
671
+ method: 'POST',
672
+ body: JSON.stringify({ revision: target, baseRevision, confirm: true }),
673
+ });
674
+ const result = payload?.result ?? {};
675
+ if (!result.committed) return null;
676
+ await loadDocument({ rebuild: true });
677
+ return result;
678
+ } catch (error) {
679
+ el('eventLine').textContent = `${error.code ?? '失败'}:${error.message}`;
680
+ if (error.code === 'REVISION_CONFLICT') await loadDocument({ rebuild: false }).catch(() => {});
681
+ return null;
682
+ }
683
+ }
684
+
685
+ async function undoEdit() {
686
+ if (state.editBusy) return;
687
+ const current = state.document?.revision;
688
+ if (!Number.isInteger(current) || current <= 0) return;
689
+ const target = state.undoStack.length > 0 ? state.undoStack[state.undoStack.length - 1] : current - 1;
690
+ state.editBusy = true;
691
+ updateEditButtons();
692
+ try {
693
+ const result = await restoreRevision(target);
694
+ if (!result) return;
695
+ if (state.undoStack.length > 0) state.undoStack.pop();
696
+ state.redoStack.push(current);
697
+ el('eventLine').textContent = `已撤销 · rev ${result.revision}`;
698
+ } finally {
699
+ state.editBusy = false;
700
+ updateEditButtons();
701
+ }
702
+ }
703
+
704
+ async function redoEdit() {
705
+ if (state.editBusy) return;
706
+ const current = state.document?.revision;
707
+ const target = state.redoStack[state.redoStack.length - 1];
708
+ if (!Number.isInteger(current) || !Number.isInteger(target)) return;
709
+ state.editBusy = true;
710
+ updateEditButtons();
711
+ try {
712
+ const result = await restoreRevision(target);
713
+ if (!result) return;
714
+ state.redoStack.pop();
715
+ state.undoStack.push(current);
716
+ el('eventLine').textContent = `已重做 · rev ${result.revision}`;
717
+ } finally {
718
+ state.editBusy = false;
719
+ updateEditButtons();
720
+ }
721
+ }
722
+
723
+ // 保存按钮兜底保存当前场景的讲稿草稿;属性与题目仍由各自表单即时提交。
724
+ async function saveAll() {
725
+ if (state.sourceMode) {
726
+ await flushSource();
727
+ return;
728
+ }
729
+ const button = el('saveButton');
730
+ button.disabled = true;
731
+ try {
732
+ await saveNotes();
733
+ el('eventLine').textContent = '已保存';
734
+ } catch (error) {
735
+ el('eventLine').textContent = `${error.code ?? '失败'}:${error.message}`;
736
+ } finally {
737
+ button.disabled = false;
738
+ }
739
+ }
740
+
741
+ // 预览 / 源码切换:源码模式下直接读取并修改当前场景的 HTML。
742
+ async function setSourceMode(enabled) {
743
+ if (enabled && !currentScene()) return;
744
+ if (enabled && state.chatPicking) setPicking(false);
745
+ // 退出源码前先把未提交的修改落盘,返回预览即可看到最新渲染。
746
+ if (!enabled) await flushSource();
747
+ stashSourceDraft();
748
+ state.sourceMode = enabled;
749
+ el('frameViewport').hidden = enabled;
750
+ el('sourceEditor').hidden = !enabled;
751
+ const toggle = el('sourceToggle');
752
+ toggle.classList.toggle('is-code', enabled);
753
+ toggle.setAttribute('aria-pressed', String(enabled));
754
+ const label = enabled ? '返回预览' : '查看源码';
755
+ toggle.title = label;
756
+ toggle.setAttribute('aria-label', label);
757
+ if (enabled) await loadSourceForScene(currentScene());
758
+ else {
759
+ layoutPreview();
760
+ syncFrame();
761
+ }
762
+ }
763
+
764
+ function stashSourceDraft() {
765
+ if (!state.sourceMode || !state.sourceSceneId) return;
766
+ const value = el('sourceCode').value;
767
+ if (value !== state.sourceOriginal) state.sourceDrafts.set(state.sourceSceneId, value);
768
+ else state.sourceDrafts.delete(state.sourceSceneId);
769
+ }
770
+
771
+ async function loadSourceForScene(scene) {
772
+ const code = el('sourceCode');
773
+ const requestId = ++state.sourceRequest;
774
+ if (!scene) {
775
+ state.sourceSceneId = null;
776
+ state.sourceOriginal = '';
777
+ code.value = '';
778
+ el('sourceName').textContent = '';
779
+ el('sourceState').textContent = '没有可编辑的场景';
780
+ return;
781
+ }
782
+ state.sourceSceneId = scene.id;
783
+ el('sourceName').textContent = scene.file ?? scene.id;
784
+ let original = state.sourceCache.get(scene.id);
785
+ if (original === undefined) {
786
+ el('sourceState').textContent = '读取中…';
787
+ try {
788
+ const response = await fetch(scene.contentUrl, { credentials: 'same-origin' });
789
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
790
+ original = await response.text();
791
+ state.sourceCache.set(scene.id, original);
792
+ } catch (error) {
793
+ if (requestId !== state.sourceRequest) return;
794
+ el('sourceState').textContent = `读取源码失败:${error.message}`;
795
+ return;
796
+ }
797
+ }
798
+ if (requestId !== state.sourceRequest) return;
799
+ state.sourceOriginal = original;
800
+ code.value = state.sourceDrafts.get(scene.id) ?? original;
801
+ updateSourceState();
802
+ }
803
+
804
+ let sourceSaveTimer = null;
805
+
806
+ function updateSourceState() {
807
+ const dirty = el('sourceCode').value !== state.sourceOriginal;
808
+ el('sourceState').textContent = dirty ? '未保存' : '已保存';
809
+ renderSourceView();
810
+ if (dirty) scheduleSourceSave();
811
+ else if (sourceSaveTimer) {
812
+ clearTimeout(sourceSaveTimer);
813
+ sourceSaveTimer = null;
814
+ }
815
+ }
816
+
817
+ // 输入停顿后自动提交当前源码,提交成功即触发预览重建。
818
+ function scheduleSourceSave() {
819
+ if (sourceSaveTimer) clearTimeout(sourceSaveTimer);
820
+ sourceSaveTimer = setTimeout(() => {
821
+ sourceSaveTimer = null;
822
+ saveSource();
823
+ }, 700);
824
+ }
825
+
826
+ async function flushSource() {
827
+ if (sourceSaveTimer) {
828
+ clearTimeout(sourceSaveTimer);
829
+ sourceSaveTimer = null;
830
+ }
831
+ if (!state.sourceMode) return;
832
+ // 等已在途的提交结束,确保随后读取到的是最新内容。
833
+ while (state.sourceSaving) await new Promise((resolve) => setTimeout(resolve, 30));
834
+ if (el('sourceCode').value === state.sourceOriginal) return;
835
+ await saveSource();
836
+ }
837
+
838
+ // 轻量高亮:按 HTML 结构分词,script/style 内容分别按 JS/CSS 规则处理。
839
+ // 不引入第三方依赖,保持离线可用。
840
+ const escapeSourceHtml = (value) => value.replace(/[&<>]/g, (ch) => ({
841
+ '&': '&amp;', '<': '&lt;', '>': '&gt;',
842
+ }[ch]));
843
+
844
+ const JS_TOKEN_RE = /\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`|\b(?:const|let|var|function|return|if|else|for|while|switch|case|break|continue|new|class|extends|import|export|from|await|async|try|catch|finally|throw|typeof|instanceof|in|of|this|null|undefined|true|false|void|delete|yield)\b|\b\d+(?:\.\d+)?\b/g;
845
+ const CSS_TOKEN_RE = /\/\*[\s\S]*?\*\/|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|#[0-9a-fA-F]{3,8}\b|-?\b\d+(?:\.\d+)?(?:px|em|rem|%|vh|vw|s|ms|deg|fr)?\b/g;
846
+
847
+ function highlightWith(source, regex, classify) {
848
+ regex.lastIndex = 0;
849
+ let html = '';
850
+ let last = 0;
851
+ let match;
852
+ while ((match = regex.exec(source)) !== null) {
853
+ if (match.index > last) html += escapeSourceHtml(source.slice(last, match.index));
854
+ const token = match[0];
855
+ html += `<span class="tok-${classify(token)}">${escapeSourceHtml(token)}</span>`;
856
+ last = match.index + token.length;
857
+ }
858
+ if (last < source.length) html += escapeSourceHtml(source.slice(last));
859
+ return html;
860
+ }
861
+
862
+ function highlightJs(source) {
863
+ return highlightWith(source, JS_TOKEN_RE, (token) => {
864
+ if (token.startsWith('//') || token.startsWith('/*')) return 'comment';
865
+ const first = token[0];
866
+ if (first === '"' || first === "'" || first === '`') return 'string';
867
+ if (/^\d/.test(token)) return 'number';
868
+ return 'keyword';
869
+ });
870
+ }
871
+
872
+ function highlightCss(source) {
873
+ return highlightWith(source, CSS_TOKEN_RE, (token) => {
874
+ if (token.startsWith('/*')) return 'comment';
875
+ const first = token[0];
876
+ if (first === '"' || first === "'") return 'string';
877
+ return 'number';
878
+ });
879
+ }
880
+
881
+ function highlightHtml(source) {
882
+ const lowerSource = source.toLowerCase();
883
+ const size = source.length;
884
+ let html = '';
885
+ let i = 0;
886
+ const plain = (text) => { html += escapeSourceHtml(text); };
887
+ const token = (cls, text) => { html += `<span class="tok-${cls}">${escapeSourceHtml(text)}</span>`; };
888
+
889
+ while (i < size) {
890
+ const lt = source.indexOf('<', i);
891
+ if (lt === -1) { plain(source.slice(i)); break; }
892
+ if (lt > i) plain(source.slice(i, lt));
893
+ if (source.startsWith('<!--', lt)) {
894
+ const end = source.indexOf('-->', lt + 4);
895
+ const stop = end === -1 ? size : end + 3;
896
+ token('comment', source.slice(lt, stop));
897
+ i = stop;
898
+ continue;
899
+ }
900
+ if (lowerSource.startsWith('<!doctype', lt)) {
901
+ const end = source.indexOf('>', lt);
902
+ const stop = end === -1 ? size : end + 1;
903
+ token('doctype', source.slice(lt, stop));
904
+ i = stop;
905
+ continue;
906
+ }
907
+ if (source[lt + 1] === '/') {
908
+ const end = source.indexOf('>', lt);
909
+ const stop = end === -1 ? size : end + 1;
910
+ token('tag', source.slice(lt, stop));
911
+ i = stop;
912
+ continue;
913
+ }
914
+ const nameMatch = /^<([a-zA-Z][\w:-]*)/.exec(source.slice(lt));
915
+ if (!nameMatch) { plain('<'); i = lt + 1; continue; }
916
+ const name = nameMatch[1];
917
+ let j = lt + 1 + name.length;
918
+ token('tag', `<${name}`);
919
+ while (j < size) {
920
+ if (source.startsWith('/>', j)) { token('tag', '/>'); j += 2; break; }
921
+ const ch = source[j];
922
+ if (ch === '>') { token('tag', '>'); j += 1; break; }
923
+ if (/\s/.test(ch)) { plain(ch); j += 1; continue; }
924
+ const attr = /^[^\s=/>]+/.exec(source.slice(j));
925
+ if (!attr) { plain(ch); j += 1; continue; }
926
+ token('attr', attr[0]);
927
+ j += attr[0].length;
928
+ let k = j;
929
+ while (k < size && /\s/.test(source[k])) k += 1;
930
+ if (source[k] !== '=') continue;
931
+ plain(source.slice(j, k + 1));
932
+ k += 1;
933
+ while (k < size && /\s/.test(source[k])) k += 1;
934
+ const quote = source[k];
935
+ if (quote === '"' || quote === "'") {
936
+ const end = source.indexOf(quote, k + 1);
937
+ const stop = end === -1 ? size : end + 1;
938
+ token('string', source.slice(k, stop));
939
+ j = stop;
940
+ } else {
941
+ const value = /^[^\s>]+/.exec(source.slice(k));
942
+ if (!value) { j = k; continue; }
943
+ token('string', value[0]);
944
+ j = k + value[0].length;
945
+ }
946
+ }
947
+ i = j;
948
+ const lowerName = name.toLowerCase();
949
+ if (lowerName === 'script' || lowerName === 'style') {
950
+ const close = lowerSource.indexOf(`</${lowerName}`, i);
951
+ const end = close === -1 ? size : close;
952
+ const content = source.slice(i, end);
953
+ if (content) html += lowerName === 'script' ? highlightJs(content) : highlightCss(content);
954
+ i = end;
955
+ }
956
+ }
957
+ return html;
958
+ }
959
+
960
+ function renderSourceView() {
961
+ const code = el('sourceCode').value;
962
+ el('sourceHighlight').innerHTML = `${highlightHtml(code)}\u200b`;
963
+ const lineCount = code.split('\n').length;
964
+ const numbers = [];
965
+ for (let line = 1; line <= lineCount; line += 1) numbers.push(String(line));
966
+ el('sourceGutter').textContent = `${numbers.join('\n')}\u200b`;
967
+ syncSourceScroll();
968
+ }
969
+
970
+ function syncSourceScroll() {
971
+ const code = el('sourceCode');
972
+ const highlight = el('sourceHighlight');
973
+ const gutter = el('sourceGutter');
974
+ highlight.scrollTop = code.scrollTop;
975
+ highlight.scrollLeft = code.scrollLeft;
976
+ gutter.scrollTop = code.scrollTop;
977
+ }
978
+
979
+ // 源码改动自动提交;提交期间的新输入排队,完成后继续渲染。
980
+ async function saveSource() {
981
+ if (state.sourceSaving) {
982
+ state.sourceQueued = true;
983
+ return;
984
+ }
985
+ const scene = currentScene();
986
+ if (!scene) return;
987
+ const html = el('sourceCode').value;
988
+ if (!html.trim()) {
989
+ el('sourceState').textContent = '源码不能为空';
990
+ return;
991
+ }
992
+ if (html === state.sourceOriginal) {
993
+ el('sourceState').textContent = '已保存';
994
+ return;
995
+ }
996
+ state.sourceSaving = true;
997
+ el('sourceState').textContent = '正在渲染…';
998
+ try {
999
+ const result = await saveOperations({
1000
+ summary: `更新场景源码 ${scene.file ?? scene.id}`,
1001
+ operations: [{ op: 'scene.patch', sceneId: scene.id, html }],
1002
+ });
1003
+ if (result?.committed) {
1004
+ state.sourceOriginal = html;
1005
+ state.sourceDrafts.delete(scene.id);
1006
+ state.sourceCache.set(scene.id, html);
1007
+ el('sourceState').textContent = `已渲染 · rev ${result.revision}`;
1008
+ if (el('sourceCode').value !== html) state.sourceQueued = true;
1009
+ } else if (result?.pending) {
1010
+ el('sourceState').textContent = '等待确认';
1011
+ }
1012
+ } catch (error) {
1013
+ // 校验未通过时保留草稿,继续输入会自动重试。
1014
+ state.sourceDrafts.set(scene.id, html);
1015
+ el('sourceState').textContent = `${error.code ?? '失败'}:${error.message}`;
1016
+ } finally {
1017
+ state.sourceSaving = false;
1018
+ if (state.sourceQueued) {
1019
+ state.sourceQueued = false;
1020
+ scheduleSourceSave();
1021
+ }
1022
+ }
1023
+ }
1024
+
1025
+
1026
+ function renderInspector() {
1027
+ const body = el('inspectorBody');
1028
+ body.replaceChildren();
1029
+ syncInspectorTabs();
1030
+ const scene = currentScene();
1031
+ body.classList.toggle('is-split', Boolean(scene) && state.inspectorTab === 'structure');
1032
+ body.classList.toggle('is-props', state.inspectorTab === 'props');
1033
+ if (!scene) {
1034
+ const empty = document.createElement('p');
1035
+ empty.className = 'muted';
1036
+ empty.textContent = '选择场景后显示页面结构。';
1037
+ body.append(empty);
1038
+ return;
1039
+ }
1040
+ if (state.inspectorTab === 'structure') {
1041
+ body.append(renderStructureSplit(scene));
1042
+ return;
1043
+ }
1044
+ const interactions = (state.document.interactions ?? []).filter((item) => item.scene === scene.id);
1045
+ if (interactions.length > 0) {
1046
+ body.append(sectionTitle('题目'));
1047
+ for (const interaction of interactions) body.append(renderInteractionEditor(interaction));
1048
+ }
1049
+ body.append(renderDiagnostics());
1050
+ }
1051
+
1052
+ // 结构 tab:上半部分是页面结构树,下半部分是本页组件说明,两段各自滚动。
1053
+ function renderStructureSplit(scene) {
1054
+ const split = document.createElement('div');
1055
+ split.className = 'inspector-split';
1056
+
1057
+ const structure = document.createElement('section');
1058
+ structure.className = 'inspector-pane structure-pane';
1059
+ structure.append(sectionTitle('页面结构'), renderStructure(scene));
1060
+
1061
+ const components = document.createElement('section');
1062
+ components.className = 'inspector-pane components-pane';
1063
+ components.append(renderSceneComponents(scene));
1064
+
1065
+ split.append(structure, components);
1066
+ return split;
1067
+ }
1068
+
1069
+ // 组件是页面里可独立交互、可采集状态的单元,这里给出定义、用途和可配置参数。
1070
+ function renderSceneComponents(scene) {
1071
+ const block = document.createElement('div');
1072
+ block.className = 'component-briefs';
1073
+ block.append(sectionTitle('本页组件'));
1074
+
1075
+ const hint = document.createElement('p');
1076
+ hint.className = 'component-definition';
1077
+ hint.textContent = '组件是页面里可独立交互、可采集状态的单元:cid 是场景内唯一标识,type 决定用途,role 决定教学主次,collect 决定状态何时上报。';
1078
+ block.append(hint);
1079
+
1080
+ const components = scene.components ?? [];
1081
+ if (components.length === 0) {
1082
+ const empty = document.createElement('div');
1083
+ empty.className = 'muted';
1084
+ empty.textContent = '当前页没有组件,可在“属性”页新增。';
1085
+ block.append(empty);
1086
+ return block;
1087
+ }
1088
+ for (const component of components) block.append(renderComponentBrief(scene, component));
1089
+ return block;
1090
+ }
1091
+
1092
+ function renderComponentBrief(scene, component) {
1093
+ const meta = COMPONENT_CATALOG[component.type] ?? {
1094
+ label: '自定义组件',
1095
+ purpose: '由组件自身定义用途与参数。',
1096
+ props: [],
1097
+ };
1098
+ const card = document.createElement('div');
1099
+ card.className = 'component-brief';
1100
+
1101
+ const head = document.createElement('div');
1102
+ head.className = 'component-brief-head';
1103
+ const cid = document.createElement('strong');
1104
+ cid.className = 'component-cid';
1105
+ cid.textContent = component.cid;
1106
+ const type = document.createElement('span');
1107
+ type.className = 'component-type';
1108
+ type.textContent = `${meta.label} · ${component.type}`;
1109
+ head.append(cid, type);
1110
+ card.append(head);
1111
+
1112
+ const purpose = document.createElement('p');
1113
+ purpose.className = 'component-purpose';
1114
+ purpose.textContent = meta.purpose;
1115
+ card.append(purpose);
1116
+
1117
+ const role = component.role ?? 'primary';
1118
+ const collect = component.collect ?? 'onDemand';
1119
+ card.append(componentParamRow('角色', `${ROLE_LABELS[role] ?? role}(${role})`));
1120
+ card.append(componentParamRow('采集', `${COLLECT_LABELS[collect] ?? collect}(${collect})`));
1121
+ card.append(componentParamRow('参数', meta.props.length > 0 ? meta.props.join('、') : '由组件自定义'));
1122
+
1123
+ const props = component.props && typeof component.props === 'object' ? component.props : null;
1124
+ if (props && Object.keys(props).length > 0) {
1125
+ card.append(componentParamRow('已设置', formatComponentProps(props)));
1126
+ }
1127
+ return card;
1128
+ }
1129
+
1130
+ function componentParamRow(labelText, valueText) {
1131
+ const row = document.createElement('div');
1132
+ row.className = 'component-param';
1133
+ const label = document.createElement('span');
1134
+ label.className = 'component-param-label';
1135
+ label.textContent = labelText;
1136
+ const value = document.createElement('span');
1137
+ value.className = 'component-param-value';
1138
+ value.textContent = valueText;
1139
+ row.append(label, value);
1140
+ return row;
1141
+ }
1142
+
1143
+ function formatComponentProps(props) {
1144
+ const entries = Object.entries(props);
1145
+ const text = entries.slice(0, 4).map(([key, value]) => {
1146
+ const raw = typeof value === 'string' ? value : JSON.stringify(value);
1147
+ return `${key}=${compactText(raw, 18)}`;
1148
+ }).join(',');
1149
+ return entries.length > 4 ? `${text} …` : text;
1150
+ }
1151
+
1152
+ function syncInspectorTabs() {
1153
+ const structure = state.inspectorTab === 'structure';
1154
+ el('tabStructure').setAttribute('aria-selected', String(structure));
1155
+ el('tabProps').setAttribute('aria-selected', String(!structure));
1156
+ }
1157
+
1158
+ // 结构树展示当前场景真实的 HTML 标签层级:组件与变量属于元数据,不进入结构树。
1159
+ const STRUCTURE_SKIP_TAGS = new Set(['head', 'script', 'style', 'link', 'meta', 'title', 'noscript', 'template']);
1160
+ // 内联标签只承载文字,不构成页面结构;直接展开其子节点,避免树过深。
1161
+ const STRUCTURE_INLINE_TAGS = new Set(['span', 'i', 'em', 'b', 'strong', 'small', 'mark', 'u', 's', 'sub', 'sup', 'br']);
1162
+ // 媒体与画布内部节点很多,折叠成一个叶子节点即可。
1163
+ const STRUCTURE_LEAF_TAGS = new Set(['img', 'svg', 'canvas', 'video', 'audio', 'iframe', 'input']);
1164
+ const STRUCTURE_CACHE_LIMIT = 20;
1165
+
1166
+ function structureKey(scene) {
1167
+ return `${scene.id}:${scene.contentHash ?? state.document?.revision ?? 0}`;
1168
+ }
1169
+
1170
+ function renderStructure(scene) {
1171
+ const tree = document.createElement('div');
1172
+ tree.className = 'tree';
1173
+ tree.setAttribute('role', 'tree');
1174
+
1175
+ const root = document.createElement('div');
1176
+ root.className = 'tree-row tree-root';
1177
+ root.setAttribute('role', 'treeitem');
1178
+ root.setAttribute('aria-expanded', 'true');
1179
+ const caret = document.createElement('span');
1180
+ caret.className = 'tree-caret';
1181
+ const fileName = document.createElement('span');
1182
+ fileName.className = 'tree-file-name';
1183
+ fileName.textContent = scene.file ?? `${scene.id}.html`;
1184
+ root.append(caret, fileName);
1185
+ tree.append(root);
1186
+
1187
+ const key = structureKey(scene);
1188
+ const html = state.structureCache.get(key);
1189
+ if (typeof html === 'string') {
1190
+ const nodes = parseStructureHtml(html);
1191
+ tree.append(nodes.length > 0
1192
+ ? buildStructureList(nodes)
1193
+ : structureEmpty('当前页面没有可展示的 HTML 结构'));
1194
+ return tree;
1195
+ }
1196
+
1197
+ const error = state.structureErrors.get(key);
1198
+ if (error) {
1199
+ tree.append(structureEmpty(`读取页面结构失败:${error}`));
1200
+ return tree;
1201
+ }
1202
+
1203
+ tree.append(structureEmpty('正在读取页面结构…'));
1204
+ loadStructureHtml(scene, key);
1205
+ return tree;
1206
+ }
1207
+
1208
+ function structureEmpty(text) {
1209
+ const empty = document.createElement('div');
1210
+ empty.className = 'tree-empty';
1211
+ empty.textContent = text;
1212
+ return empty;
1213
+ }
1214
+
1215
+ // 按场景内容哈希缓存源码,避免面板每次重绘都请求一次页面。
1216
+ function loadStructureHtml(scene, key) {
1217
+ if (state.structurePending.has(key)) return;
1218
+ state.structurePending.add(key);
1219
+ fetch(scene.contentUrl, { credentials: 'same-origin' })
1220
+ .then(async (response) => {
1221
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
1222
+ state.structureCache.set(key, await response.text());
1223
+ state.structureErrors.delete(key);
1224
+ while (state.structureCache.size > STRUCTURE_CACHE_LIMIT) {
1225
+ state.structureCache.delete(state.structureCache.keys().next().value);
1226
+ }
1227
+ })
1228
+ .catch((error) => {
1229
+ state.structureErrors.set(key, error.message);
1230
+ })
1231
+ .finally(() => {
1232
+ state.structurePending.delete(key);
1233
+ const current = currentScene();
1234
+ if (state.inspectorTab === 'structure' && current && structureKey(current) === key) renderInspector();
1235
+ });
1236
+ }
1237
+
1238
+ // 从 body 开始生成轻量树:省略 html/body 包装、脚本样式与内联文字标签。
1239
+ function parseStructureHtml(html) {
1240
+ let doc;
1241
+ try {
1242
+ doc = new DOMParser().parseFromString(html, 'text/html');
1243
+ } catch {
1244
+ return [];
1245
+ }
1246
+ return doc.body ? structureChildren(doc.body) : [];
1247
+ }
1248
+
1249
+ function structureChildren(parent) {
1250
+ const nodes = [];
1251
+ for (const child of parent.children) {
1252
+ const tag = child.tagName.toLowerCase();
1253
+ if (STRUCTURE_SKIP_TAGS.has(tag)) continue;
1254
+ // 内联标签不占层级,把其子节点提升到当前层。
1255
+ if (STRUCTURE_INLINE_TAGS.has(tag)) {
1256
+ nodes.push(...structureChildren(child));
1257
+ continue;
1258
+ }
1259
+ nodes.push(structureNode(child));
1260
+ }
1261
+ return nodes;
1262
+ }
1263
+
1264
+ function structureNode(element) {
1265
+ const tag = element.tagName.toLowerCase();
1266
+ const children = STRUCTURE_LEAF_TAGS.has(tag) ? [] : structureChildren(element);
1267
+ return {
1268
+ tag,
1269
+ id: element.id || '',
1270
+ classes: [...element.classList].slice(0, 2),
1271
+ // 叶子节点直接展示完整文字,容器只展示自身直属文字,避免整段内容挤进树里。
1272
+ text: children.length === 0 ? compactText(element.textContent, 40) : directTextOf(element),
1273
+ children,
1274
+ };
1275
+ }
1276
+
1277
+ function compactText(value, max) {
1278
+ return String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, max);
1279
+ }
1280
+
1281
+ function directTextOf(element) {
1282
+ let text = '';
1283
+ for (const node of element.childNodes) {
1284
+ if (node.nodeType === Node.TEXT_NODE) text += ` ${node.nodeValue}`;
1285
+ }
1286
+ return compactText(text, 40);
1287
+ }
1288
+
1289
+ function buildStructureList(nodes) {
1290
+ const list = document.createElement('ul');
1291
+ list.className = 'tree-children';
1292
+ list.setAttribute('role', 'group');
1293
+ for (const node of nodes) {
1294
+ const item = document.createElement('li');
1295
+ item.className = 'tree-item';
1296
+ item.setAttribute('role', 'none');
1297
+ const hasChildren = node.children.length > 0;
1298
+ const row = document.createElement('div');
1299
+ row.className = `tree-row tree-node${hasChildren ? ' is-branch' : ''}`;
1300
+ row.setAttribute('role', 'treeitem');
1301
+ if (hasChildren) row.setAttribute('aria-expanded', 'true');
1302
+ const caret = document.createElement('span');
1303
+ caret.className = `tree-caret${hasChildren ? '' : ' is-leaf'}`;
1304
+ const name = document.createElement('span');
1305
+ name.className = 'tree-name';
1306
+ name.textContent = formatStructureSelector(node);
1307
+ name.title = name.textContent;
1308
+ const text = document.createElement('span');
1309
+ text.className = 'tree-type';
1310
+ text.textContent = node.text;
1311
+ row.append(caret, name, text);
1312
+ if (hasChildren) {
1313
+ row.addEventListener('click', () => {
1314
+ const collapsed = item.classList.toggle('is-collapsed');
1315
+ row.setAttribute('aria-expanded', String(!collapsed));
1316
+ });
1317
+ }
1318
+ item.append(row);
1319
+ if (hasChildren) item.append(buildStructureList(node.children));
1320
+ list.append(item);
1321
+ }
1322
+ return list;
1323
+ }
1324
+
1325
+ function formatStructureSelector(node) {
1326
+ const id = node.id ? `#${node.id}` : '';
1327
+ const classes = node.classes.map((name) => `.${name}`).join('');
1328
+ return `${node.tag}${id}${classes}`;
1329
+ }
1330
+
1331
+ function sectionTitle(text) {
1332
+ const node = document.createElement('div');
1333
+ node.className = 'section-title';
1334
+ node.textContent = text;
1335
+ return node;
1336
+ }
1337
+
1338
+ function field(labelText, control) {
1339
+ const wrap = document.createElement('div');
1340
+ wrap.className = 'field';
1341
+ const label = document.createElement('label');
1342
+ label.textContent = labelText;
1343
+ wrap.append(label, control);
1344
+ return wrap;
1345
+ }
1346
+
1347
+ function input(value, { type = 'text', min, max, step } = {}) {
1348
+ const node = document.createElement('input');
1349
+ node.className = 'quiz-input';
1350
+ node.type = type;
1351
+ node.value = value ?? '';
1352
+ if (min !== undefined) node.min = min;
1353
+ if (max !== undefined) node.max = max;
1354
+ if (step !== undefined) node.step = step;
1355
+ return node;
1356
+ }
1357
+
1358
+ function select(value, options) {
1359
+ const node = document.createElement('select');
1360
+ node.className = 'quiz-input';
1361
+ for (const option of options) {
1362
+ const item = document.createElement('option');
1363
+ item.value = option;
1364
+ item.textContent = option;
1365
+ if (value === option) item.selected = true;
1366
+ node.append(item);
1367
+ }
1368
+ return node;
1369
+ }
1370
+
1371
+ function checkbox(labelText, checked) {
1372
+ const wrap = document.createElement('label');
1373
+ wrap.className = 'check-row';
1374
+ const node = document.createElement('input');
1375
+ node.type = 'checkbox';
1376
+ node.checked = Boolean(checked);
1377
+ const text = document.createElement('span');
1378
+ text.textContent = labelText;
1379
+ wrap.append(node, text);
1380
+ return { wrap, node };
1381
+ }
1382
+
1383
+ function saveRow(onSave, label = '保存') {
1384
+ const actions = document.createElement('div');
1385
+ actions.className = 'quiz-actions';
1386
+ const button = document.createElement('button');
1387
+ button.type = 'button';
1388
+ button.className = 'ghost-button';
1389
+ button.textContent = label;
1390
+ const status = document.createElement('span');
1391
+ status.className = 'muted quiz-state';
1392
+ button.addEventListener('click', async () => {
1393
+ button.disabled = true;
1394
+ status.textContent = '提交中…';
1395
+ try {
1396
+ const message = await onSave();
1397
+ status.textContent = message ?? '已保存';
1398
+ } catch (error) {
1399
+ status.textContent = `${error.code ?? '失败'}:${error.message}`;
1400
+ } finally {
1401
+ button.disabled = false;
1402
+ }
1403
+ });
1404
+ actions.append(button, status);
1405
+ return { actions, button, status };
1406
+ }
1407
+
1408
+ // 全局设置统一入口:课件元数据与页面比例不再散落在属性面板里。
1409
+ function openSettings() {
1410
+ if (!state.document?.meta) return;
1411
+ renderSettingsForm();
1412
+ el('settingsDialog').showModal();
1413
+ }
1414
+
1415
+ function renderSettingsForm() {
1416
+ const body = el('settingsBody');
1417
+ body.replaceChildren();
1418
+ const meta = state.document.meta;
1419
+ body.append(sectionTitle('基础信息'));
1420
+ const title = input(meta.title);
1421
+ const subject = select(meta.subject, SUBJECTS);
1422
+ const grade = input(meta.grade);
1423
+ const duration = input(meta.durationMin, { type: 'number', min: 10, max: 90, step: 1 });
1424
+ const ratio = select(meta.aspectRatio ?? '16:9', ASPECT_RATIOS);
1425
+ body.append(field('标题', title), field('学科', subject), field('年级', grade), field('时长(分钟)', duration));
1426
+
1427
+ body.append(sectionTitle('展示'));
1428
+ const ratioField = field('页面比例', ratio);
1429
+ const hint = document.createElement('div');
1430
+ hint.className = 'muted settings-hint';
1431
+ hint.textContent = '全局生效:Studio 预览、教师端和学生端都按该比例放映。';
1432
+ ratioField.append(hint);
1433
+ body.append(ratioField);
1434
+
1435
+ const { actions } = saveRow(async () => {
1436
+ const courseware = buildCoursewarePatch(meta, {
1437
+ title: title.value,
1438
+ subject: subject.value,
1439
+ grade: grade.value,
1440
+ durationMin: duration.value,
1441
+ aspectRatio: ratio.value,
1442
+ });
1443
+ if (!courseware.hasChanges) return '没有改动';
1444
+ const result = await saveOperations({
1445
+ summary: '更新课件全局设置',
1446
+ operations: [{ op: 'courseware.patch', set: courseware.set }],
1447
+ });
1448
+ return describeSave(result);
1449
+ }, '保存设置');
1450
+ body.append(actions);
1451
+ }
1452
+
1453
+ // 场景顺序通过拖动左侧缩略图调整,右侧不再提供场景操作区。
1454
+ async function moveSceneOperation(scene, toIndex) {
1455
+ if (!Number.isInteger(toIndex) || toIndex < 0) return;
1456
+ try {
1457
+ await saveOperations({
1458
+ summary: `调整场景 ${scene.id} 顺序`,
1459
+ operations: [{ op: 'scene.move', sceneId: scene.id, toIndex }],
1460
+ });
1461
+ // 重排后保持被拖动场景为当前场景。
1462
+ const index = state.document.scenes.findIndex((item) => item.id === scene.id);
1463
+ if (index >= 0 && index !== state.sceneIndex) {
1464
+ state.sceneIndex = index;
1465
+ renderSceneList();
1466
+ renderInspector();
1467
+ renderScene();
1468
+ }
1469
+ } catch (error) {
1470
+ el('eventLine').textContent = `${error.code ?? '失败'}:${error.message}`;
1471
+ }
1472
+ }
1473
+
1474
+ const INTERACTION_TYPE_LABELS = {
1475
+ 'single-choice': '单选题',
1476
+ 'multi-choice': '多选题',
1477
+ 'fill-blank': '填空题',
1478
+ code: '代码题',
1479
+ open: '开放题',
1480
+ };
1481
+
1482
+ function interactionTypeLabel(type) {
1483
+ return INTERACTION_TYPE_LABELS[type] ?? (type || '题目');
1484
+ }
1485
+
1486
+ // 选项键保持 A/B/C… 稳定递增,删除中间项时也不复用旧键。
1487
+ function nextOptionKey(options) {
1488
+ const used = new Set(options.map((option) => option.key));
1489
+ for (let index = 0; index < 26; index += 1) {
1490
+ const key = String.fromCharCode(65 + index);
1491
+ if (!used.has(key)) return key;
1492
+ }
1493
+ return `A${options.length + 1}`;
1494
+ }
1495
+
1496
+ function quizLabel(text) {
1497
+ const label = document.createElement('div');
1498
+ label.className = 'quiz-label';
1499
+ label.textContent = text;
1500
+ return label;
1501
+ }
1502
+
1503
+ // 题目配置:按“内容 / 答案 / 评分策略”分组,避免窄面板里控件挤成一团。
1504
+ function renderInteractionEditor(interaction) {
1505
+ const body = interaction.body ?? {};
1506
+ const card = document.createElement('div');
1507
+ card.className = 'quiz-card';
1508
+
1509
+ const head = document.createElement('div');
1510
+ head.className = 'quiz-head';
1511
+ const titleRow = document.createElement('div');
1512
+ titleRow.className = 'quiz-title-row';
1513
+ const title = document.createElement('strong');
1514
+ title.textContent = '题目';
1515
+ const typeChip = document.createElement('span');
1516
+ typeChip.className = 'quiz-chip';
1517
+ typeChip.textContent = interactionTypeLabel(body.type);
1518
+ titleRow.append(title, typeChip);
1519
+ const meta = document.createElement('span');
1520
+ meta.className = 'quiz-meta';
1521
+ meta.textContent = `${interaction.id} · ${interaction.points ?? 1} 分${interaction.graded === false ? ' · 不计成绩' : ''}`;
1522
+ head.append(titleRow, meta);
1523
+ card.append(head);
1524
+
1525
+ // 学生视角预览:与场景里的 <lume-quiz> 使用同一份渲染代码,
1526
+ // 编辑题干、选项、答案时同步刷新,做到“所见即所得”。
1527
+ let syncPreview = () => {};
1528
+ let previewSection = null;
1529
+ let previewMount = null;
1530
+ if (window.LumeQuizView && typeof window.LumeQuizView.render === 'function') {
1531
+ window.LumeQuizView.ensureStyles(document);
1532
+ previewSection = document.createElement('div');
1533
+ previewSection.className = 'quiz-section quiz-preview-section';
1534
+ previewSection.append(quizLabel('学生视角预览'));
1535
+ previewMount = document.createElement('div');
1536
+ previewMount.className = 'quiz-preview';
1537
+ previewSection.append(previewMount);
1538
+ card.append(previewSection);
1539
+ }
1540
+
1541
+ const content = document.createElement('div');
1542
+ content.className = 'quiz-section';
1543
+ content.append(quizLabel('题干'));
1544
+ const stemInput = document.createElement('textarea');
1545
+ stemInput.className = 'quiz-input quiz-stem';
1546
+ stemInput.rows = 3;
1547
+ stemInput.value = body.stem ?? '';
1548
+ stemInput.addEventListener('input', () => syncPreview());
1549
+ content.append(stemInput);
1550
+ card.append(content);
1551
+
1552
+ const isChoice = body.type === 'single-choice' || body.type === 'multi-choice';
1553
+ const optionsState = (Array.isArray(body.options) ? body.options : []).map((option) => ({
1554
+ key: String(option.key),
1555
+ text: String(option.text ?? ''),
1556
+ }));
1557
+ const chosenKeys = new Set();
1558
+ const current = body.answer ?? {};
1559
+ for (const option of optionsState) {
1560
+ if (body.type === 'multi-choice') {
1561
+ if (Array.isArray(current.choices) && current.choices.includes(option.key)) chosenKeys.add(option.key);
1562
+ } else if (current.choice === option.key) {
1563
+ chosenKeys.add(option.key);
1564
+ }
1565
+ }
1566
+ const currentAnswer = () => {
1567
+ if (!isChoice) return undefined;
1568
+ const keys = optionsState.map((option) => option.key).filter((key) => chosenKeys.has(key));
1569
+ if (keys.length === 0) return undefined;
1570
+ if (body.type === 'multi-choice') return { choices: keys };
1571
+ return { choice: keys[0] };
1572
+ };
1573
+ let repaintOptions = () => {};
1574
+
1575
+ if (isChoice) {
1576
+ const wrap = document.createElement('div');
1577
+ wrap.className = 'quiz-section';
1578
+ wrap.append(quizLabel(body.type === 'multi-choice' ? '选项与正确答案(可多选)' : '选项与正确答案'));
1579
+ const list = document.createElement('div');
1580
+ list.className = 'answer-list';
1581
+ const tools = document.createElement('div');
1582
+ tools.className = 'quiz-option-tools';
1583
+ const addButton = document.createElement('button');
1584
+ addButton.type = 'button';
1585
+ addButton.className = 'ghost-button quiz-option-add';
1586
+ addButton.textContent = '添加选项';
1587
+ const hint = document.createElement('div');
1588
+ hint.className = 'hint-warn';
1589
+ hint.textContent = '尚未配置正确答案';
1590
+ hint.hidden = chosenKeys.size > 0 || body.answerConfigured === true;
1591
+ addButton.addEventListener('click', () => {
1592
+ optionsState.push({ key: nextOptionKey(optionsState), text: '' });
1593
+ repaintOptions();
1594
+ syncPreview();
1595
+ });
1596
+ tools.append(addButton);
1597
+
1598
+ repaintOptions = () => {
1599
+ list.replaceChildren();
1600
+ for (const [index, option] of optionsState.entries()) {
1601
+ const row = document.createElement('div');
1602
+ row.className = 'answer-item';
1603
+ const node = document.createElement('input');
1604
+ node.type = body.type === 'multi-choice' ? 'checkbox' : 'radio';
1605
+ node.name = `answer-${interaction.id}`;
1606
+ node.value = option.key;
1607
+ node.checked = chosenKeys.has(option.key);
1608
+ node.addEventListener('change', () => {
1609
+ if (body.type === 'multi-choice') {
1610
+ if (node.checked) chosenKeys.add(option.key);
1611
+ else chosenKeys.delete(option.key);
1612
+ } else {
1613
+ chosenKeys.clear();
1614
+ chosenKeys.add(option.key);
1615
+ repaintChecks();
1616
+ }
1617
+ hint.hidden = chosenKeys.size > 0;
1618
+ syncPreview();
1619
+ });
1620
+ const letter = document.createElement('span');
1621
+ letter.className = 'answer-key';
1622
+ letter.textContent = option.key;
1623
+ const textInput = document.createElement('input');
1624
+ textInput.className = 'quiz-option-input';
1625
+ textInput.value = option.text;
1626
+ textInput.placeholder = `选项 ${option.key}`;
1627
+ textInput.setAttribute('aria-label', `选项 ${option.key} 内容`);
1628
+ textInput.addEventListener('input', () => {
1629
+ optionsState[index].text = textInput.value;
1630
+ syncPreview();
1631
+ });
1632
+ const remove = document.createElement('button');
1633
+ remove.type = 'button';
1634
+ remove.className = 'quiz-option-remove';
1635
+ remove.textContent = '×';
1636
+ remove.title = '删除选项';
1637
+ remove.setAttribute('aria-label', `删除选项 ${option.key}`);
1638
+ remove.disabled = optionsState.length <= 2;
1639
+ remove.addEventListener('click', () => {
1640
+ chosenKeys.delete(option.key);
1641
+ optionsState.splice(index, 1);
1642
+ repaintOptions();
1643
+ hint.hidden = chosenKeys.size > 0;
1644
+ syncPreview();
1645
+ });
1646
+ row.append(node, letter, textInput, remove);
1647
+ list.append(row);
1648
+ }
1649
+ };
1650
+ const repaintChecks = () => {
1651
+ for (const node of list.querySelectorAll('input')) {
1652
+ node.checked = chosenKeys.has(node.value);
1653
+ }
1654
+ };
1655
+ repaintOptions();
1656
+ wrap.append(list, tools, hint);
1657
+ card.append(wrap);
1658
+ } else {
1659
+ const note = document.createElement('div');
1660
+ note.className = 'quiz-section muted';
1661
+ note.textContent = body.answerConfigured ? '已配置答案(该类型需通过工具修改)' : '未配置答案';
1662
+ card.append(note);
1663
+ }
1664
+
1665
+ const policy = body.policy ?? {};
1666
+ // 评分与显示策略收进折叠区,默认只露出题干与答案,降低首屏拥挤感。
1667
+ const advanced = document.createElement('details');
1668
+ advanced.className = 'quiz-advanced';
1669
+ const summary = document.createElement('summary');
1670
+ const summaryText = document.createElement('span');
1671
+ summaryText.textContent = '评分与作答策略';
1672
+ const summaryHint = document.createElement('span');
1673
+ summaryHint.className = 'quiz-summary-hint';
1674
+ summaryHint.textContent = `${interaction.points ?? 1} 分 · 最多 ${policy.maxAttempts ?? 1} 次`;
1675
+ summary.append(summaryText, summaryHint);
1676
+ advanced.append(summary);
1677
+
1678
+ const points = input(interaction.points ?? 1, { type: 'number', min: 0, max: 100, step: 1 });
1679
+ const attempts = input(policy.maxAttempts ?? 1, { type: 'number', min: 1, max: 10, step: 1 });
1680
+ const limit = input(policy.timeLimitSec ?? 0, { type: 'number', min: 0, max: 7200, step: 1 });
1681
+ const numbers = document.createElement('div');
1682
+ numbers.className = 'quiz-grid';
1683
+ const limitField = field('作答时限(秒)', limit);
1684
+ limitField.classList.add('quiz-span-2');
1685
+ numbers.append(field('分值', points), field('最多次数', attempts), limitField);
1686
+
1687
+ const toggles = document.createElement('div');
1688
+ toggles.className = 'quiz-toggles';
1689
+ const graded = checkbox('计入成绩', interaction.graded ?? true);
1690
+ const lock = checkbox('提交后锁定', policy.lockAfterSubmit ?? true);
1691
+ const showResult = checkbox('立即显示结果', policy.showResultAfterSubmit ?? true);
1692
+ const showAnswer = checkbox('提交后显示解析', policy.showAnswerAfterSubmit ?? true);
1693
+ const shuffle = checkbox('打乱选项', policy.shuffleOptions ?? false);
1694
+ toggles.append(graded.wrap, lock.wrap, showResult.wrap, showAnswer.wrap, shuffle.wrap);
1695
+
1696
+ let partialCredit = null;
1697
+ if (body.type === 'multi-choice') {
1698
+ partialCredit = checkbox('多选部分给分', body.partialCredit ?? false);
1699
+ toggles.append(partialCredit.wrap);
1700
+ }
1701
+
1702
+ advanced.append(numbers, toggles);
1703
+ card.append(advanced);
1704
+
1705
+ if (previewMount) {
1706
+ syncPreview = () => {
1707
+ const draftPolicy = {
1708
+ maxAttempts: Number(attempts.value) || 1,
1709
+ lockAfterSubmit: lock.node.checked,
1710
+ showAnswerAfterSubmit: showAnswer.node.checked,
1711
+ showResultAfterSubmit: showResult.node.checked,
1712
+ shuffleOptions: shuffle.node.checked,
1713
+ timeLimitSec: Number(limit.value) || 0,
1714
+ };
1715
+ window.LumeQuizView.render(previewMount, {
1716
+ id: interaction.id,
1717
+ type: body.type,
1718
+ stem: stemInput.value,
1719
+ options: optionsState.map((option) => ({ key: option.key, text: option.text })),
1720
+ explain: body.explain,
1721
+ points: Number(points.value) || 0,
1722
+ graded: graded.node.checked,
1723
+ partialCredit: body.partialCredit,
1724
+ policy: draftPolicy,
1725
+ // 仅 Studio 预览携带答案,用于即时试答判分;学生端注入的数据不含答案。
1726
+ answer: currentAnswer() ?? body.answer ?? null,
1727
+ });
1728
+ };
1729
+ syncPreview();
1730
+ }
1731
+
1732
+ const { actions, status } = saveRow(async () => {
1733
+ const chosen = optionsState.map((option) => option.key).filter((key) => chosenKeys.has(key));
1734
+ let answer;
1735
+ if (body.type === 'single-choice' && chosen.length === 1) answer = { choice: chosen[0] };
1736
+ else if (body.type === 'multi-choice' && chosen.length > 0) answer = { choices: chosen };
1737
+ const form = {
1738
+ stem: stemInput.value,
1739
+ options: optionsState.map((option) => ({ key: option.key, text: option.text })),
1740
+ points: points.value,
1741
+ graded: graded.node.checked,
1742
+ policy: {
1743
+ maxAttempts: Number(attempts.value) || 1,
1744
+ lockAfterSubmit: lock.node.checked,
1745
+ showAnswerAfterSubmit: showAnswer.node.checked,
1746
+ showResultAfterSubmit: showResult.node.checked,
1747
+ shuffleOptions: shuffle.node.checked,
1748
+ timeLimitSec: Number(limit.value) || 0,
1749
+ },
1750
+ answer,
1751
+ partialCredit: partialCredit ? partialCredit.node.checked : undefined,
1752
+ };
1753
+ if (body.type === 'multi-choice' && partialCredit?.node.checked && chosen.length > 0) {
1754
+ form.answerKeys = chosen;
1755
+ }
1756
+ const patch = buildInteractionPatch(interaction, form);
1757
+ if (!patch.hasChanges) return '没有改动';
1758
+ const result = await saveOperations({
1759
+ summary: `更新题目 ${interaction.id}`,
1760
+ operations: [{
1761
+ op: 'interaction.upsert',
1762
+ interactionId: interaction.id,
1763
+ sceneId: interaction.scene,
1764
+ points: patch.points,
1765
+ graded: patch.graded,
1766
+ value: patch.value,
1767
+ }],
1768
+ });
1769
+ return describeSave(result);
1770
+ }, '保存题目');
1771
+ actions.classList.add('quiz-footer');
1772
+ card.append(actions);
1773
+ return card;
1774
+ }
1775
+
1776
+ function renderDiagnostics() {
1777
+ const block = document.createElement('div');
1778
+ block.append(sectionTitle('校验'));
1779
+ const diagnostics = state.document.report.items ?? [];
1780
+ if (diagnostics.length === 0) {
1781
+ const ok = document.createElement('div');
1782
+ ok.className = 'diagnostic';
1783
+ ok.textContent = '没有发现错误或提示。';
1784
+ block.append(ok);
1785
+ return block;
1786
+ }
1787
+ for (const item of diagnostics.slice(0, 40)) {
1788
+ const card = document.createElement('div');
1789
+ card.className = `diagnostic ${item.level}`;
1790
+ const head = document.createElement('div');
1791
+ const strong = document.createElement('strong');
1792
+ strong.textContent = item.level === 'error' ? '错误' : '提示';
1793
+ const code = document.createElement('span');
1794
+ code.className = 'code';
1795
+ code.textContent = `${item.code} ${item.path}`;
1796
+ head.append(strong, document.createTextNode(' '), code);
1797
+ const message = document.createElement('div');
1798
+ message.className = 'muted';
1799
+ message.textContent = item.message;
1800
+ card.append(head, message);
1801
+ block.append(card);
1802
+ }
1803
+ return block;
1804
+ }
1805
+
1806
+ // 统一保存入口:处理 revision 冲突、高影响确认与刷新。
1807
+ async function saveOperations({ summary, operations, confirmation }) {
1808
+ const baseRevision = state.document.revision;
1809
+ let response;
1810
+ try {
1811
+ response = await api('/api/invoke', {
1812
+ method: 'POST',
1813
+ body: JSON.stringify({
1814
+ tool: 'courseware.apply',
1815
+ args: {
1816
+ operationId: nextOperationId('ui'),
1817
+ baseRevision,
1818
+ summary,
1819
+ operations,
1820
+ ...(confirmation ? { confirmation } : {}),
1821
+ awaitAck: true,
1822
+ awaitAckMs: 1500,
1823
+ },
1824
+ }),
1825
+ });
1826
+ } catch (error) {
1827
+ if (error.code === 'REVISION_CONFLICT') await loadDocument({ rebuild: false }).catch(() => {});
1828
+ throw error;
1829
+ }
1830
+ const result = response.result ?? {};
1831
+ // 题目数据不参与场景 HTML 的哈希,需要记录受影响的场景,保存后主动刷新预览。
1832
+ const quizScenes = [...new Set(operations
1833
+ .filter((operation) => operation.op === 'interaction.upsert' && operation.sceneId)
1834
+ .map((operation) => operation.sceneId))];
1835
+ if (result.pending) {
1836
+ state.pendingPreviewScenes = quizScenes;
1837
+ openConfirmation(result, async (change) => {
1838
+ const responseRetry = await api('/api/invoke', {
1839
+ method: 'POST',
1840
+ body: JSON.stringify({
1841
+ tool: 'courseware.apply',
1842
+ args: {
1843
+ operationId: nextOperationId('ui'),
1844
+ baseRevision: change.baseRevision,
1845
+ summary,
1846
+ operations,
1847
+ confirmation: change,
1848
+ awaitAck: true,
1849
+ awaitAckMs: 1500,
1850
+ },
1851
+ }),
1852
+ });
1853
+ return responseRetry.result ?? {};
1854
+ });
1855
+ return result;
1856
+ }
1857
+ await loadDocument({ rebuild: false });
1858
+ if (result.committed) {
1859
+ recordUndo(baseRevision);
1860
+ updateEditButtons();
1861
+ if (quizScenes.length > 0) refreshInteractionPreviews(quizScenes);
1862
+ }
1863
+ return result;
1864
+ }
1865
+
1866
+ // 让题目编辑后的预览与缩略图重新取数,保证显示内容与保存结果一致。
1867
+ function refreshInteractionPreviews(sceneIds) {
1868
+ let refreshMain = false;
1869
+ for (const sceneId of sceneIds) {
1870
+ const scene = state.document.scenes.find((item) => item.id === sceneId);
1871
+ if (!scene) continue;
1872
+ const entry = state.sceneItems.get(sceneId);
1873
+ if (entry) {
1874
+ delete entry.frame.dataset.hash;
1875
+ entry.frame.src = `${scene.contentUrl}?v=${state.document.revision}&thumb=1`;
1876
+ }
1877
+ if (state.document.scenes[state.sceneIndex]?.id === sceneId) refreshMain = true;
1878
+ }
1879
+ if (refreshMain) renderScene({ force: true });
1880
+ }
1881
+
1882
+ function describeSave(result) {
1883
+ if (!result) return '未写入';
1884
+ if (result.pending) return '需要确认后提交';
1885
+ if (result.committed) {
1886
+ const ack = result.renderAck?.acknowledged ? '预览已渲染' : '等待预览端';
1887
+ return `已保存 · rev ${result.revision} · ${ack}`;
1888
+ }
1889
+ return '未写入';
1890
+ }
1891
+
1892
+ function openConfirmation(pending, retry) {
1893
+ state.confirmation = { pending, retry };
1894
+ const reasons = (pending.reasons ?? []).map((reason) => reason.message ?? reason.code).join(';');
1895
+ el('confirmReason').textContent = reasons || '该操作会修改答案、评分或删除内容。';
1896
+ renderDiff(pending.preview?.diff, el('confirmDiff'));
1897
+ el('confirmState').textContent = '';
1898
+ if (!el('confirmDialog').open) el('confirmDialog').showModal();
1899
+ }
1900
+
1901
+ function closeConfirmation() {
1902
+ state.confirmation = null;
1903
+ el('confirmDialog').close();
1904
+ }
1905
+
1906
+ async function confirmPending() {
1907
+ const current = state.confirmation;
1908
+ if (!current) return;
1909
+ el('confirmApply').disabled = true;
1910
+ el('confirmState').textContent = '提交中…';
1911
+ try {
1912
+ const result = await current.retry(current.pending.change);
1913
+ const baseRevision = current.pending.change?.baseRevision ?? current.pending.baseRevision;
1914
+ const quizScenes = state.pendingPreviewScenes ?? [];
1915
+ state.pendingPreviewScenes = null;
1916
+ closeConfirmation();
1917
+ await loadDocument({ rebuild: true });
1918
+ if (result?.committed) {
1919
+ recordUndo(baseRevision);
1920
+ if (quizScenes.length > 0) refreshInteractionPreviews(quizScenes);
1921
+ }
1922
+ updateEditButtons();
1923
+ el('eventLine').textContent = describeSave(result);
1924
+ } catch (error) {
1925
+ el('confirmState').textContent = `${error.code ?? '失败'}:${error.message}`;
1926
+ await loadDocument({ rebuild: false }).catch(() => {});
1927
+ } finally {
1928
+ el('confirmApply').disabled = false;
1929
+ }
1930
+ }
1931
+
1932
+ function renderDiff(diff, container) {
1933
+ container.replaceChildren();
1934
+ if (!diff || !Array.isArray(diff.files) || diff.files.length === 0) {
1935
+ const empty = document.createElement('div');
1936
+ empty.className = 'muted';
1937
+ empty.textContent = '没有文件差异。';
1938
+ container.append(empty);
1939
+ return;
1940
+ }
1941
+ if (diff.summary) {
1942
+ const summary = document.createElement('div');
1943
+ summary.className = 'diff-summary';
1944
+ summary.textContent = diff.summary;
1945
+ container.append(summary);
1946
+ }
1947
+ for (const file of diff.files.slice(0, 40)) {
1948
+ const card = document.createElement('details');
1949
+ card.className = 'diff-file';
1950
+ const summary = document.createElement('summary');
1951
+ const label = document.createElement('span');
1952
+ label.className = `diff-kind ${file.kind}`;
1953
+ label.textContent = file.kind;
1954
+ summary.append(label, document.createTextNode(` ${file.path}`));
1955
+ if (file.answerChanged) {
1956
+ const badge = document.createElement('span');
1957
+ badge.className = 'chip chip-warn';
1958
+ badge.textContent = '答案变化';
1959
+ summary.append(badge);
1960
+ }
1961
+ card.append(summary);
1962
+ if (file.binary) {
1963
+ const pre = document.createElement('pre');
1964
+ pre.textContent = JSON.stringify({ before: file.before, after: file.after }, null, 2);
1965
+ card.append(pre);
1966
+ } else {
1967
+ for (const side of ['before', 'after']) {
1968
+ if (file[side] === null || file[side] === undefined) continue;
1969
+ const caption = document.createElement('div');
1970
+ caption.className = 'diff-caption';
1971
+ caption.textContent = `${side}${file[`${side}Truncated`] ? '(截断)' : ''}`;
1972
+ const pre = document.createElement('pre');
1973
+ pre.textContent = file[side];
1974
+ card.append(caption, pre);
1975
+ }
1976
+ }
1977
+ container.append(card);
1978
+ }
1979
+ }
1980
+
1981
+ // 导出:下载当前课件的 .lume 包,便于备份或分享给其他工作区。
1982
+ async function downloadCourseware() {
1983
+ const button = el('exportButton');
1984
+ button.disabled = true;
1985
+ try {
1986
+ const response = await fetch('/api/export', { credentials: 'same-origin' });
1987
+ if (!response.ok) {
1988
+ const value = await response.json().catch(() => null);
1989
+ throw new Error(value?.error?.message ?? `导出失败:HTTP ${response.status}`);
1990
+ }
1991
+ const blob = await response.blob();
1992
+ const match = /filename="([^"]+)"/.exec(response.headers.get('content-disposition') ?? '');
1993
+ const name = match?.[1] ?? `${state.document?.coursewareId ?? 'courseware'}.lume`;
1994
+ const url = URL.createObjectURL(blob);
1995
+ const link = document.createElement('a');
1996
+ link.href = url;
1997
+ link.download = name;
1998
+ document.body.append(link);
1999
+ link.click();
2000
+ link.remove();
2001
+ URL.revokeObjectURL(url);
2002
+ el('renderLine').textContent = `已导出 ${name}`;
2003
+ } catch (error) {
2004
+ el('renderLine').textContent = error.message;
2005
+ } finally {
2006
+ button.disabled = false;
2007
+ }
2008
+ }
2009
+
2010
+ // 导入:选择 .lume 文件后先确认,再上传;服务端会以新 revision 提交并保留历史。
2011
+ function chooseImportFile() {
2012
+ el('importInput').click();
2013
+ }
2014
+
2015
+ function handleImportSelection(event) {
2016
+ const file = event.target.files?.[0];
2017
+ event.target.value = '';
2018
+ if (!file) return;
2019
+ state.pendingImport = file;
2020
+ const title = state.document?.meta?.title ?? '当前课件';
2021
+ el('importSummary').textContent = `将用 ${file.name}(${formatBytes(file.size)})替换「${title}」。`;
2022
+ el('importState').textContent = '';
2023
+ el('confirmImport').disabled = false;
2024
+ if (!el('importDialog').open) el('importDialog').showModal();
2025
+ }
2026
+
2027
+ function formatBytes(bytes) {
2028
+ if (!Number.isFinite(bytes)) return '未知大小';
2029
+ if (bytes < 1024) return `${bytes} B`;
2030
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
2031
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2032
+ }
2033
+
2034
+ async function confirmImport() {
2035
+ const file = state.pendingImport;
2036
+ if (!file) return;
2037
+ const button = el('confirmImport');
2038
+ button.disabled = true;
2039
+ el('importState').textContent = '导入中…';
2040
+ const baseRevision = state.document?.revision;
2041
+ try {
2042
+ const response = await fetch('/api/import', {
2043
+ method: 'POST',
2044
+ headers: { 'content-type': 'application/octet-stream' },
2045
+ body: file,
2046
+ credentials: 'same-origin',
2047
+ });
2048
+ const value = await response.json().catch(() => null);
2049
+ if (!response.ok) throw new Error(value?.error?.message ?? `导入失败:HTTP ${response.status}`);
2050
+ state.pendingImport = null;
2051
+ state.sceneIndex = 0;
2052
+ state.staleScenes.clear();
2053
+ state.sceneHashes.clear();
2054
+ el('importDialog').close();
2055
+ await loadDocument({ rebuild: true });
2056
+ if (Number.isInteger(baseRevision)) recordUndo(baseRevision);
2057
+ updateEditButtons();
2058
+ el('eventLine').textContent = `已导入 ${value.title ?? value.coursewareId ?? ''} · ${value.scenes ?? 0} 场景 · rev ${value.revision}`;
2059
+ } catch (error) {
2060
+ el('importState').textContent = error.message;
2061
+ button.disabled = false;
2062
+ }
2063
+ }
2064
+
2065
+ // 撤销/重做在输入框内交给浏览器原生文本撤销,避免打断录入。
2066
+ function handleEditShortcut(event) {
2067
+ const mod = event.metaKey || event.ctrlKey;
2068
+ if (!mod) return;
2069
+ const key = event.key.toLowerCase();
2070
+ if (key === 's') {
2071
+ event.preventDefault();
2072
+ saveAll();
2073
+ return;
2074
+ }
2075
+ if (key !== 'z' && key !== 'y') return;
2076
+ const target = event.target;
2077
+ const editing = target instanceof HTMLElement
2078
+ && (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));
2079
+ if (editing) return;
2080
+ event.preventDefault();
2081
+ if (key === 'y' || event.shiftKey) redoEdit();
2082
+ else undoEdit();
2083
+ }
2084
+
2085
+ // ---- AI 对话(Agent 信箱)与预览元素选择 ----
2086
+ // 浏览器只负责把消息写入信箱;启动 Studio 的 Agent 通过 chat 命令拉取并回复。
2087
+ const CHAT_POLL_MS = 2500;
2088
+
2089
+ function toggleChat() {
2090
+ setChatOpen(!state.chatOpen);
2091
+ }
2092
+
2093
+ function setChatOpen(open) {
2094
+ state.chatOpen = open;
2095
+ el('chatPanel').hidden = !open;
2096
+ el('chatButton').setAttribute('aria-expanded', String(open));
2097
+ el('chatButton').classList.toggle('is-active', open);
2098
+ if (open) {
2099
+ state.chatUnread = 0;
2100
+ updateChatButton();
2101
+ renderChat();
2102
+ loadChat();
2103
+ if (!state.chatTimer) state.chatTimer = setInterval(() => loadChat(), CHAT_POLL_MS);
2104
+ } else {
2105
+ if (state.chatTimer) {
2106
+ clearInterval(state.chatTimer);
2107
+ state.chatTimer = null;
2108
+ }
2109
+ setPicking(false);
2110
+ }
2111
+ }
2112
+
2113
+ function updateChatButton() {
2114
+ el('chatButton').classList.toggle('has-unread', !state.chatOpen && state.chatUnread > 0);
2115
+ }
2116
+
2117
+ async function loadChat() {
2118
+ try {
2119
+ const payload = await api(`/api/chat?since=${state.chatCursor}&limit=100`);
2120
+ let added = false;
2121
+ for (const message of payload.messages ?? []) {
2122
+ if (appendChatMessage(message)) added = true;
2123
+ }
2124
+ if (Number.isInteger(payload.cursor)) state.chatCursor = Math.max(state.chatCursor, payload.cursor);
2125
+ // 认领状态变化也要重绘,界面才能从“等待处理”切到“处理中”。
2126
+ const claimed = new Set(payload.claimed ?? []);
2127
+ const claimedChanged = claimed.size !== state.chatClaimed.size
2128
+ || [...claimed].some((id) => !state.chatClaimed.has(id));
2129
+ state.chatClaimed = claimed;
2130
+ if (added || claimedChanged) renderChat();
2131
+ if (state.chatOpen) {
2132
+ el('chatState').textContent = payload.pending > 0 ? `等待 Agent · ${payload.pending}` : 'Agent 信箱';
2133
+ }
2134
+ } catch {
2135
+ if (state.chatOpen) el('chatState').textContent = '无法连接信箱';
2136
+ }
2137
+ }
2138
+
2139
+ function appendChatMessage(message) {
2140
+ if (!message || typeof message.id !== 'string' || state.chatIds.has(message.id)) return false;
2141
+ state.chatIds.add(message.id);
2142
+ state.chatMessages.push(message);
2143
+ return true;
2144
+ }
2145
+
2146
+ function renderChat() {
2147
+ const list = el('chatMessages');
2148
+ if (!list) return;
2149
+ const atBottom = list.scrollHeight - list.scrollTop - list.clientHeight < 48;
2150
+ list.replaceChildren();
2151
+ if (state.chatMessages.length === 0) {
2152
+ const empty = document.createElement('p');
2153
+ empty.className = 'chat-empty muted';
2154
+ empty.textContent = '把修改要求发到这里;点击右上角准星可在预览中选择元素。';
2155
+ list.append(empty);
2156
+ return;
2157
+ }
2158
+ const replied = new Set(
2159
+ state.chatMessages
2160
+ .filter((message) => message.role === 'agent' && message.inReplyTo)
2161
+ .map((message) => message.inReplyTo),
2162
+ );
2163
+ for (const message of state.chatMessages) list.append(createChatBubble(message, replied));
2164
+ if (atBottom) list.scrollTop = list.scrollHeight;
2165
+ }
2166
+
2167
+ function createChatBubble(message, replied) { const role = message.role === 'agent' ? 'agent' : message.role === 'system' ? 'system' : 'user';
2168
+ const article = document.createElement('article');
2169
+ article.className = `chat-msg ${role}`;
2170
+ if (role !== 'system') {
2171
+ const head = document.createElement('div');
2172
+ head.className = 'chat-msg-head';
2173
+ const who = document.createElement('span');
2174
+ who.textContent = role === 'agent' ? 'Agent' : '我';
2175
+ head.append(who);
2176
+ if (Number.isInteger(message.revision)) {
2177
+ const rev = document.createElement('span');
2178
+ rev.className = 'chat-rev';
2179
+ rev.textContent = `rev ${message.revision}`;
2180
+ head.append(rev);
2181
+ }
2182
+ if (role === 'user') {
2183
+ const status = document.createElement('span');
2184
+ status.className = 'chat-status';
2185
+ if (replied.has(message.id)) {
2186
+ status.textContent = '已处理';
2187
+ } else if (state.chatClaimed.has(message.id)) {
2188
+ status.textContent = '处理中';
2189
+ status.classList.add('is-claimed');
2190
+ } else {
2191
+ status.textContent = '等待处理';
2192
+ }
2193
+ head.append(status);
2194
+ }
2195
+ article.append(head);
2196
+ }
2197
+ const body = document.createElement('div');
2198
+ body.className = 'chat-msg-body';
2199
+ body.textContent = message.text || '(仅选中元素)';
2200
+ article.append(body);
2201
+ if (message.selection) {
2202
+ const ref = document.createElement('span');
2203
+ ref.className = 'chat-ref';
2204
+ const selection = message.selection;
2205
+ ref.textContent = `选中 ${selection.tag || '元素'}${selection.text ? ` · ${selection.text.slice(0, 40)}` : ''}`;
2206
+ ref.title = selection.selector || '';
2207
+ article.append(ref);
2208
+ }
2209
+ return article;
2210
+ }
2211
+
2212
+ function renderChatSelection() {
2213
+ const box = el('chatSelection');
2214
+ box.replaceChildren();
2215
+ const selection = state.chatSelection;
2216
+ if (!selection) {
2217
+ box.hidden = true;
2218
+ return;
2219
+ }
2220
+ box.hidden = false;
2221
+ const ref = document.createElement('span');
2222
+ ref.className = 'chat-ref';
2223
+ ref.textContent = `已选 <${selection.tag || '元素'}>${selection.text ? ` · ${selection.text.slice(0, 36)}` : ''}`;
2224
+ ref.title = selection.selector || '';
2225
+ const clear = document.createElement('button');
2226
+ clear.type = 'button';
2227
+ clear.className = 'icon-button';
2228
+ clear.title = '清除选区';
2229
+ clear.setAttribute('aria-label', '清除选区');
2230
+ clear.textContent = '×';
2231
+ clear.addEventListener('click', () => {
2232
+ state.chatSelection = null;
2233
+ renderChatSelection();
2234
+ });
2235
+ box.append(ref, clear);
2236
+ }
2237
+
2238
+ function setPicking(enabled) {
2239
+ if (enabled) {
2240
+ if (state.sourceMode) {
2241
+ el('chatState').textContent = '请先切回预览';
2242
+ return;
2243
+ }
2244
+ if (!currentScene()) return;
2245
+ }
2246
+ state.chatPicking = enabled;
2247
+ const button = el('chatPick');
2248
+ button.setAttribute('aria-pressed', String(enabled));
2249
+ button.classList.toggle('is-active', enabled);
2250
+ el('pickHint').hidden = !enabled;
2251
+ postPickMode(enabled);
2252
+ }
2253
+
2254
+ function postPickMode(enabled) {
2255
+ const frame = el('previewFrame');
2256
+ try {
2257
+ frame.contentWindow?.postMessage({ source: 'lume-host', type: 'pick-mode', enabled }, '*');
2258
+ } catch {
2259
+ // iframe 尚未就绪时忽略,加载后会再次下发。
2260
+ }
2261
+ }
2262
+
2263
+ function handlePicked(data) {
2264
+ if (data.type !== 'picked' || !data.selection) {
2265
+ setPicking(false);
2266
+ return;
2267
+ }
2268
+ state.chatSelection = {
2269
+ ...data.selection,
2270
+ sceneId: currentScene()?.id ?? data.selection.sceneId ?? null,
2271
+ };
2272
+ setPicking(false);
2273
+ renderChatSelection();
2274
+ el('chatInput').focus();
2275
+ el('chatState').textContent = `已选 ${state.chatSelection.tag || '元素'}`;
2276
+ }
2277
+
2278
+ async function sendChat() {
2279
+ if (state.chatSending) return;
2280
+ const input = el('chatInput');
2281
+ const text = input.value.trim();
2282
+ const selection = state.chatSelection;
2283
+ if (!text && !selection) return;
2284
+ // 源码草稿尚未提交时先落盘,让 Agent 读到最新 revision。
2285
+ if (state.sourceMode) await flushSource();
2286
+ state.chatSending = true;
2287
+ el('chatSend').disabled = true;
2288
+ el('chatState').textContent = '发送中…';
2289
+ try {
2290
+ const payload = await api('/api/chat', {
2291
+ method: 'POST',
2292
+ body: JSON.stringify({ text, selection, revision: state.document?.revision }),
2293
+ });
2294
+ input.value = '';
2295
+ state.chatSelection = null;
2296
+ renderChatSelection();
2297
+ if (appendChatMessage(payload.message)) renderChat();
2298
+ state.chatCursor = Math.max(state.chatCursor, payload.cursor ?? 0);
2299
+ el('chatState').textContent = '已送达 · 等待 Agent';
2300
+ } catch (error) {
2301
+ el('chatState').textContent = `发送失败:${error.message}`;
2302
+ } finally {
2303
+ state.chatSending = false;
2304
+ el('chatSend').disabled = false;
2305
+ }
2306
+ }
2307
+
2308
+ function bindControls() {
2309
+ el('prevScene').addEventListener('click', () => moveScene(-1));
2310
+ el('nextScene').addEventListener('click', () => moveScene(1));
2311
+ el('undoButton').addEventListener('click', undoEdit);
2312
+ el('redoButton').addEventListener('click', redoEdit);
2313
+ el('saveButton').addEventListener('click', saveAll);
2314
+ el('sourceToggle').addEventListener('click', () => setSourceMode(!state.sourceMode));
2315
+ el('sourceCode').addEventListener('input', updateSourceState);
2316
+ el('sourceCode').addEventListener('scroll', syncSourceScroll);
2317
+ el('sourceCode').addEventListener('compositionstart', () => {
2318
+ el('sourceCode').classList.add('is-composing');
2319
+ el('sourceCodeLayer').classList.add('is-composing');
2320
+ });
2321
+ el('sourceCode').addEventListener('compositionend', () => {
2322
+ el('sourceCode').classList.remove('is-composing');
2323
+ el('sourceCodeLayer').classList.remove('is-composing');
2324
+ renderSourceView();
2325
+ });
2326
+ document.addEventListener('keydown', handleEditShortcut);
2327
+ el('saveNotes').addEventListener('click', onSaveNotes);
2328
+ el('toggleInspector').addEventListener('click', toggleInspector);
2329
+ setupPanelResizers();
2330
+ el('tabStructure').addEventListener('click', () => setInspectorTab('structure'));
2331
+ el('tabProps').addEventListener('click', () => setInspectorTab('props'));
2332
+ el('importButton').addEventListener('click', chooseImportFile);
2333
+ el('exportButton').addEventListener('click', downloadCourseware);
2334
+ el('importInput').addEventListener('change', handleImportSelection);
2335
+ el('cancelImport').addEventListener('click', () => el('importDialog').close());
2336
+ el('confirmImport').addEventListener('click', confirmImport);
2337
+ el('importDialog').addEventListener('close', () => { state.pendingImport = null; });
2338
+ el('refreshButton').addEventListener('click', async () => {
2339
+ await loadDocument({ rebuild: true });
2340
+ });
2341
+ el('historyButton').addEventListener('click', openHistory);
2342
+ el('chatButton').addEventListener('click', toggleChat);
2343
+ el('chatClose').addEventListener('click', () => setChatOpen(false));
2344
+ el('chatPick').addEventListener('click', () => setPicking(!state.chatPicking));
2345
+ el('chatForm').addEventListener('submit', (event) => {
2346
+ event.preventDefault();
2347
+ sendChat();
2348
+ });
2349
+ el('chatInput').addEventListener('keydown', (event) => {
2350
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
2351
+ event.preventDefault();
2352
+ sendChat();
2353
+ }
2354
+ });
2355
+ el('settingsButton').addEventListener('click', openSettings);
2356
+ el('closeSettings').addEventListener('click', () => el('settingsDialog').close());
2357
+ el('closeHistory').addEventListener('click', () => el('historyDialog').close());
2358
+ el('cancelConfirm').addEventListener('click', closeConfirmation);
2359
+ el('confirmApply').addEventListener('click', confirmPending);
2360
+ el('confirmDialog').addEventListener('close', () => { state.confirmation = null; });
2361
+ for (const frame of document.querySelectorAll('.preview-frame')) {
2362
+ frame.addEventListener('load', () => {
2363
+ // 后台帧加载完成时先不处理,交换后由 loadSceneIntoBuffer 统一同步。
2364
+ if (frame.id !== 'previewFrame') return;
2365
+ syncFrame();
2366
+ // 换页或刷新后把选择模式重新下发给新的预览文档。
2367
+ if (state.chatPicking) postPickMode(true);
2368
+ });
2369
+ }
2370
+ window.addEventListener('message', receiveMessage);
2371
+ window.addEventListener('keydown', (event) => {
2372
+ if (event.key === 'Escape' && state.chatPicking) {
2373
+ setPicking(false);
2374
+ return;
2375
+ }
2376
+ if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) return;
2377
+ if (event.key === 'ArrowRight') moveScene(1);
2378
+ if (event.key === 'ArrowLeft') moveScene(-1);
2379
+ });
2380
+ }
2381
+
2382
+ function moveScene(delta) {
2383
+ if (!state.document?.scenes) return;
2384
+ if (state.chatPicking) setPicking(false);
2385
+ const next = state.sceneIndex + delta;
2386
+ if (next < 0 || next >= state.document.scenes.length) return;
2387
+ state.sceneIndex = next;
2388
+ state.pendingStates = {};
2389
+ state.staleScenes.delete(state.document.scenes[next].id);
2390
+ renderSceneList();
2391
+ renderInspector();
2392
+ renderScene({ force: true });
2393
+ }
2394
+
2395
+ function receiveMessage(event) {
2396
+ const frame = el('previewFrame');
2397
+ if (event.source !== frame.contentWindow || event.origin !== 'null') return;
2398
+ const data = event.data;
2399
+ // 元素选择桥与课件 SDK 分属不同消息来源,先处理选择结果。
2400
+ if (data?.source === 'lume-picker') {
2401
+ handlePicked(data);
2402
+ return;
2403
+ }
2404
+ if (!data || data.source !== 'lume-courseware') return;
2405
+ if (data.type === 'ready') {
2406
+ if (data.sceneId && data.sceneId !== currentScene()?.id) return;
2407
+ syncFrame();
2408
+ return;
2409
+ }
2410
+ if (data.type === 'render-ack') {
2411
+ if (data.revision !== state.document.revision) return;
2412
+ if (data.sceneId && data.sceneId !== currentScene()?.id) return;
2413
+ state.pendingStates = {};
2414
+ reportRenderAck();
2415
+ return;
2416
+ }
2417
+ if (data.type === 'navigate') {
2418
+ if (data.sceneId) {
2419
+ const index = state.document.scenes.findIndex((scene) => scene.id === data.sceneId);
2420
+ if (index >= 0) {
2421
+ state.sceneIndex = index;
2422
+ renderSceneList();
2423
+ renderInspector();
2424
+ renderScene({ force: true });
2425
+ }
2426
+ }
2427
+ if (typeof data.delta === 'number') moveScene(data.delta);
2428
+ return;
2429
+ }
2430
+ if (data.type === 'state' && typeof data.cid === 'string') {
2431
+ state.pendingStates[data.cid] = { state: data.state, seq: Number.isFinite(data.seq) ? data.seq : 0 };
2432
+ return;
2433
+ }
2434
+ if (data.type === 'event') {
2435
+ el('eventLine').textContent = `${data.action} · ${data.cid ?? ''}`;
2436
+ }
2437
+ }
2438
+
2439
+ function reportRenderAck() {
2440
+ el('renderLine').textContent = `已渲染 rev ${state.document.revision}`;
2441
+ if (!state.socket || state.socket.readyState !== WebSocket.OPEN) return;
2442
+ state.socket.send(JSON.stringify({
2443
+ type: 'renderAck',
2444
+ revision: state.document.revision,
2445
+ sceneId: currentScene()?.id ?? null,
2446
+ coursewareId: state.document.coursewareId,
2447
+ }));
2448
+ }
2449
+
2450
+ function connectSocket() {
2451
+ const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
2452
+ const socket = new WebSocket(`${scheme}://${location.host}/ws`);
2453
+ state.socket = socket;
2454
+ socket.addEventListener('open', () => {
2455
+ updateStatusBadge('connected');
2456
+ socket.send(JSON.stringify({ type: 'ping' }));
2457
+ });
2458
+ socket.addEventListener('close', () => {
2459
+ updateStatusBadge('closed');
2460
+ setTimeout(connectSocket, 2000);
2461
+ });
2462
+ socket.addEventListener('error', () => updateStatusBadge('closed'));
2463
+ socket.addEventListener('message', (event) => {
2464
+ state.connected = true;
2465
+ let message;
2466
+ try {
2467
+ message = JSON.parse(event.data);
2468
+ } catch {
2469
+ return;
2470
+ }
2471
+ if (message.type === 'studio.hello') {
2472
+ updateStatusBadge('connected');
2473
+ return;
2474
+ }
2475
+ if (message.type === 'courseware.snapshot') {
2476
+ if (state.document && message.revision < state.document.revision) return;
2477
+ const previousSceneId = currentScene()?.id;
2478
+ state.document = message.document;
2479
+ state.lastRenderedRevision = message.revision;
2480
+ const index = state.document.scenes.findIndex((scene) => scene.id === previousSceneId);
2481
+ if (index >= 0) state.sceneIndex = index;
2482
+ rememberSceneHashes();
2483
+ renderAll();
2484
+ return;
2485
+ }
2486
+ if (message.type === 'courseware.changed') {
2487
+ applyChange(message);
2488
+ return;
2489
+ }
2490
+ if (message.type === 'preview.goto') {
2491
+ const index = state.document.scenes.findIndex((scene) => scene.id === message.sceneId);
2492
+ if (index >= 0) {
2493
+ state.sceneIndex = index;
2494
+ renderSceneList();
2495
+ renderInspector();
2496
+ renderScene({ force: true });
2497
+ }
2498
+ return;
2499
+ }
2500
+ if (message.type === 'preview.ack') {
2501
+ el('renderLine').textContent = `已渲染 rev ${message.revision}`;
2502
+ return;
2503
+ }
2504
+ if (message.type === 'chat.message') {
2505
+ if (state.chatOpen) loadChat();
2506
+ else if (message.message?.role === 'agent') {
2507
+ state.chatUnread += 1;
2508
+ updateChatButton();
2509
+ }
2510
+ }
2511
+ });
2512
+ }
2513
+
2514
+ // 先分析变更,再做最小刷新:无关场景与纯元数据提交不重建 iframe。
2515
+ async function applyChange(message) {
2516
+ const previousIndex = state.sceneIndex;
2517
+ const previousSceneId = state.document?.scenes?.[previousIndex]?.id;
2518
+ const payload = await api('/api/document').catch(() => null);
2519
+ if (!payload) {
2520
+ el('eventLine').textContent = '文档读取失败,等待下一次同步';
2521
+ return;
2522
+ }
2523
+ if (state.document && payload.revision < state.document.revision) {
2524
+ // 并发提交时较早的读取结果可能晚到,不能把 revision 回退。
2525
+ return;
2526
+ }
2527
+ const previousHashes = new Map(state.sceneHashes);
2528
+ state.document = payload.document;
2529
+ state.lastRenderedRevision = payload.revision;
2530
+ for (const scene of state.document.scenes) {
2531
+ if (previousHashes.has(scene.id) && previousHashes.get(scene.id) !== scene.contentHash) {
2532
+ state.staleScenes.add(scene.id);
2533
+ }
2534
+ state.sceneHashes.set(scene.id, scene.contentHash);
2535
+ }
2536
+ const nextIndex = state.document.scenes.findIndex((scene) => scene.id === previousSceneId);
2537
+ state.sceneIndex = nextIndex >= 0 ? nextIndex : Math.min(previousIndex, state.document.scenes.length - 1);
2538
+ state.staleScenes.delete(state.document.scenes[state.sceneIndex]?.id);
2539
+ const assetChanged = (message.changes ?? []).some((change) => change.kind === 'asset');
2540
+ const orderChanged = (message.changes ?? []).some((change) => change.kind === 'scene-order');
2541
+ const imported = (message.changes ?? []).some((change) => change.kind === 'import');
2542
+ if (nextIndex < 0 || assetChanged || orderChanged || imported || previousHashes.size !== state.document.scenes.length) {
2543
+ state.forceRebuild = true;
2544
+ }
2545
+ renderAll();
2546
+ }
2547
+
2548
+ function updateStatusBadge(kind) {
2549
+ const badge = el('statusBadge');
2550
+ if (kind === 'connected') {
2551
+ state.connected = true;
2552
+ badge.textContent = '已连接';
2553
+ badge.className = 'badge badge-ok';
2554
+ return;
2555
+ }
2556
+ if (kind === 'closed') {
2557
+ state.connected = false;
2558
+ badge.textContent = '离线';
2559
+ badge.className = 'badge badge-danger';
2560
+ return;
2561
+ }
2562
+ if (state.connected) {
2563
+ badge.textContent = '已连接';
2564
+ badge.className = 'badge badge-ok';
2565
+ return;
2566
+ }
2567
+ if (!state.document) {
2568
+ badge.textContent = '连接中';
2569
+ badge.className = 'badge badge-warn';
2570
+ return;
2571
+ }
2572
+ badge.textContent = state.document.report.valid ? '校验通过' : '校验失败';
2573
+ badge.className = state.document.report.valid ? 'badge badge-ok' : 'badge badge-danger';
2574
+ }
2575
+
2576
+ async function openHistory() {
2577
+ const payload = await api('/api/invoke', {
2578
+ method: 'POST',
2579
+ body: JSON.stringify({ tool: 'courseware.history', args: { limit: 20 } }),
2580
+ });
2581
+ const list = el('historyList');
2582
+ list.replaceChildren();
2583
+ el('historyDiff').textContent = '选择一条历史查看 Diff。';
2584
+ const history = payload.result?.history ?? [];
2585
+ if (history.length === 0) {
2586
+ const empty = document.createElement('li');
2587
+ empty.className = 'history-item muted';
2588
+ empty.textContent = '还没有编辑记录。';
2589
+ list.append(empty);
2590
+ }
2591
+ for (const entry of history) {
2592
+ const item = document.createElement('li');
2593
+ item.className = 'history-item';
2594
+ const title = document.createElement('button');
2595
+ title.type = 'button';
2596
+ title.className = 'history-link';
2597
+ const strong = document.createElement('strong');
2598
+ strong.textContent = `rev ${entry.revision}`;
2599
+ const summary = document.createElement('span');
2600
+ summary.textContent = ` ${entry.summary || '(无摘要)'}`;
2601
+ title.append(strong, summary);
2602
+ const meta = document.createElement('div');
2603
+ meta.className = 'muted';
2604
+ meta.textContent = `${entry.timestamp ?? ''} · ${entry.actor ?? ''} · ${entry.changedFiles?.length ?? 0} 个文件`;
2605
+ title.addEventListener('click', async () => {
2606
+ try {
2607
+ const diff = await api('/api/invoke', {
2608
+ method: 'POST',
2609
+ body: JSON.stringify({
2610
+ tool: 'courseware.diff',
2611
+ args: {
2612
+ fromRevision: Math.max(0, entry.revision - 1),
2613
+ toRevision: entry.revision,
2614
+ },
2615
+ }),
2616
+ });
2617
+ renderDiff(diff.result, el('historyDiff'));
2618
+ } catch (error) {
2619
+ el('historyDiff').textContent = `${error.code ?? '失败'}:${error.message}`;
2620
+ }
2621
+ });
2622
+ item.append(title, meta);
2623
+ if (entry.revision < state.document.revision) {
2624
+ const undo = document.createElement('button');
2625
+ undo.type = 'button';
2626
+ undo.className = 'ghost-button';
2627
+ undo.textContent = `撤销到 rev ${entry.revision}`;
2628
+ undo.addEventListener('click', () => undoTo(entry.revision));
2629
+ item.append(undo);
2630
+ }
2631
+ list.append(item);
2632
+ }
2633
+ if (!el('historyDialog').open) el('historyDialog').showModal();
2634
+ }
2635
+
2636
+ async function undoTo(revision) {
2637
+ const baseRevision = state.document.revision;
2638
+ try {
2639
+ const response = await api('/api/invoke', {
2640
+ method: 'POST',
2641
+ body: JSON.stringify({
2642
+ tool: 'courseware.undo',
2643
+ args: { revision, baseRevision },
2644
+ }),
2645
+ });
2646
+ const result = response.result ?? {};
2647
+ if (result.pending) {
2648
+ openConfirmation(result, async () => {
2649
+ const retry = await api('/api/invoke', {
2650
+ method: 'POST',
2651
+ body: JSON.stringify({
2652
+ tool: 'courseware.undo',
2653
+ args: { revision, baseRevision, confirm: true, awaitAck: true },
2654
+ }),
2655
+ });
2656
+ return retry.result ?? {};
2657
+ });
2658
+ return;
2659
+ }
2660
+ await loadDocument({ rebuild: true });
2661
+ el('historyDialog').close();
2662
+ el('eventLine').textContent = `已撤销到 rev ${revision}`;
2663
+ } catch (error) {
2664
+ el('eventLine').textContent = `${error.code ?? '失败'}:${error.message}`;
2665
+ }
2666
+ }
2667
+
2668
+ boot().catch((error) => {
2669
+ el('statusBadge').textContent = error.message;
2670
+ el('statusBadge').className = 'badge badge-danger';
2671
+ });