ERP/frontend/js/router.js

104 lines
3.0 KiB
JavaScript
Raw Normal View History

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 `<a href="${acc}" style="color:${last ? 'var(--text)' : 'var(--text-2)'};text-decoration:none">${label(p)}</a>`;
}).join(' / ');
}
function label(key) {
const map = {
dashboard: '仪表盘',
login: '登录',
upload: '上传',
mac: 'MAC与批次',
stats: '良/不良统计',
defects: '不良明细',
repairs: '返修记录',
2025-11-21 14:04:43 +00:00
shipments: '发货',
2025-11-22 12:40:46 +00:00
sop: 'SOP',
2025-11-21 14:04:43 +00:00
query: '详细记录查询',
summary: '汇总信息查询',
devices: '设备状态',
environment: '环境参数',
personnel: '人员信息',
qa: '质检报告',
production: '时间记录',
2025-11-23 05:28:53 +00:00
'production-mgmt': '生产管理',
'work-order': '生产工单下发中心',
export: '导出',
settings: '设置'
};
return map[key] || key;
}
return { register, init, onBeforeEach, onAfterEach };
})();