| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141 |
- /**
- * utils/router.js —— History API path 路由(/、/p/<id>、/lab/<id>)。
- *
- * - 子路径部署:base 取自 <base href>(解成绝对 URL),所有链接 / 比较都带 base 前缀。
- * - 不支持 pushState(file:// 等)时自动退回 hash(#/p/<id>),功能不变。
- * - 旧 hash 链接(#/p/<id>)启动时 replaceState 改写成对应 path,刷新也不丢。
- * - 链接统一 <a data-link href="...">:全局拦截左键点击 → 只改 history,不整页刷新;
- * target="_blank" / ctrl·cmd·shift·alt 点击 / 中键 / download / 外域 一律交还浏览器默认。
- */
- import { docBase } from '../config.js';
- let BASE = '/';
- try { BASE = new URL(docBase()).pathname.replace(/\/+$/, ''); } catch { BASE = ''; }
- /** 应用内路径 → 浏览器路径('/p/x' → '<base>/p/x') */
- export function appPath(p) {
- const clean = '/' + String(p || '').replace(/^#/, '').replace(/^\/+/, '');
- return BASE + (clean === '/' ? '/' : clean);
- }
- /** pushState 是否可用(file:// 下不可用) */
- export const canHistory = (() => {
- try { return location.protocol !== 'file:' && typeof history.pushState === 'function'; } catch { return false; }
- })();
- /** '/p/ai-pin' → '/base/p/ai-pin'(history 模式)或 '#/p/ai-pin'(hash 回退) */
- export function linkHref(path) {
- return canHistory ? appPath(path) : '#' + (String(path || '/').startsWith('/') ? path : '/' + path);
- }
- /** 浏览器路径 → 应用内路径;不在 base 下(外域 / 静态资源)返回 null */
- export function currentPath() {
- if (!canHistory) {
- const h = location.hash.replace(/^#/, '');
- return h ? '/' + h.replace(/^\/+/, '') : '/';
- }
- let p = location.pathname;
- try { p = decodeURIComponent(p); } catch { /* 保留原文 */ }
- if (BASE && p !== BASE && !p.startsWith(BASE + '/')) return null;
- p = p.slice(BASE.length) || '/';
- return p.startsWith('/') ? p : '/' + p;
- }
- /** 路由匹配:支持 :param;'*' 为兜底 */
- export function matchRoute(pattern, path) {
- if (pattern === '*') return {};
- const pp = pattern.split('/').filter(Boolean);
- const ap = path.split('/').filter(Boolean);
- if (pp.length !== ap.length) return null;
- const params = {};
- for (let i = 0; i < pp.length; i++) {
- const seg = pp[i];
- let v = ap[i];
- try { v = decodeURIComponent(v); } catch { /* 保留原文 */ }
- if (seg.startsWith(':')) params[seg.slice(1)] = v;
- else if (seg !== v) return null;
- }
- return params;
- }
- /** 启动时把 '#/...' 旧链接改写成 path(或把缺失的 hash 规范) */
- function normalizeLegacy() {
- const h = location.hash;
- if (!h || !h.startsWith('#/')) return false;
- const path = h.slice(1);
- const url = canHistory ? appPath(path) + location.search : location.pathname + location.search + '#' + path;
- try { history.replaceState({ ph: 1, legacy: true }, '', url); } catch { return false; }
- return true;
- }
- export function createRouter(routes) {
- const listeners = new Set();
- const notify = () => { for (const fn of listeners) fn(); };
- const router = {
- base: BASE,
- navigate(path, { replace = false } = {}) {
- if (!canHistory) {
- const hash = linkHref(path);
- if (location.hash === hash) { notify(); return; }
- if (replace) { history.replaceState({}, '', location.pathname + location.search + hash); notify(); }
- else location.hash = hash;
- return;
- }
- const url = appPath(path) + location.search;
- if (location.pathname + location.search === url && !location.hash) { notify(); return; }
- history[replace ? 'replaceState' : 'pushState']({ ph: 1 }, '', url);
- notify();
- },
- resolve() {
- const path = currentPath() ?? location.pathname;
- for (const r of routes) {
- const params = matchRoute(r.path, path);
- if (params) return { path, params, route: r.path, render: r.render };
- }
- const last = routes[routes.length - 1];
- return { path, params: {}, route: '*', render: last.render };
- },
- subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
- start(paint) {
- history.scrollRestoration = 'manual';
- normalizeLegacy();
- try { paint(); } catch (e) { console.error('[router] paint initial', e); }
- if (canHistory) {
- addEventListener('popstate', paint);
- // 中转站页面(404.html 副本)把目标路径塞进 sessionStorage:地址栏修正为干净的 path
- try {
- const saved = sessionStorage.getItem('ph:spa-target');
- if (saved) {
- sessionStorage.removeItem('ph:spa-target');
- if (saved !== location.pathname) history.replaceState({ ph: 1, from404: true }, '', saved + location.search + location.hash);
- }
- } catch { /* 隐私模式 */ }
- } else {
- addEventListener('hashchange', paint);
- }
- listeners.add(paint);
- // composedPath 穿透 Shadow DOM;无修饰键左键才算导航
- document.addEventListener('click', (e) => {
- if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
- const a = e.composedPath().find((n) => n instanceof HTMLAnchorElement);
- if (!a) return;
- if (a.target && a.target !== '_self') return;
- if (a.hasAttribute('download')) return;
- const href = a.getAttribute('href');
- if (!href || href.startsWith('mailto:') || href.startsWith('tel:')) return;
- const u = new URL(href, location.href);
- if (u.origin !== location.origin) return; // 外域:交给浏览器
- if (canHistory && href.startsWith('#')) return; // 页内锚点:交给浏览器
- if (!canHistory && !href.startsWith('#')) return;
- // 只接管站内路径;静态资源(带扩展名)与 base 之外的路径交还浏览器
- const isStatic = /\.[a-z0-9]{2,5}$/i.test(u.pathname);
- if (canHistory && (isStatic || (BASE && u.pathname !== BASE && !u.pathname.startsWith(BASE + '/')))) return;
- if (!canHistory && !href.startsWith('#/') && href !== '#') return;
- e.preventDefault();
- const path = canHistory ? (u.pathname.slice(BASE.length) || '/') : u.hash.slice(1);
- router.navigate(path);
- });
- return router;
- },
- };
- return router;
- }
|