store-and-ui.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // store-and-ui.js — Unified State Store, Production/Engineering Mode Switcher,
  2. // Confirmation Modal, Password Change Modal & Single-DIMM Temperature Curve Modal
  3. (() => {
  4. const $ = id => document.getElementById(id);
  5. const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  6. const listeners = new Set();
  7. const state = {
  8. uiMode: localStorage.getItem('stl_ui_mode') === 'production' ? 'production' : 'engineering',
  9. page: 'overview',
  10. stationId: 'S1',
  11. connected: false,
  12. sysInfo: null,
  13. stations: [],
  14. controlByStation: {},
  15. diagnosticsByStation: {},
  16. alarmsByStation: {},
  17. traceConfig: null,
  18. hwInfo: null,
  19. };
  20. function emit(path, prev, next, trigger = 'ui') {
  21. for (const fn of listeners) {
  22. try { fn({ path, prev, next, trigger, ts_ms: Date.now() }); } catch (e) { console.error('[stlStore]', e); }
  23. }
  24. }
  25. window.stlStore = {
  26. state,
  27. get(key) { return state[key]; },
  28. set(key, value, trigger = 'ui') {
  29. const prev = state[key];
  30. state[key] = value;
  31. emit(key, prev, value, trigger);
  32. },
  33. setStationMap(mapKey, sid, value, trigger = 'poll') {
  34. if (!state[mapKey] || typeof state[mapKey] !== 'object') state[mapKey] = {};
  35. const prev = state[mapKey][sid];
  36. state[mapKey][sid] = value;
  37. emit(`${mapKey}.${sid}`, prev, value, trigger);
  38. },
  39. subscribe(fn) {
  40. listeners.add(fn);
  41. return () => listeners.delete(fn);
  42. },
  43. };
  44. function formatElapsed(ms) {
  45. const n = Math.max(0, Math.floor(Number(ms || 0) / 1000));
  46. const h = Math.floor(n / 3600), m = Math.floor((n % 3600) / 60), s = n % 60;
  47. return [h, m, s].map(v => String(v).padStart(2, '0')).join(':');
  48. }
  49. function formatClock(ms) {
  50. if (!Number(ms)) return '--:--:--';
  51. const d = new Date(Number(ms));
  52. return [d.getHours(), d.getMinutes(), d.getSeconds()].map(v => String(v).padStart(2, '0')).join(':');
  53. }
  54. // ---- Universal Confirmation Modal ----
  55. let confirmResolve = null;
  56. function closeConfirm(result) {
  57. const modal = $('stl-confirm-modal');
  58. if (modal) modal.classList.add('hidden');
  59. if (confirmResolve) {
  60. const fn = confirmResolve;
  61. confirmResolve = null;
  62. fn(result);
  63. }
  64. }
  65. function confirmDialog(title, message, confirmLabel = '确认执行', isDanger = true) {
  66. const modal = $('stl-confirm-modal');
  67. if (!modal) return Promise.resolve(true);
  68. if (confirmResolve) closeConfirm(false);
  69. $('stl-confirm-title').textContent = title || '操作确认';
  70. $('stl-confirm-body').textContent = message || '';
  71. const okBtn = $('stl-confirm-ok');
  72. okBtn.textContent = confirmLabel || '确认执行';
  73. okBtn.className = isDanger ? 'btn btn-danger btn-sm' : 'btn btn-primary btn-sm';
  74. modal.classList.remove('hidden');
  75. okBtn.focus();
  76. return new Promise(resolve => { confirmResolve = resolve; });
  77. }
  78. // ---- Password Change Modal ----
  79. function openPasswordModal() {
  80. const modal = $('stl-password-modal');
  81. if (!modal) return;
  82. $('pw-current').value = '';
  83. $('pw-new').value = '';
  84. $('pw-confirm').value = '';
  85. $('pw-modal-msg').textContent = '';
  86. $('pw-modal-msg').className = 'field-note';
  87. modal.classList.remove('hidden');
  88. $('pw-current').focus();
  89. }
  90. function closePasswordModal() {
  91. $('stl-password-modal')?.classList.add('hidden');
  92. }
  93. // ---- Single-DIMM Temperature Curve Modal ----
  94. let curveState = { stationId: 'S1', slot: 0, label: 'CPU0 CH A' };
  95. let curveRefreshTimer = null;
  96. function drawDimmCurveCanvas(canvas, points) {
  97. if (!canvas) return;
  98. const dpr = window.devicePixelRatio || 1;
  99. const rect = canvas.getBoundingClientRect();
  100. const w = Math.max(320, Math.round(rect.width || 720));
  101. const h = Math.max(200, Math.round(rect.height || 260));
  102. canvas.width = w * dpr;
  103. canvas.height = h * dpr;
  104. const ctx = canvas.getContext('2d');
  105. ctx.scale(dpr, dpr);
  106. ctx.clearRect(0, 0, w, h);
  107. ctx.fillStyle = '#fbfdfe';
  108. ctx.fillRect(0, 0, w, h);
  109. const pad = { l: 48, r: 20, t: 18, b: 30 };
  110. const pw = w - pad.l - pad.r;
  111. const ph = h - pad.t - pad.b;
  112. if (!points.length) {
  113. ctx.fillStyle = '#64748b';
  114. ctx.font = '13px sans-serif';
  115. ctx.textAlign = 'center';
  116. ctx.fillText('当前尚未采集到该槽位温度数据(接入高温罩 MCU 0x82 或 BMC SDR 后自动记录)', w / 2, h / 2);
  117. return;
  118. }
  119. const temps = points.map(p => Number(p.temp_c)).filter(Number.isFinite);
  120. const minT = Math.max(0, Math.floor((Math.min(...temps) - 5) / 5) * 5);
  121. const maxT = Math.min(130, Math.ceil((Math.max(...temps, minT + 10) + 5) / 5) * 5);
  122. const spanT = Math.max(10, maxT - minT);
  123. // Grid lines
  124. ctx.strokeStyle = '#e2e8f0';
  125. ctx.lineWidth = 1;
  126. ctx.fillStyle = '#64748b';
  127. ctx.font = '11px monospace';
  128. ctx.textAlign = 'right';
  129. const yTicks = 5;
  130. for (let i = 0; i <= yTicks; i++) {
  131. const y = pad.t + (ph * i) / yTicks;
  132. const val = maxT - (spanT * i) / yTicks;
  133. ctx.beginPath();
  134. ctx.moveTo(pad.l, y);
  135. ctx.lineTo(pad.l + pw, y);
  136. ctx.stroke();
  137. ctx.fillText(`${val.toFixed(0)}°C`, pad.l - 6, y + 4);
  138. }
  139. // Time labels
  140. const t0 = Number(points[0].ts_ms || 0);
  141. const t1 = Number(points[points.length - 1].ts_ms || t0);
  142. const spanMs = Math.max(1000, t1 - t0);
  143. ctx.textAlign = 'center';
  144. for (let i = 0; i <= 4; i++) {
  145. const x = pad.l + (pw * i) / 4;
  146. const ts = t0 + (spanMs * i) / 4;
  147. ctx.fillText(formatClock(ts), x, h - 8);
  148. }
  149. // Line
  150. ctx.strokeStyle = '#0d8b80';
  151. ctx.lineWidth = 2;
  152. ctx.beginPath();
  153. points.forEach((p, idx) => {
  154. const x = pad.l + (points.length === 1 ? pw / 2 : ((Number(p.ts_ms) - t0) / spanMs) * pw);
  155. const y = pad.t + ((maxT - Number(p.temp_c)) / spanT) * ph;
  156. if (idx === 0) ctx.moveTo(x, y);
  157. else ctx.lineTo(x, y);
  158. });
  159. ctx.stroke();
  160. // Last point highlight
  161. const last = points[points.length - 1];
  162. const lx = pad.l + (points.length === 1 ? pw / 2 : ((Number(last.ts_ms) - t0) / spanMs) * pw);
  163. const ly = pad.t + ((maxT - Number(last.temp_c)) / spanT) * ph;
  164. ctx.fillStyle = '#c5424b';
  165. ctx.beginPath();
  166. ctx.arc(lx, ly, 4, 0, Math.PI * 2);
  167. ctx.fill();
  168. }
  169. async function refreshDimmCurve() {
  170. const { stationId, slot, label } = curveState;
  171. $('dimm-curve-title').textContent = `${stationId} · 槽位 ${label} (BMC${slot}) 实时温度曲线`;
  172. $('dimm-curve-stats').textContent = '正在读取温度历史曲线...';
  173. try {
  174. const res = await fetch(`/api/stations/${encodeURIComponent(stationId)}/dimm-curve?slot=${slot}`, { credentials: 'same-origin', cache: 'no-store' });
  175. if (!res.ok) throw new Error(`HTTP ${res.status}`);
  176. const data = await res.json();
  177. const pts = Array.isArray(data.points) ? data.points : [];
  178. if (pts.length) {
  179. const vals = pts.map(p => Number(p.temp_c)).filter(Number.isFinite);
  180. const minV = Math.min(...vals), maxV = Math.max(...vals);
  181. const avgV = vals.reduce((a, b) => a + b, 0) / vals.length;
  182. const curV = vals[vals.length - 1];
  183. const srcTag = data.source === 'bmc_sdr_fallback' ? ' · 来源: BMC SDR' : ' · 来源: MCU 0x82';
  184. $('dimm-curve-stats').textContent = `采样点 ${pts.length} · 当前 ${curV.toFixed(1)}°C · 最低 ${minV.toFixed(1)}°C · 最高 ${maxV.toFixed(1)}°C · 均值 ${avgV.toFixed(1)}°C${srcTag}`;
  185. } else {
  186. $('dimm-curve-stats').textContent = '暂无该槽位历史温度采样点(连接高温罩或启用 BMC 温度轮询后自动记录)';
  187. }
  188. drawDimmCurveCanvas($('dimm-curve-canvas'), pts);
  189. } catch (err) {
  190. $('dimm-curve-stats').textContent = `读取温度曲线失败:${err.message}`;
  191. drawDimmCurveCanvas($('dimm-curve-canvas'), []);
  192. }
  193. }
  194. function openDimmCurveModal(stationId, slotIdx, slotLabel) {
  195. const modal = $('stl-dimm-curve-modal');
  196. if (!modal) return;
  197. const cpu = slotIdx < 12 ? 0 : 1;
  198. const ch = String.fromCharCode(65 + (slotIdx % 12));
  199. curveState = { stationId, slot: slotIdx, label: slotLabel || `CPU${cpu} CH ${ch}` };
  200. modal.classList.remove('hidden');
  201. void refreshDimmCurve();
  202. if (curveRefreshTimer) clearInterval(curveRefreshTimer);
  203. curveRefreshTimer = setInterval(() => {
  204. if (modal.classList.contains('hidden')) {
  205. clearInterval(curveRefreshTimer);
  206. curveRefreshTimer = null;
  207. return;
  208. }
  209. void refreshDimmCurve();
  210. }, 2000);
  211. }
  212. function closeDimmCurveModal() {
  213. if (curveRefreshTimer) {
  214. clearInterval(curveRefreshTimer);
  215. curveRefreshTimer = null;
  216. }
  217. $('stl-dimm-curve-modal')?.classList.add('hidden');
  218. }
  219. // ---- Production / Engineering View Mode Switcher (Option B) ----
  220. function applyUiMode(mode, persist = true) {
  221. const next = mode === 'production' ? 'production' : 'engineering';
  222. if (persist) localStorage.setItem('stl_ui_mode', next);
  223. document.body.dataset.uiMode = next;
  224. window.stlStore.set('uiMode', next, 'mode_switch');
  225. const prodBtn = $('btn-mode-production');
  226. const engBtn = $('btn-mode-engineering');
  227. if (prodBtn) prodBtn.classList.toggle('active', next === 'production');
  228. if (engBtn) engBtn.classList.toggle('active', next === 'engineering');
  229. const prodPanel = $('production-dashboard');
  230. if (prodPanel) prodPanel.hidden = next !== 'production';
  231. window.dispatchEvent(new CustomEvent('stl:ui-mode-change', { detail: { mode: next } }));
  232. }
  233. // ---- Production Dashboard Renderer (Unlimited Dynamic Stations) ----
  234. let prodCallbacks = {};
  235. const prodTargetDraft = new Map();
  236. const prodProfileDraft = new Map();
  237. function renderProductionDashboard(stations = []) {
  238. const grid = $('prod-stations-grid');
  239. if (!grid) return;
  240. const summaryEl = $('prod-summary-bar');
  241. const total = stations.length;
  242. const running = stations.filter(s => s.task_status === 'running').length;
  243. const failed = stations.filter(s => s.task_status === 'failed' || s.verdict === 'fail' || s.awaiting_dimm_replacement || s.fault_code).length;
  244. const passed = stations.filter(s => s.task_status === 'completed' && s.verdict === 'pass' && !s.fault_code).length;
  245. if (summaryEl) {
  246. summaryEl.innerHTML = `<span class="badge">总工位 ${total}</span>` +
  247. `<span class="badge connected">测试中 ${running}</span>` +
  248. `<span class="badge" style="background:#dcfce7;color:#166534;border-color:#86efac">PASS ${passed}</span>` +
  249. `<span class="badge ${failed ? 'error' : ''}">异常 / FAIL ${failed}</span>`;
  250. }
  251. const activeEl = document.activeElement;
  252. if (activeEl && grid.contains(activeEl) && (activeEl.matches('[data-prod-target]') || activeEl.matches('[data-prod-profile]'))) {
  253. return;
  254. }
  255. grid.innerHTML = stations.map(s => {
  256. const sid = s.station_id;
  257. const ctrl = window.stlFirmware?.snapshot?.(sid) || {};
  258. const profiles = Array.isArray(ctrl.saved_profiles) ? ctrl.saved_profiles : [];
  259. const thPolicy = ctrl.thermal_policy || {};
  260. const defaultTarget = prodTargetDraft.has(sid) ? prodTargetDraft.get(sid) : (s.thermal_target_c ?? thPolicy.target_temp_c ?? 70);
  261. const chamberTxt = typeof s.chamber_temp_c === 'number' && Number.isFinite(s.chamber_temp_c) ? `${s.chamber_temp_c.toFixed(1)}°C` : '--.-°C';
  262. const hoodOnline = !!s.thermal_online;
  263. const isRunning = s.task_status === 'running';
  264. const isFail = !!(s.awaiting_dimm_replacement || s.task_status === 'failed' || s.verdict === 'fail' || s.fault_code);
  265. const isPass = s.task_status === 'completed' && s.verdict === 'pass' && !isFail;
  266. const statusCls = isFail ? 'error' : isPass ? 'connected' : isRunning ? 'active' : '';
  267. const statusTxt = s.fault_code ? `异常: ${s.fault_code}`
  268. : s.awaiting_dimm_replacement ? 'FAIL · 待换条'
  269. : isFail ? 'FAIL'
  270. : isPass ? 'PASS'
  271. : isRunning ? `运行中 · ${s.phase || 'running'}`
  272. : (s.console_online || s.bmc_state === 'online') ? '就绪待测' : '离线';
  273. const dimms = Array.isArray(s.dimm_states) && s.dimm_states.length === 24
  274. ? s.dimm_states
  275. : Array.from({ length: 24 }, (_, idx) => ({ slot: idx, state: 'idle', present: false, temp_c: null }));
  276. const renderRow = (startIdx, title) => `<div class="prod-dimm-row"><span class="prod-cpu-lbl">${title}</span>${dimms.slice(startIdx, startIdx + 12).map(d => {
  277. const ch = String.fromCharCode(65 + (d.slot % 12));
  278. const st = (d.state || 'idle').toLowerCase();
  279. const tVal = typeof d.temp_c === 'number' && Number.isFinite(d.temp_c) ? `${Math.round(d.temp_c)}°` : '';
  280. return `<button type="button" class="prod-dimm-cell is-${esc(st)}" data-prod-curve="${esc(sid)}:${d.slot}" title="${esc(sid)} CPU${d.slot < 12 ? 0 : 1} CH ${ch} · ${esc(st.toUpperCase())}${tVal ? ' · ' + tVal + 'C' : ''}(点击查看单槽温度曲线)"><b>${ch}</b><span>${esc(tVal || (st === 'pass' ? 'OK' : st === 'fail' ? 'NG' : '-'))}</span></button>`;
  281. }).join('')}</div>`;
  282. const alarmCnt = Number(s.alarm_count || 0);
  283. const chosenProf = prodProfileDraft.get(sid) || '__current__';
  284. const profOptions = `<option value="__current__" ${chosenProf === '__current__' ? 'selected' : ''}>当前工位激活配置</option>` +
  285. profiles.map(p => {
  286. const val = p.profile_id || p.name;
  287. return `<option value="${esc(val)}" ${chosenProf === val ? 'selected' : ''}>${esc(p.name)} (×${p.repeat === 0 ? '无限' : (p.repeat || 1)})</option>`;
  288. }).join('');
  289. return `<article class="prod-station-card ${isFail ? 'is-fail' : isPass ? 'is-pass' : isRunning ? 'is-running' : ''}" data-prod-station="${esc(sid)}">
  290. <div class="prod-card-head">
  291. <div>
  292. <h3>${esc(sid)} · ${esc(s.name || sid)}</h3>
  293. <div class="prod-card-meta">
  294. <span class="badge ${s.console_online ? 'connected' : ''}">串口 ${s.console_online ? '在线' : '离线'}</span>
  295. <span class="badge ${s.bmc_state === 'online' ? 'connected' : ''}">BMC ${s.bmc_state === 'online' ? '在线' : '离线'}</span>
  296. <span class="badge ${hoodOnline ? 'connected' : 'error'}">高温罩 ${hoodOnline ? `在线 · ${esc(s.thermal_mode || 'idle')}` : '未连接'}</span>
  297. </div>
  298. </div>
  299. <div class="prod-card-right">
  300. <span class="badge ${statusCls}" style="font-size:12px">${esc(statusTxt)}</span>
  301. <div class="prod-metrics-inline">
  302. <span>腔温 <strong>${esc(chamberTxt)}</strong></span>
  303. <span>用时 <strong>${esc(formatElapsed(s.elapsed_ms || 0))}</strong></span>
  304. </div>
  305. </div>
  306. </div>
  307. <div class="prod-dimm-matrix">
  308. ${renderRow(0, 'C0')}
  309. ${renderRow(12, 'C1')}
  310. </div>
  311. <div class="prod-card-controls">
  312. <label class="prod-ctrl-temp">目标℃<input type="number" min="0" max="254" value="${esc(defaultTarget)}" data-prod-target="${esc(sid)}"></label>
  313. <select class="prod-ctrl-prof" data-prod-profile="${esc(sid)}" aria-label="测试配置">${profOptions}</select>
  314. <button type="button" class="btn btn-primary btn-xs" data-prod-action="start" data-sid="${esc(sid)}">开始测试</button>
  315. <button type="button" class="btn btn-secondary btn-xs" data-prod-action="stop" data-sid="${esc(sid)}">停止</button>
  316. <a class="btn btn-quiet btn-xs" href="/api/stations/${encodeURIComponent(sid)}/alarms.xlsx" download>异常(${alarmCnt}) · 导出.xlsx</a>
  317. <button type="button" class="btn btn-quiet btn-xs" data-prod-action="detail" data-sid="${esc(sid)}">工程详情 →</button>
  318. </div>
  319. </article>`;
  320. }).join('') || '<p class="field-note">当前无已配置工位,请切换至工程视图添加工位。</p>';
  321. grid.querySelectorAll('[data-prod-target]').forEach(inp => {
  322. inp.addEventListener('change', () => {
  323. const v = Math.max(0, Math.min(254, Number(inp.value || 0)));
  324. prodTargetDraft.set(inp.dataset.prodTarget, v);
  325. });
  326. });
  327. grid.querySelectorAll('[data-prod-profile]').forEach(sel => {
  328. sel.addEventListener('change', () => {
  329. prodProfileDraft.set(sel.dataset.prodProfile, sel.value);
  330. });
  331. });
  332. grid.querySelectorAll('[data-prod-curve]').forEach(btn => {
  333. btn.addEventListener('click', () => {
  334. const [sid, slotStr] = btn.dataset.prodCurve.split(':');
  335. const idx = Number(slotStr);
  336. const cpu = idx < 12 ? 0 : 1;
  337. const ch = String.fromCharCode(65 + (idx % 12));
  338. openDimmCurveModal(sid, idx, `CPU${cpu} CH ${ch}`);
  339. });
  340. });
  341. grid.querySelectorAll('[data-prod-action]').forEach(btn => {
  342. btn.addEventListener('click', async () => {
  343. const act = btn.dataset.prodAction;
  344. const sid = btn.dataset.sid;
  345. if (act === 'detail') {
  346. applyUiMode('engineering', true);
  347. prodCallbacks.onSelectStation?.(sid);
  348. return;
  349. }
  350. if (act === 'start') {
  351. const targetInp = grid.querySelector(`[data-prod-target="${CSS.escape(sid)}"]`);
  352. const profSel = grid.querySelector(`[data-prod-profile="${CSS.escape(sid)}"]`);
  353. const targetTemp = Math.max(0, Math.min(254, Number(targetInp?.value ?? 70)));
  354. const profId = profSel?.value || '__current__';
  355. btn.disabled = true;
  356. try {
  357. await prodCallbacks.onStartStation?.(sid, { targetTemp, profileId: profId });
  358. } finally {
  359. btn.disabled = false;
  360. }
  361. } else if (act === 'stop') {
  362. const ok = await confirmDialog(`停止工位 ${sid}`, `确认停止工位 ${sid} 当前测试队列并自动联动高温罩降温吗?`, '确认停止', true);
  363. if (!ok) return;
  364. btn.disabled = true;
  365. try {
  366. await prodCallbacks.onStopStation?.(sid);
  367. } finally {
  368. btn.disabled = false;
  369. }
  370. }
  371. });
  372. });
  373. }
  374. function initUi(callbacks = {}) {
  375. prodCallbacks = callbacks;
  376. $('btn-mode-production')?.addEventListener('click', () => applyUiMode('production', true));
  377. $('btn-mode-engineering')?.addEventListener('click', () => applyUiMode('engineering', true));
  378. $('btn-change-password')?.addEventListener('click', openPasswordModal);
  379. // Confirm modal events
  380. $('stl-confirm-ok')?.addEventListener('click', () => closeConfirm(true));
  381. $('stl-confirm-cancel')?.addEventListener('click', () => closeConfirm(false));
  382. $('stl-confirm-modal')?.addEventListener('click', e => { if (e.target.id === 'stl-confirm-modal') closeConfirm(false); });
  383. // Password modal events
  384. $('pw-modal-cancel')?.addEventListener('click', closePasswordModal);
  385. $('stl-password-modal')?.addEventListener('click', e => { if (e.target.id === 'stl-password-modal') closePasswordModal(); });
  386. $('pw-modal-form')?.addEventListener('submit', async e => {
  387. e.preventDefault();
  388. const cur = $('pw-current').value;
  389. const next = $('pw-new').value;
  390. const conf = $('pw-confirm').value;
  391. const msg = $('pw-modal-msg');
  392. if (next.length < 6) {
  393. msg.textContent = '新密码长度不能少于 6 位';
  394. msg.className = 'field-note error-text';
  395. return;
  396. }
  397. if (next !== conf) {
  398. msg.textContent = '两次输入的新密码不一致';
  399. msg.className = 'field-note error-text';
  400. return;
  401. }
  402. const btn = $('pw-modal-submit');
  403. btn.disabled = true;
  404. msg.textContent = '正在更新密码...';
  405. msg.className = 'field-note';
  406. try {
  407. const res = await fetch('/api/auth/change-password', {
  408. method: 'POST',
  409. credentials: 'same-origin',
  410. headers: { 'Content-Type': 'application/json' },
  411. body: JSON.stringify({ current_password: cur, new_password: next }),
  412. });
  413. const data = await res.json().catch(() => ({}));
  414. if (!res.ok || !data.ok) {
  415. throw new Error(data?.error?.message || `修改失败 (HTTP ${res.status})`);
  416. }
  417. msg.textContent = '密码已更新并持久化,新会话已自动生效。';
  418. msg.className = 'field-note ok-text';
  419. setTimeout(closePasswordModal, 900);
  420. } catch (err) {
  421. msg.textContent = err.message;
  422. msg.className = 'field-note error-text';
  423. } finally {
  424. btn.disabled = false;
  425. }
  426. });
  427. // DIMM curve modal events
  428. $('dimm-curve-close')?.addEventListener('click', closeDimmCurveModal);
  429. $('dimm-curve-refresh')?.addEventListener('click', () => void refreshDimmCurve());
  430. $('stl-dimm-curve-modal')?.addEventListener('click', e => { if (e.target.id === 'stl-dimm-curve-modal') closeDimmCurveModal(); });
  431. // Console expand toggle
  432. $('btn-console-expand')?.addEventListener('click', () => {
  433. const split = document.querySelector('.workspace-split');
  434. if (!split) return;
  435. const expanded = split.classList.toggle('console-expanded');
  436. $('btn-console-expand').textContent = expanded ? '恢复分栏' : '放大终端';
  437. });
  438. // Global Escape closes open modals
  439. document.addEventListener('keydown', e => {
  440. if (e.key !== 'Escape') return;
  441. if (!$('stl-confirm-modal')?.classList.contains('hidden')) closeConfirm(false);
  442. else if (!$('stl-password-modal')?.classList.contains('hidden')) closePasswordModal();
  443. else if (!$('stl-dimm-curve-modal')?.classList.contains('hidden')) closeDimmCurveModal();
  444. });
  445. applyUiMode(state.uiMode, false);
  446. }
  447. window.stlUi = {
  448. init: initUi,
  449. confirm: confirmDialog,
  450. openPasswordModal,
  451. openDimmCurveModal,
  452. setMode: applyUiMode,
  453. getMode: () => state.uiMode,
  454. renderProductionDashboard,
  455. };
  456. })();