app.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. const $ = (selector) => document.querySelector(selector);
  2. const $$ = (selector) => Array.from(document.querySelectorAll(selector));
  3. const state = { source: 'sample', mode: 'demo', health: null, sample: null, run: null, busy: false, pollTimer: null, pollGeneration: 0, fileGeneration: 0, code: '', toastTimer: null };
  4. const stageNames = { ingest: '读取设计', import: '导入设计', fetch: '获取设计', parse: '解析设计', normalize: '规范化设计', design: '理解设计', analyze: '分析设计', analysis: '分析设计', plan: '制定实现计划', planning: '制定实现计划', generate: '生成代码', codegen: '生成代码', coding: '生成代码', review: '审查代码', verify: '检查结果', repair: '修复问题', export: '整理项目', complete: '生成完成', validate: '校验输入' };
  5. const fieldNames = { summary: '概述', description: '说明', warnings: '注意事项', limitations: '能力边界', issues: '发现的问题', checks: '检查项', status: '状态', passed: '通过', name: '名称', title: '标题', type: '类型', node_id: '节点 ID', node_count: '设计节点数', total_nodes: '设计节点数', text_count: '文本数', total_texts: '文本总数', covered_nodes: '已覆盖节点', covered_texts: '已覆盖文本', text_coverage: '文本覆盖度', structure_coverage: '结构覆盖度', coverage: '结构覆盖度', coverage_ratio: '结构覆盖度', duration_ms: '耗时(毫秒)', iterations: '修复轮数', repair_count: '修复次数', mode: '生成模式', score: '结构检查得分', components: '组件', layout: '布局', style: '样式', styles: '样式', colors: '颜色', typography: '字体', responsive: '响应式', files: '文件', file_count: '文件数', path: '文件路径', size: '大小', missing_nodes: '未覆盖节点', missing_texts: '缺失文本', unsupported_nodes: '暂不支持的节点', framework: '实现方案', steps: '实现步骤', tasks: '任务', evidence: '检查依据', result: '结果', message: '详情', priority: '优先级', reason: '原因', action: '建议', recommendations: '建议', brief: '补充要求', width: '宽度', height: '高度', target: '目标', notes: '备注', assets: '素材', node_ids: '节点 ID', component_name: '组件名', design_name: '设计名称', generated_nodes: '生成节点数', total_duration_ms: '总耗时(毫秒)' };
  6. Object.assign(fieldNames, { llm_calls: '模型调用次数', llm_latency_ms: '模型总耗时(毫秒)', input_chars: '输入字符数', output_chars: '输出字符数', input_chars_note: '输入统计说明', context_omitted_nodes: '上下文省略节点数', truncated_context_calls: '上下文截断次数', token_usage: 'Token 用量', estimated_cost_usd: '模型费用(美元)', cost_note: '费用统计说明', files_count: '生成文件数', node_coverage_percent: '节点结构覆盖率', coverage_note: '覆盖率说明', calls: '模型调用记录', runner: '运行方式', rendered_node_count: '匹配节点数', scope: '检查范围', repair_applied: '已执行修复', model_review: '模型审查', model_review_note: '模型审查说明', observations: '设计观察', detail: '详情', severity: '严重程度', source: '来源', role: '角色', input: '输入', output: '输出', tag: 'HTML 标签', component: '组件名', rationale: '选择依据', responsive_strategy: '响应式策略', context_truncated: '上下文已截断', omitted_nodes: '省略节点数' });
  7. function el(tag, className, value) {
  8. const node = document.createElement(tag);
  9. if (className) node.className = className;
  10. if (value !== undefined) node.textContent = String(value);
  11. return node;
  12. }
  13. function notify(message) {
  14. clearTimeout(state.toastTimer);
  15. $('#toast').textContent = message;
  16. $('#toast').hidden = false;
  17. state.toastTimer = setTimeout(() => { $('#toast').hidden = true; }, 3200);
  18. }
  19. async function request(url, options = {}, raw = false) {
  20. const response = await fetch(url, { ...options, headers: { ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...options.headers } });
  21. if (!response.ok) {
  22. let message = `请求失败(${response.status})`;
  23. try { const body = await response.json(); message = body.error || body.detail || body.message || message; } catch { /* Keep the HTTP error when the response is not JSON. */ }
  24. throw new Error(typeof message === 'string' ? message : JSON.stringify(message));
  25. }
  26. return raw ? response.text() : response.json();
  27. }
  28. function setFormError(message) {
  29. $('#form-error').textContent = message || '';
  30. $('#form-error').hidden = !message;
  31. }
  32. function updateControls() {
  33. const liveAvailable = Boolean(state.health?.live_available);
  34. const figmaAvailable = Boolean(state.health?.figma_available);
  35. const serverReady = Boolean(state.health);
  36. $$('[data-mode]').forEach((button) => {
  37. const selected = button.dataset.mode === state.mode;
  38. button.classList.toggle('selected', selected);
  39. button.setAttribute('aria-pressed', String(selected));
  40. button.disabled = state.busy || (button.dataset.mode === 'live' && !liveAvailable);
  41. if (button.dataset.mode === 'live') button.title = liveAvailable ? '使用服务端配置的模型运行 Agent' : '服务端未配置模型凭据,暂不可用';
  42. });
  43. $('#mode-hint').textContent = state.mode === 'live' ? '模型分析设计并规划语义结构,生成后再审查。布局与样式由设计数据决定。' : liveAvailable ? '离线模式按设计数据生成;也可切换到在线 Agent。' : '离线模式可直接运行。在线 Agent 需在服务端配置模型凭据。';
  44. $('#figma-hint').textContent = figmaAvailable ? '已配置 Figma 凭据。请选择单个 Frame 的链接。' : '服务端未配置 Figma 凭据。请先配置 FIGMA_ACCESS_TOKEN,或使用样例 / JSON。';
  45. $('#run-button').disabled = state.busy || !serverReady || (state.source === 'figma' && !figmaAvailable);
  46. $('#run-button').classList.toggle('busy', state.busy);
  47. $('#run-label').textContent = state.busy ? '正在生成…' : state.run?.status === 'failed' ? '重新生成' : '生成代码';
  48. $('#run-caption').textContent = state.busy ? '可以切换结果视图查看进度,请等待当前任务完成。' : state.source === 'figma' && !figmaAvailable ? 'Figma 连接就绪后即可生成。' : '完整过程与检查结果会保留在本次任务中。';
  49. }
  50. function selectSource(source) {
  51. state.source = source;
  52. $$('[data-source]').forEach((button) => {
  53. const selected = button.dataset.source === source;
  54. button.setAttribute('aria-selected', String(selected));
  55. button.tabIndex = selected ? 0 : -1;
  56. $(`#source-${button.dataset.source}`).hidden = !selected;
  57. });
  58. setFormError('');
  59. updateControls();
  60. }
  61. function selectView(view) {
  62. $$('[data-view]').forEach((button) => {
  63. const selected = button.dataset.view === view;
  64. button.setAttribute('aria-selected', String(selected));
  65. button.tabIndex = selected ? 0 : -1;
  66. $(`#view-${button.dataset.view}`).hidden = !selected;
  67. });
  68. }
  69. function addTabKeyboard(selector, attribute, callback) {
  70. const tabs = $$(selector);
  71. tabs.forEach((button, index) => button.addEventListener('keydown', (event) => {
  72. if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
  73. event.preventDefault();
  74. const next = event.key === 'Home' ? 0 : event.key === 'End' ? tabs.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
  75. callback(tabs[next].dataset[attribute]);
  76. tabs[next].focus();
  77. }));
  78. }
  79. function inspectSample(sample) {
  80. let root = sample?.document || sample?.design || sample?.root || sample;
  81. if (sample?.nodes && typeof sample.nodes === 'object') root = Object.values(sample.nodes)[0]?.document || root;
  82. let frame = null;
  83. const visit = (node) => {
  84. if (!node || typeof node !== 'object') return;
  85. if (!frame && node.type === 'FRAME') frame = node;
  86. (Array.isArray(node.children) ? node.children : []).forEach(visit);
  87. };
  88. visit(root);
  89. const design = frame || root;
  90. const countNodes = (node) => !node || typeof node !== 'object' ? 0 : 1 + (Array.isArray(node.children) ? node.children : []).reduce((sum, child) => sum + countNodes(child), 0);
  91. const count = countNodes(design);
  92. $('#sample-name').textContent = design?.name || sample?.name || '内置设计样例';
  93. const bounds = design?.absoluteBoundingBox || design?.bounds || design?.size;
  94. const dimensions = bounds?.width && bounds?.height ? `${Math.round(bounds.width)} × ${Math.round(bounds.height)}` : '';
  95. $('#sample-detail').textContent = [dimensions, count > 0 ? `${count} 个设计节点` : 'Figma 设计数据'].filter(Boolean).join(' · ');
  96. }
  97. async function loadFile(file) {
  98. if (!file) return;
  99. if (file.size > 2 * 1024 * 1024) { setFormError('JSON 文件超过 2 MB,请只导出需要生成的 Frame。'); return; }
  100. try {
  101. const content = await file.text();
  102. const parsed = JSON.parse(content);
  103. if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') throw new Error('文件顶层需要是 JSON 对象。');
  104. $('#json-input').value = content;
  105. $('#file-label').textContent = file.name;
  106. setFormError('');
  107. } catch (error) { setFormError(`无法读取 JSON:${error.message}`); }
  108. }
  109. function collectInput() {
  110. const input = { source: state.source, mode: state.mode };
  111. const brief = $('#brief').value.trim();
  112. if (brief) input.brief = brief;
  113. if (state.source === 'json') {
  114. const raw = $('#json-input').value.trim();
  115. if (!raw) throw new Error('请上传或粘贴 Figma JSON。');
  116. try { input.payload = JSON.parse(raw); } catch { throw new Error('JSON 格式有误,请检查引号、逗号和括号。'); }
  117. if (!input.payload || Array.isArray(input.payload) || typeof input.payload !== 'object') throw new Error('JSON 顶层需要是一个对象。');
  118. }
  119. if (state.source === 'figma') {
  120. const value = $('#figma-url').value.trim();
  121. let url;
  122. try { url = new URL(value); } catch { throw new Error('请输入完整的 Figma 设计链接。'); }
  123. if (url.protocol !== 'https:' || !['www.figma.com', 'figma.com'].includes(url.hostname)) throw new Error('请使用 https://www.figma.com/ 开头的设计链接。');
  124. if (!/^\/(design|file)\/[^/]+/.test(url.pathname)) throw new Error('请选择 Figma design 或 file 设计链接。');
  125. input.figma_url = value;
  126. if ($('#node-id').value.trim()) input.node_id = $('#node-id').value.trim();
  127. }
  128. if (new TextEncoder().encode(JSON.stringify(input)).byteLength > 2 * 1024 * 1024) throw new Error('完整请求超过 2 MB,请缩小设计 JSON 或减少补充要求。');
  129. return input;
  130. }
  131. function setRunStatus(status) {
  132. const names = { queued: '等待执行', running: '正在执行', completed: '生成完成', failed: '执行失败' };
  133. $('#run-status').className = `run-status ${['queued', 'running', 'completed', 'failed'].includes(status) ? status : ''}`;
  134. $('#run-status-label').textContent = names[status] || '尚未运行';
  135. }
  136. function resetResult() {
  137. state.code = '';
  138. state.fileGeneration += 1;
  139. $('#preview-frame').removeAttribute('src');
  140. $('#preview-shell').hidden = true;
  141. $('#preview-canvas').classList.remove('has-preview');
  142. $('#preview-empty').hidden = false;
  143. $('#empty-title').textContent = '正在把设计变成代码';
  144. $('#empty-description').textContent = '当前阶段与执行结果会实时记录在下方。生成完成后,页面预览将显示在这里。';
  145. $('#preview-name').textContent = '正在生成';
  146. $('#preview-note').textContent = '预览将在隔离环境中展示';
  147. $('#file-select').replaceChildren(el('option', '', '正在生成项目文件…'));
  148. $('#file-select').disabled = true;
  149. $('#copy-button').disabled = true;
  150. $('#copy-label').textContent = '复制代码';
  151. $('#code-content').hidden = true;
  152. $('#code-placeholder').hidden = false;
  153. $('#file-code').textContent = '';
  154. $('#report-content').replaceChildren();
  155. $('#report-content').hidden = true;
  156. $('#report-placeholder').hidden = false;
  157. const download = $('#download-button');
  158. download.removeAttribute('href');
  159. download.classList.add('disabled');
  160. download.setAttribute('aria-disabled', 'true');
  161. download.tabIndex = -1;
  162. $('#event-list').replaceChildren();
  163. delete $('#event-list').dataset.fingerprint;
  164. $('#activity-empty').hidden = false;
  165. $('#activity-empty').textContent = '正在创建任务…';
  166. $('#event-count').textContent = '0 条记录';
  167. }
  168. function renderEvents(events = []) {
  169. const container = $('#event-list');
  170. const body = $('#activity-body');
  171. const nearBottom = body.scrollHeight - body.scrollTop - body.clientHeight < 65;
  172. const items = Array.isArray(events) ? events : [];
  173. const fingerprint = JSON.stringify(items);
  174. if (container.dataset.fingerprint === fingerprint) return;
  175. container.dataset.fingerprint = fingerprint;
  176. container.replaceChildren();
  177. $('#activity-empty').hidden = items.length > 0;
  178. $('#activity-empty').textContent = '任务已创建,正在等待执行记录…';
  179. items.forEach((event) => {
  180. const status = String(event.status || '');
  181. const known = ['completed', 'success', 'passed', 'running', 'started', 'failed', 'error'].includes(status) ? status : 'pending';
  182. const item = el('li', `event-item ${known}`);
  183. item.append(el('span', 'event-marker', ['completed', 'success', 'passed'].includes(status) ? '✓' : ['failed', 'error'].includes(status) ? '!' : '•'));
  184. const description = el('div', 'event-description');
  185. description.append(el('strong', '', stageNames[event.stage] || event.stage || '执行阶段'));
  186. if (event.message) description.append(el('p', '', event.message));
  187. item.append(description);
  188. if (Number.isFinite(event.duration_ms)) item.append(el('span', 'event-duration', event.duration_ms >= 1000 ? `${(event.duration_ms / 1000).toFixed(1)} s` : `${Math.round(event.duration_ms)} ms`));
  189. container.append(item);
  190. });
  191. $('#event-count').textContent = `${items.length} 条记录`;
  192. if (nearBottom) body.scrollTop = body.scrollHeight;
  193. }
  194. function readable(value, key = '') {
  195. if (value === null || value === undefined) return '未提供';
  196. if (typeof value === 'boolean') return value ? '是' : '否';
  197. if (typeof value === 'number' && key === 'node_coverage_percent') return `${value}%`;
  198. if (typeof value === 'number' && /coverage/.test(key) && value >= 0 && value <= 1) return `${Math.round(value * 100)}%`;
  199. if (key === 'mode') return value === 'demo' ? '离线演示' : value === 'live' ? '在线 Agent' : String(value);
  200. if (key === 'status') return ({ passed: '通过', passed_with_advisories: '通过,有待人工复核建议', failed: '未通过', completed: '已完成', running: '执行中' })[value] || String(value);
  201. if (key === 'name') return ({ required_files: '必备文件', node_coverage: '节点结构覆盖', manifest_json: '节点映射文件', basic_accessibility: '基础可访问性' })[value] || String(value);
  202. if (key === 'runner') return ({ deterministic_demo: '离线规则生成', 'hello_agents.SimpleAgent': 'HelloAgents SimpleAgent', injected_test_runner: '测试替身(非真实模型)' })[value] || String(value);
  203. return String(value);
  204. }
  205. function renderValue(value, depth = 0) {
  206. const wrapper = el('div', 'report-data');
  207. if (depth > 5) { wrapper.append(el('p', '', typeof value === 'object' ? JSON.stringify(value) : readable(value))); return wrapper; }
  208. if (Array.isArray(value)) {
  209. if (!value.length) { wrapper.textContent = '无'; return wrapper; }
  210. const list = el('ul', value.some((item) => item && typeof item === 'object') ? 'report-list' : '');
  211. value.forEach((item) => { const li = el('li'); li.append(renderValue(item, depth + 1)); list.append(li); });
  212. wrapper.append(list);
  213. } else if (value && typeof value === 'object') {
  214. const list = el('dl');
  215. Object.entries(value).forEach(([key, content]) => {
  216. list.append(el('dt', '', fieldNames[key] || key));
  217. const detail = el('dd');
  218. if (content && typeof content === 'object') detail.append(renderValue(content, depth + 1));
  219. else detail.textContent = readable(content, key);
  220. list.append(detail);
  221. });
  222. wrapper.append(list);
  223. } else { wrapper.append(el('p', '', readable(value))); }
  224. return wrapper;
  225. }
  226. function renderReport(result) {
  227. const report = $('#report-content');
  228. report.replaceChildren();
  229. report.className = 'report-content';
  230. const reviewFailed = result.review?.passed === false || result.review?.status === 'failed';
  231. const summary = el('div', reviewFailed ? 'report-summary needs-review' : 'report-summary');
  232. summary.append(el('h2', '', reviewFailed ? '代码已生成,存在待修复问题' : '生成结果已就绪'), el('p', '', '以下审查基于设计结构与输出代码。结构检查通过不代表像素级还原,请结合页面预览核对字体、间距和素材。'));
  233. report.append(summary);
  234. const appendSection = (title, value) => {
  235. if (value === undefined || value === null) return;
  236. const section = el('section', 'report-section');
  237. section.append(el('h3', '', title), renderValue(value));
  238. report.append(section);
  239. };
  240. if (result.metrics && typeof result.metrics === 'object') {
  241. const section = el('section', 'report-section');
  242. section.append(el('h3', '', '运行与结构指标'));
  243. const grid = el('div', 'metric-grid');
  244. const headlineMetrics = ['node_coverage_percent', 'node_count', 'files_count', 'llm_calls', 'duration_ms', 'input_chars', 'output_chars'];
  245. Object.entries(result.metrics).filter(([key, value]) => headlineMetrics.includes(key) && typeof value === 'number').forEach(([key, value]) => {
  246. const item = el('div', 'metric-item');
  247. item.append(el('strong', '', readable(value, key)), el('span', '', fieldNames[key] || key));
  248. grid.append(item);
  249. });
  250. section.append(grid, el('p', 'report-note', '仅展示本次任务实际返回的指标;覆盖度衡量结构或文本,不衡量视觉相似度。'));
  251. const extraMetrics = Object.fromEntries(Object.entries(result.metrics).filter(([key]) => !headlineMetrics.includes(key)));
  252. if (Object.keys(extraMetrics).length) {
  253. const details = el('details', 'metrics-details');
  254. details.append(el('summary', '', '查看调用明细与费用说明'), renderValue(extraMetrics));
  255. section.append(details);
  256. }
  257. report.append(section);
  258. }
  259. const warnings = result.warnings || result.design?.warnings;
  260. if (warnings && (!Array.isArray(warnings) || warnings.length)) {
  261. const warning = el('section', 'warning-block');
  262. warning.append(el('h3', '', '设计导入注意事项'), renderValue(warnings));
  263. report.append(warning);
  264. }
  265. appendSection('代码审查', result.review);
  266. appendSection('设计分析', result.analysis);
  267. appendSection('实现计划', result.plan);
  268. if (!result.analysis && !result.plan && !result.review && !result.metrics) report.append(el('p', 'report-note', '本次任务没有返回详细审查数据,请直接查看源代码与预览。'));
  269. report.hidden = false;
  270. $('#report-placeholder').hidden = true;
  271. }
  272. async function loadCode(path) {
  273. if (!state.run || !path) return;
  274. const generation = ++state.fileGeneration;
  275. const runId = state.run.id;
  276. $('#copy-button').disabled = true;
  277. $('#copy-label').textContent = '复制代码';
  278. $('#file-code').textContent = '正在读取文件…';
  279. $('#code-placeholder').hidden = true;
  280. $('#code-content').hidden = false;
  281. state.code = '';
  282. try {
  283. const content = await request(`/api/runs/${encodeURIComponent(runId)}/files?path=${encodeURIComponent(path)}`, {}, true);
  284. if (generation !== state.fileGeneration || state.run?.id !== runId) return;
  285. state.code = content;
  286. $('#file-code').textContent = content;
  287. $('#copy-button').disabled = false;
  288. } catch (error) {
  289. if (generation !== state.fileGeneration) return;
  290. $('#file-code').textContent = `文件读取失败:${error.message}`;
  291. }
  292. }
  293. function renderCompleted(run) {
  294. const result = run.result || {};
  295. const base = `/api/runs/${encodeURIComponent(run.id)}`;
  296. $('#preview-empty').hidden = true;
  297. $('#preview-shell').hidden = false;
  298. $('#preview-canvas').classList.add('has-preview');
  299. $('#preview-frame').src = `${base}/preview`;
  300. $('#preview-name').textContent = result.design?.name || result.design?.root?.name || '生成页面';
  301. $('#preview-note').textContent = `${result.mode === 'live' ? '在线 Agent' : '离线演示'}生成 · 脚本已在预览中禁用`;
  302. const download = $('#download-button');
  303. download.href = `${base}/download`;
  304. download.setAttribute('download', `framecraft-${run.id}.zip`);
  305. download.classList.remove('disabled');
  306. download.setAttribute('aria-disabled', 'false');
  307. download.tabIndex = 0;
  308. const files = Array.isArray(result.files) ? result.files : [];
  309. const select = $('#file-select');
  310. select.replaceChildren();
  311. files.forEach((file) => {
  312. const path = typeof file === 'string' ? file : file.path;
  313. if (!path) return;
  314. const option = el('option', '', path);
  315. option.value = path;
  316. select.append(option);
  317. });
  318. select.disabled = select.options.length === 0;
  319. if (Array.from(select.options).some((option) => option.value === 'src/App.tsx')) select.value = 'src/App.tsx';
  320. if (select.options.length) void loadCode(select.value);
  321. else select.append(el('option', '', '本次任务没有返回项目文件'));
  322. renderReport(result);
  323. }
  324. function renderFailure(message) {
  325. $('#empty-title').textContent = '这次生成没有完成';
  326. $('#empty-description').textContent = message || '请查看执行记录,检查输入后重新生成。';
  327. $('#preview-name').textContent = '执行失败';
  328. $('#file-select').replaceChildren(el('option', '', '任务失败,暂无项目文件'));
  329. setFormError(message || '生成失败,请检查输入后重试。');
  330. }
  331. async function pollRun(id, generation) {
  332. if (generation !== state.pollGeneration) return;
  333. try {
  334. const run = await request(`/api/runs/${encodeURIComponent(id)}`);
  335. if (generation !== state.pollGeneration) return;
  336. state.run = run;
  337. renderEvents(run.events);
  338. setRunStatus(run.status);
  339. if (run.status === 'completed' || run.status === 'failed') {
  340. state.busy = false;
  341. state.pollTimer = null;
  342. if (run.status === 'completed') renderCompleted(run);
  343. else renderFailure(run.error || '生成失败,请查看执行记录后重试。');
  344. updateControls();
  345. return;
  346. }
  347. state.pollTimer = setTimeout(() => void pollRun(id, generation), 800);
  348. } catch (error) {
  349. if (generation !== state.pollGeneration) return;
  350. state.busy = false;
  351. state.run = { ...state.run, status: 'failed' };
  352. setRunStatus('failed');
  353. renderFailure(`无法获取任务状态:${error.message}。任务可能仍在服务端运行,可恢复连接后重新生成。`);
  354. updateControls();
  355. }
  356. }
  357. async function startRun(event) {
  358. event.preventDefault();
  359. if (state.busy) return;
  360. let body;
  361. try { body = collectInput(); } catch (error) { setFormError(error.message); return; }
  362. clearTimeout(state.pollTimer);
  363. const generation = ++state.pollGeneration;
  364. state.busy = true;
  365. state.run = null;
  366. setFormError('');
  367. resetResult();
  368. setRunStatus('queued');
  369. updateControls();
  370. try {
  371. const run = await request('/api/runs', { method: 'POST', body: JSON.stringify(body) });
  372. if (generation !== state.pollGeneration) return;
  373. if (!run.id) throw new Error('服务未返回有效的任务 ID');
  374. state.run = run;
  375. $('#run-id-label').textContent = `任务 ${run.id}`;
  376. void pollRun(run.id, generation);
  377. } catch (error) {
  378. if (generation !== state.pollGeneration) return;
  379. state.busy = false;
  380. state.run = { status: 'failed' };
  381. setRunStatus('failed');
  382. renderFailure(error.message);
  383. $('#activity-empty').textContent = '任务未能创建,请检查上方错误信息。';
  384. updateControls();
  385. }
  386. }
  387. async function copyCode() {
  388. if (!state.code) return;
  389. try {
  390. await navigator.clipboard.writeText(state.code);
  391. $('#copy-label').textContent = '已复制';
  392. notify('代码已复制到剪贴板');
  393. setTimeout(() => { $('#copy-label').textContent = '复制代码'; }, 2400);
  394. } catch { notify('浏览器未允许复制,请在代码区手动选择并复制。'); }
  395. }
  396. async function initialize() {
  397. const results = await Promise.allSettled([request('/api/health'), request('/api/sample')]);
  398. if (results[0].status === 'fulfilled') {
  399. state.health = results[0].value;
  400. $('#connection-status').className = 'connection ready';
  401. $('#connection-label').textContent = '本地服务已连接';
  402. } else {
  403. $('#connection-status').className = 'connection failed';
  404. $('#connection-label').textContent = '服务未连接';
  405. setFormError('无法连接本地服务。请确认服务已启动,然后刷新页面。');
  406. }
  407. if (results[1].status === 'fulfilled') { state.sample = results[1].value; inspectSample(state.sample); }
  408. else { $('#sample-detail').textContent = '暂时无法读取样例,可尝试重新生成'; }
  409. updateControls();
  410. }
  411. $$('[data-source]').forEach((button) => button.addEventListener('click', () => selectSource(button.dataset.source)));
  412. $$('[data-view]').forEach((button) => button.addEventListener('click', () => selectView(button.dataset.view)));
  413. $$('[data-mode]').forEach((button) => button.addEventListener('click', () => { state.mode = button.dataset.mode; updateControls(); }));
  414. addTabKeyboard('[data-source]', 'source', selectSource);
  415. addTabKeyboard('[data-view]', 'view', selectView);
  416. $$('[data-viewport]').forEach((button) => button.addEventListener('click', () => {
  417. const mobile = button.dataset.viewport === 'mobile';
  418. $$('[data-viewport]').forEach((option) => { const selected = option === button; option.classList.toggle('selected', selected); option.setAttribute('aria-pressed', String(selected)); });
  419. $('#preview-shell').classList.toggle('mobile', mobile);
  420. $('#viewport-label').textContent = mobile ? '手机画布 · 390px' : '自适应画布';
  421. }));
  422. $('#run-form').addEventListener('submit', startRun);
  423. $('#json-file').addEventListener('change', (event) => void loadFile(event.target.files?.[0]));
  424. $('#file-drop').addEventListener('dragover', (event) => { event.preventDefault(); $('#file-drop').classList.add('drag-over'); });
  425. $('#file-drop').addEventListener('dragleave', () => $('#file-drop').classList.remove('drag-over'));
  426. $('#file-drop').addEventListener('drop', (event) => { event.preventDefault(); $('#file-drop').classList.remove('drag-over'); void loadFile(event.dataTransfer.files?.[0]); });
  427. $('#file-select').addEventListener('change', (event) => void loadCode(event.target.value));
  428. $('#copy-button').addEventListener('click', () => void copyCode());
  429. $('#download-button').addEventListener('click', (event) => { if ($('#download-button').getAttribute('aria-disabled') === 'true') event.preventDefault(); });
  430. window.addEventListener('beforeunload', () => { clearTimeout(state.pollTimer); state.pollGeneration += 1; });
  431. void initialize();