const Router = (() => { const routes = {}; const beforeEachHooks = []; const afterEachHooks = []; function register(path, render) { routes[path] = render; } function onBeforeEach(fn) { beforeEachHooks.push(fn); } function onAfterEach(fn) { afterEachHooks.push(fn); } async function navigate(path) { for (const h of beforeEachHooks) await h(path); const view = document.getElementById('view'); view.classList.add('fade-enter'); const render = routes[path] || routes['/404']; const html = await render(); view.innerHTML = html; requestAnimationFrame(() => { view.classList.add('fade-enter-active'); view.classList.remove('fade-enter'); setTimeout(() => view.classList.remove('fade-enter-active'), 220); }); for (const h of afterEachHooks) await h(path); } async function init() { window.addEventListener('hashchange', () => { const path = location.hash.replace('#', '') || '/dashboard'; navigate(path); highlightActive(path); updateBreadcrumb(path); }); // 检查用户登录状态,决定默认路径 let defaultPath = '/dashboard'; try { const user = await API.me().catch(() => null); if (!user || !user.username) { defaultPath = '/login'; } } catch(e) { defaultPath = '/login'; } const path = location.hash.replace('#', '') || defaultPath; navigate(path); highlightActive(path); updateBreadcrumb(path); } function highlightActive(path) { document.querySelectorAll('.nav-item, .nav-child').forEach(el => el.classList.remove('active')); const target = document.querySelector(`[data-route="${routeKey(path)}"]`); if (target) target.classList.add('active'); } function routeKey(path) { return path .replace('/', '') .replaceAll('/', '-') || 'dashboard'; } function updateBreadcrumb(path) { const bc = document.getElementById('breadcrumb'); const parts = path.split('/').filter(Boolean); let acc = '#'; bc.innerHTML = parts.map((p, i) => { acc += '/' + p; const last = i === parts.length - 1; return `${label(p)}`; }).join(' / '); } function label(key) { const map = { dashboard: '仪表盘', login: '登录', upload: '上传', mac: 'MAC与批次', stats: '良/不良统计', defects: '不良明细', repairs: '返修记录', shipments: '发货记录', query: '查询', devices: '设备状态', environment: '环境参数', personnel: '人员信息', qa: '质检报告', production: '时间记录', export: '导出', settings: '设置' }; return map[key] || key; } return { register, init, onBeforeEach, onAfterEach }; })();