router.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. /**
  2. * utils/router.js —— History API path 路由(/、/p/<id>、/lab/<id>)。
  3. *
  4. * - 子路径部署:base 取自 <base href>(解成绝对 URL),所有链接 / 比较都带 base 前缀。
  5. * - 不支持 pushState(file:// 等)时自动退回 hash(#/p/<id>),功能不变。
  6. * - 旧 hash 链接(#/p/<id>)启动时 replaceState 改写成对应 path,刷新也不丢。
  7. * - 链接统一 <a data-link href="...">:全局拦截左键点击 → 只改 history,不整页刷新;
  8. * target="_blank" / ctrl·cmd·shift·alt 点击 / 中键 / download / 外域 一律交还浏览器默认。
  9. */
  10. import { docBase } from '../config.js';
  11. let BASE = '/';
  12. try { BASE = new URL(docBase()).pathname.replace(/\/+$/, ''); } catch { BASE = ''; }
  13. /** 应用内路径 → 浏览器路径('/p/x' → '<base>/p/x') */
  14. export function appPath(p) {
  15. const clean = '/' + String(p || '').replace(/^#/, '').replace(/^\/+/, '');
  16. return BASE + (clean === '/' ? '/' : clean);
  17. }
  18. /** pushState 是否可用(file:// 下不可用) */
  19. export const canHistory = (() => {
  20. try { return location.protocol !== 'file:' && typeof history.pushState === 'function'; } catch { return false; }
  21. })();
  22. /** '/p/ai-pin' → '/base/p/ai-pin'(history 模式)或 '#/p/ai-pin'(hash 回退) */
  23. export function linkHref(path) {
  24. return canHistory ? appPath(path) : '#' + (String(path || '/').startsWith('/') ? path : '/' + path);
  25. }
  26. /** 浏览器路径 → 应用内路径;不在 base 下(外域 / 静态资源)返回 null */
  27. export function currentPath() {
  28. if (!canHistory) {
  29. const h = location.hash.replace(/^#/, '');
  30. return h ? '/' + h.replace(/^\/+/, '') : '/';
  31. }
  32. let p = location.pathname;
  33. try { p = decodeURIComponent(p); } catch { /* 保留原文 */ }
  34. if (BASE && p !== BASE && !p.startsWith(BASE + '/')) return null;
  35. p = p.slice(BASE.length) || '/';
  36. return p.startsWith('/') ? p : '/' + p;
  37. }
  38. /** 路由匹配:支持 :param;'*' 为兜底 */
  39. export function matchRoute(pattern, path) {
  40. if (pattern === '*') return {};
  41. const pp = pattern.split('/').filter(Boolean);
  42. const ap = path.split('/').filter(Boolean);
  43. if (pp.length !== ap.length) return null;
  44. const params = {};
  45. for (let i = 0; i < pp.length; i++) {
  46. const seg = pp[i];
  47. let v = ap[i];
  48. try { v = decodeURIComponent(v); } catch { /* 保留原文 */ }
  49. if (seg.startsWith(':')) params[seg.slice(1)] = v;
  50. else if (seg !== v) return null;
  51. }
  52. return params;
  53. }
  54. /** 启动时把 '#/...' 旧链接改写成 path(或把缺失的 hash 规范) */
  55. function normalizeLegacy() {
  56. const h = location.hash;
  57. if (!h || !h.startsWith('#/')) return false;
  58. const path = h.slice(1);
  59. const url = canHistory ? appPath(path) + location.search : location.pathname + location.search + '#' + path;
  60. try { history.replaceState({ ph: 1, legacy: true }, '', url); } catch { return false; }
  61. return true;
  62. }
  63. export function createRouter(routes) {
  64. const listeners = new Set();
  65. const notify = () => { for (const fn of listeners) fn(); };
  66. const router = {
  67. base: BASE,
  68. navigate(path, { replace = false } = {}) {
  69. if (!canHistory) {
  70. const hash = linkHref(path);
  71. if (location.hash === hash) { notify(); return; }
  72. if (replace) { history.replaceState({}, '', location.pathname + location.search + hash); notify(); }
  73. else location.hash = hash;
  74. return;
  75. }
  76. const url = appPath(path) + location.search;
  77. if (location.pathname + location.search === url && !location.hash) { notify(); return; }
  78. history[replace ? 'replaceState' : 'pushState']({ ph: 1 }, '', url);
  79. notify();
  80. },
  81. resolve() {
  82. const path = currentPath() ?? location.pathname;
  83. for (const r of routes) {
  84. const params = matchRoute(r.path, path);
  85. if (params) return { path, params, route: r.path, render: r.render };
  86. }
  87. const last = routes[routes.length - 1];
  88. return { path, params: {}, route: '*', render: last.render };
  89. },
  90. subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
  91. start(paint) {
  92. history.scrollRestoration = 'manual';
  93. normalizeLegacy();
  94. try { paint(); } catch (e) { console.error('[router] paint initial', e); }
  95. if (canHistory) {
  96. addEventListener('popstate', paint);
  97. // 中转站页面(404.html 副本)把目标路径塞进 sessionStorage:地址栏修正为干净的 path
  98. try {
  99. const saved = sessionStorage.getItem('ph:spa-target');
  100. if (saved) {
  101. sessionStorage.removeItem('ph:spa-target');
  102. if (saved !== location.pathname) history.replaceState({ ph: 1, from404: true }, '', saved + location.search + location.hash);
  103. }
  104. } catch { /* 隐私模式 */ }
  105. } else {
  106. addEventListener('hashchange', paint);
  107. }
  108. listeners.add(paint);
  109. // composedPath 穿透 Shadow DOM;无修饰键左键才算导航
  110. document.addEventListener('click', (e) => {
  111. if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
  112. const a = e.composedPath().find((n) => n instanceof HTMLAnchorElement);
  113. if (!a) return;
  114. if (a.target && a.target !== '_self') return;
  115. if (a.hasAttribute('download')) return;
  116. const href = a.getAttribute('href');
  117. if (!href || href.startsWith('mailto:') || href.startsWith('tel:')) return;
  118. const u = new URL(href, location.href);
  119. if (u.origin !== location.origin) return; // 外域:交给浏览器
  120. if (canHistory && href.startsWith('#')) return; // 页内锚点:交给浏览器
  121. if (!canHistory && !href.startsWith('#')) return;
  122. // 只接管站内路径;静态资源(带扩展名)与 base 之外的路径交还浏览器
  123. const isStatic = /\.[a-z0-9]{2,5}$/i.test(u.pathname);
  124. if (canHistory && (isStatic || (BASE && u.pathname !== BASE && !u.pathname.startsWith(BASE + '/')))) return;
  125. if (!canHistory && !href.startsWith('#/') && href !== '#') return;
  126. e.preventDefault();
  127. const path = canHistory ? (u.pathname.slice(BASE.length) || '/') : u.hash.slice(1);
  128. router.navigate(path);
  129. });
  130. return router;
  131. },
  132. };
  133. return router;
  134. }