Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

refactor(web): 路由收拢成一张 ROUTES 表

longmeidaoa88ff312397c
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 193cb6c13..597353b92 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -1403,23 +1403,28 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertEqual(keys[keys.index("follow") + 1], "immerse",
"关注入口应当排在沉浸模式前面")
self.assertPageContains("['follow','关注','rss']")
- self.assertPageContains("if(k==='follow'){openFollow();return}")
- self.assertPageContains("if(k==='follow')return path==='/follow';")
+ # 关注入口的路径、导航键和高亮都在路由表那一条里(web/app.js 的 ROUTES),
+ # 不再是 navTo/navOn 各写一条 `k==='follow'` 分支。
+ self.assertPageContains("{match:'/follow',nav:'follow',title:'关注',refresh:'skip',")
+ self.assertPageContains("open:(params,push)=>openFollow(push),reload:()=>openFollow(false)},")
# 两个数组现在同名,字面量断言分不出是哪一个:
# 管理区这一项得在 MANAGE_SECTIONS 里找,否则它被删了测试照样绿。
manage = self.page[self.page.index("const MANAGE_SECTIONS=["):]
manage = manage[:manage.index("];")]
self.assertIn("['follow','关注','rss']", manage)
self.assertPageContains('<symbol id="i-rss"')
- self.assertPageContains("if(path==='/follow-manage')return 'follow'")
- self.assertPageContains("if(section==='follow'){openFollowManage();return}")
+ # 管理区身份同理:`section` 写在路由表上,`openManage('follow')` 按它查表。
+ self.assertPageContains("{match:'/follow-manage',section:'follow',title:'关注管理',refresh:'skip',")
+ self.assertPageContains("open:(params,push)=>openFollowManage(push)},")
def test_follow_routes_restore_on_reload(self):
- self.assertPageContains("if(path==='/follow'){await openFollow(false);return}")
+ # 恢复只有一个派发点:路径匹配到哪条路由,就打开那一屏。
+ self.assertPageContains("const hit=matchRoute(ROUTES,path);")
+ self.assertPageContains("if(hit)await hit.route.open(hit.params,false);")
+ self.assertPageContains("open:(params,push)=>openFollow(push),reload:()=>openFollow(false)},")
+ self.assertPageContains("open:(params,push)=>openFollowManage(push)},")
self.assertPageContains(
- "if(path==='/follow-manage'){await openFollowManage(false);return}")
- self.assertPageContains(
- "await openFollow(false,true);await openFollowDetail(+parts[2],false)")
+ "await openFollow(push,true);await openFollowDetail(params.id,push)")
self.assertPageContains("api(`/api/follow?item=${encodeURIComponent(id)}`)")
self.assertPageContains(".then(async()=>{buildEdge();wireAllDrag();await restoreRoute();scheduleStickySurfaces()})")
@@ -1881,7 +1886,7 @@ class FollowWebSourceTests(unittest.TestCase):
self.assertPageContains("async function openFollow(push=true,renderForDetail=false)")
self.assertPageContains("const surface=claimSurface(renderForDetail?surfacePath():'/follow')")
self.assertPageContains("if(!surfaceCurrent(surface))return")
- self.assertPageContains("await openFollow(false,true);await openFollowDetail(+parts[2],false)")
+ self.assertPageContains("await openFollow(push,true);await openFollowDetail(params.id,push)")
self.assertPageContains("const followList=$('#stats').querySelector('.followlist')")
# 就近展开:插在被点击那张卡片所在的一行之后,不是整个列表之前。
# 插在列表前等于每次都把视线拽回页面顶部,翻了几屏点开一条尤其明显。
@@ -1984,9 +1989,11 @@ class FollowWebSourceTests(unittest.TestCase):
def test_network_check_is_an_explicit_button_not_an_auto_refresh(self):
self.assertPageContains("data-follow-check")
- # 「换一批」自动刷新绝不能顺手触发一次联网检查。
- self.assertPageContains(
- "if(location.pathname==='/follow'||location.pathname==='/follow-manage')return;")
+ # 「换一批」自动刷新绝不能顺手触发一次联网检查。这件事现在由路由表上的
+ # `refresh:'skip'` 表达:refreshAll 只认这个标记,两个关注页各自带一个。
+ self.assertPageContains("if(hit?.route.refresh==='skip')return;")
+ self.assertPageContains("{match:'/follow',nav:'follow',title:'关注',refresh:'skip',")
+ self.assertPageContains("{match:'/follow-manage',section:'follow',title:'关注管理',refresh:'skip',")
def test_every_entered_state_can_be_left_again(self):
self.assertPageContains("""item.status==='seen'||item.status==='ignored'""")
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 21b2fecfb..ffde9dd16 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -34,6 +34,26 @@ class WebUiSourceTests(unittest.TestCase):
if needle in self.page:
self.fail(f"index.html 不应再出现:{needle!r}" + (f"({message})" if message else ""))
+ def route_entry(self, match: str) -> str:
+ """路由表里 `match` 那一条的源码。
+
+ 「哪个路径进哪一屏」是用户能感知的契约;它是写成一张表还是写成一条
+ 二十五分支的 if 链,是实现细节。这些断言问的是「这条路径在不在、进去的是
+ 哪一屏」,所以换派发方式不该让它们变红——真把一条路径弄丢了才该红。
+ """
+ table = self.app_js.split("\nconst ROUTES=[", 1)[1].split("\n];", 1)[0]
+ for entry in re.split(r"\n (?=\{match:|\.\.\.)", table):
+ if entry.lstrip().startswith("{match:'%s'" % match):
+ return entry
+ listed = ", ".join(re.findall(r"\{match:'([^']+)'", table))
+ self.fail(f"路由表里没有 {match}(表里有:{listed})")
+
+ def assertRoute(self, match: str, *needles: str):
+ entry = self.route_entry(match)
+ for needle in needles:
+ if needle not in entry:
+ self.fail(f"路由 {match} 这一条缺少:{needle!r}")
+
def test_module_level_bindings_are_declared_before_they_are_used(self):
"""模块级 `let`/`const` 不许在声明行之前被引用。
@@ -279,9 +299,13 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains('button,a,input,textarea,select,summary{touch-action:manipulation}')
def test_route_titles_and_settings_dialog_manage_focus(self):
- self.assertPageContains('const pageTitle=path=>{')
- self.assertPageContains("'follow-manage':'关注管理'")
- self.assertPageContains("unseen:'没看过','watch-later':'稍后看',flagged:'已标记'")
+ # 标题跟着路由表走:每一屏的标签写在自己那条记录上,不再有第二份
+ # 「路径 → 标题」映射跟路由分支各自演化。
+ self.assertPageContains("const label=routeLabel(ROUTES,decodeURIComponent(url.pathname));")
+ self.assertPageContains("document.title=label?`${label} · Peach`:'Peach · 蜜桃';")
+ self.assertRoute('/follow-manage', "title:'关注管理'")
+ # 目录页四个筛选态的标题就是筛选名本身,和侧栏取同一份 STATE_LABELS。
+ self.assertPageContains("title:STATE_LABELS[key],open:()=>openCatalog(path)")
self.assertPageContains('syncPageTitle(path);')
self.assertPageContains('queueMicrotask(()=>{syncHeaderActions();paintListTitle()})')
self.assertPageContains("queueMicrotask(()=>$('#settingsClose').focus())")
@@ -733,8 +757,10 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageLacks("localStorage.getItem(SEED_KEY)")
self.assertPageContains("seed:initialParam('seed')||rollSeed()")
self.assertPageContains("sort:appSettings.defaultSort,seed:rollSeed(),q:''")
- self.assertPageContains("const previousPath=lastRoutePath;lastRoutePath=path;")
- self.assertPageContains("const enteringHome=path==='/'&&previousPath!=='/';")
+ # 「从别处回到首页」才换种子,判据是上一屏的路径,所以 lastRoutePath
+ # 必须等这一屏打开之后再更新。
+ self.assertPageContains("const enteringHome=path==='/'&&lastRoutePath!=='/';")
+ self.assertPageContains("}finally{lastRoutePath=path}")
self.assertPageContains("enteringHome?rollSeed():state.seed||rollSeed()")
self.assertPageContains("const SORTS=[['seed','随机'],['rating','评分']")
self.assertPageContains('<option value="seed">随机</option>')
@@ -1393,7 +1419,7 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains('<div class="linkhosts"><span>最多的站点</span>')
def test_taste_page_combines_private_exports_and_peach_behavior(self):
- self.assertPageContains("if(path==='/taste'){await openTaste(false);return}")
+ self.assertRoute('/taste', "openTaste(push)", "section:'taste'")
self.assertPageContains("/api/taste?window=")
self.assertPageContains("/api/taste/import")
self.assertPageContains("/api/taste/refresh")
@@ -1538,13 +1564,66 @@ class WebUiSourceTests(unittest.TestCase):
表现就是抽屉里点「在线追更」没反应,点窄栏同一个图标却能进。
"""
self.assertPageContains("function navTo(k){")
- self.assertPageContains("if(k==='follow'){openFollow();return}")
- self.assertPageContains("if(k==='playlists'){openPlaylists();return}")
+ # 有自己路径的入口一律从路由表进,两边点同一个键必然到同一屏。
+ self.assertPageContains("const target=ROUTES.find(spec=>spec.nav===k&&!STATE_ROUTES[k]);")
+ self.assertRoute('/follow', "nav:'follow'", "openFollow(push)")
+ self.assertRoute('/playlists', "nav:'playlists'", "openPlaylists(push)")
self.assertPageContains(
"$('#drawer').querySelectorAll('[data-nav]').forEach(b=>b.onclick=()=>navTo(b.dataset.nav));")
self.assertPageContains("e.stopPropagation();navTo(b.dataset.nav)})")
- # 分支只能存在一处;再出现第二份就是下一次漂移。
- self.assertEqual(self.page.count("if(k==='immerse'){openTok();return}"), 1)
+ # 派发只能存在一处;再出现第二份就是下一次漂移。
+ self.assertEqual(self.app_js.count("ROUTES.find(spec=>spec.nav===k"), 1,
+ "导航跳转只能查一次路由表")
+ self.assertEqual(self.app_js.count("function navTo(k){"), 1)
+
+ def test_one_route_table_owns_every_surface_dispatch(self):
+ """「哪个路径进哪一屏」只有一份真相,七处副本不许回来。
+
+ 以前 restoreRoute 是一条二十五分支的 if 链,navTo、navOn、openManage、
+ manageSection、reloadCurrentSurface、refreshAll 各自又抄了自己关心的那几条。
+ 加一屏要改七处,漏一处的症状还各不相同:URL 能进但侧栏不亮、点进去了但
+ 「换一批」把你扔回统计页、批量操作后回到首页而不是刚才那一屏。
+ """
+ for match in ('/', '/trash', '/playlists', '/playlists/:playlist/:item',
+ '/mix/:seed/:item', '/parts/:seed/:item', '/editions/:seed/:item',
+ '/item/:id', '/follow/item/:id', '/performers', '/creators', '/tags',
+ '/stats', '/taste', '/review', '/data-cleanup', '/duplicates',
+ '/resource-sync', '/quality-goals', '/follow', '/follow-manage',
+ '/immerse'):
+ self.route_entry(match)
+ # 目录页四态和四种实体页由既有的映射生成:两边各写一份就会出现
+ # 「路由认得、isCatalogPath 不认得」这种半死路径。
+ self.assertPageContains("...Object.entries(STATE_ROUTES).map(([key,path])=>({")
+ self.assertPageContains("...Object.entries(ROUTE_ENTITIES).map(([segment,kind])=>({")
+ # 派发只有一处:匹配到哪条就打开哪条,没匹配上才回首页表面。
+ self.assertPageContains("const hit=matchRoute(ROUTES,path);")
+ self.assertPageContains("if(hit)await hit.route.open(hit.params,false);")
+ self.assertPageContains("else{showHomeSurfaces();disposeStage(false)}")
+ for revived in ("if(path==='/stats')", "if(path==='/taste')", "if(path==='/immerse')",
+ "if(path==='/follow-manage')", "if(parts[0]==='item'",
+ "const entityKind=ROUTE_ENTITIES[parts[0]]"):
+ self.assertPageLacks(revived, "路径判定回到了 restoreRoute 的分支链")
+ # 迁移期要能让 frontend/ 里的一屏自己登记,不必回来改这张表(ADR-0022)。
+ self.assertPageContains("const registerRoute=spec=>{ROUTES.push(spec);return spec};")
+ self.assertPageContains("window.peachRegisterRoute=registerRoute;")
+
+ def test_route_patterns_only_match_numeric_ids(self):
+ """动态段只吃数字,实体名吃掉剩下全部段。
+
+ 原来每条动态路由都自己写一遍数字校验,忘写的那条会把 /item/abc 当成
+ 合法 id 送进 `+parts[1]`,得到 NaN;实体名里有斜杠,所以那一段必须贪心。
+ """
+ self.assertPageContains(r"if (!/^\d+$/.test(got[i] || '')) return null;")
+ self.assertPageContains("params[name] = Number(got[i]);")
+ self.assertPageContains("const tail = got.slice(i).join('/');")
+ # 匹配失败返回 null,空参数对象仍是真值——路由表里有一堆没有参数的精确路径。
+ self.assertPageContains("return got.length === want.length ? params : null;")
+
+ def test_immersive_mode_keeps_the_current_clip_in_the_url(self):
+ """竖划切片也过 route():刷新之后落回同一条片子,而不是重新抽一批。"""
+ self.assertPageContains("route('/immerse?id='+it.id,true);")
+ self.assertRoute('/immerse', "openTok(immerseStartId(),push)")
+ self.assertPageContains("function immerseStartId(){")
def test_online_assets_use_rss_and_open_the_saved_follow_surface(self):
self.assertPageContains("online:icon('rss')")
@@ -1688,7 +1767,9 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("decodeURIComponent(location.pathname)!==decodeURIComponent(expectedPath)")
index = self.page.split("async function openIndex", 1)[1].split("const d=await api", 1)[0]
self.assertIn("showHomeSurfaces();", index)
- self.assertPageContains("if(!$('#stats').hidden){\n if(location.pathname==='/review'){await openReview(false);return}")
+ # 「换一批」在管理区的行为写在路由表的 refresh 上,不再每页一条分支。
+ self.assertPageContains("if(hit?.route.refresh==='reopen'){await hit.route.open(hit.params,false);return}")
+ self.assertRoute('/review', "refresh:'reopen'")
def test_immersive_close_restores_the_home_surface(self):
self.assertPageContains("document.body.style.overflow='';openHome()")
@@ -1730,7 +1811,12 @@ class WebUiSourceTests(unittest.TestCase):
def test_top_level_highlight_is_exclusive_and_covers_index_pages(self):
"""首页原来只看 state.state,进管理区和索引页时它仍然亮着,两个入口同时高亮。"""
- self.assertPageContains("if(k==='performers'||k==='tags')return path==='/'+k")
+ # 高亮由「当前路径匹配到哪条路由」决定,索引页和实体页因此天然分开:
+ # /performers 有 nav,/performers/<名字> 没有,不会两个入口一起亮。
+ self.assertPageContains("const nav=matchRoute(ROUTES,path)?.route.nav||'';")
+ self.assertPageContains("if(nav)return nav===k;")
+ self.assertRoute('/performers', "nav:'performers'")
+ self.assertRoute('/tags', "nav:'tags'")
self.assertPageContains("if(k==='')return path==='/'&&!manageSection()&&!state.state")
self.assertPageContains("buildEdge(); // 顶层高亮跟随管理区")
@@ -2140,8 +2226,7 @@ class WebUiSourceTests(unittest.TestCase):
# 而主列表的 exclude_vertical 管不到这条——它是独立请求、独立插入的。
self.assertPageContains("!isCatalogPath(decodeURIComponent(location.pathname))||javActive()||state.orient==='竖屏'")
self.assertPageContains("||state.state==='ads'||state.state==='trash'")
- self.assertPageContains("route(section==='trash'?'/trash':junkPath())")
- self.assertPageContains("if(path==='/trash')")
+ self.assertRoute('/trash', "section:'trash'", "openTrash(push)")
self.assertPageContains("/api/trash/empty")
def test_multipart_releases_use_a_distinct_group_card_and_queue(self):
@@ -2155,7 +2240,7 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("route(`/parts/${seedId}/${chosen}`)")
self.assertPageContains("queue.kind==='parts'?`${queue.items.length} 卷`")
self.assertPageContains("queueContext.kind==='parts'?openParts")
- self.assertPageContains("if(parts[0]==='parts'")
+ self.assertRoute('/parts/:seed/:item', "openParts(params.seed,params.item,push)")
self.assertPageContains(".partstack::before,.partstack::after")
self.assertPageLacks("Mix · ${group.title}")
@@ -2409,8 +2494,9 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("document.querySelectorAll('#grid > .card[data-id]')")
def test_recycle_bin_has_its_own_route_and_reports_undeletable_files(self):
- self.assertPageContains("route(section==='trash'?'/trash':junkPath())")
- self.assertPageContains("if(path==='/trash'){")
+ self.assertRoute('/trash', "section:'trash'", "openTrash(push)")
+ self.assertPageContains("function openTrash(push){")
+ self.assertPageContains("state:'trash',q:''};$('#q').value='';")
self.assertPageContains("/api/trash/empty")
self.assertPageContains("r.blocked&&r.blocked.length")
@@ -2495,7 +2581,7 @@ class WebUiSourceTests(unittest.TestCase):
"""
# 限宽已回退:整条规则不许再出现(重排导航/标题前是已知的坏版式)。
self.assertPageLacks("max-width:1004px;margin-inline:auto")
- self.assertPageContains("document.body.dataset.surface=new URL(path,location.origin).pathname")
+ self.assertPageContains("document.body.dataset.surface=url.pathname")
# 导航激活态随路由重算:抽屉/窄栏按钮是 buildBars 时一次性画的,
# 管理页不跑 buildBars,不重算就会停留在上一个页面的按下态。
self.assertPageContains("paintNav();")
@@ -2654,7 +2740,7 @@ class WebUiSourceTests(unittest.TestCase):
def test_better_version_targets_have_a_management_page(self):
self.assertPageContains("['quality','高清版','sparkles']")
- self.assertPageContains("if(path==='/quality-goals')return 'quality'")
+ self.assertRoute('/quality-goals', "section:'quality'", "openQualityGoals(push)")
self.assertPageContains("async function openQualityGoals(push=true)")
# 这一页已经迁到 Preact island(ADR-0022):取数与渲染在 frontend/ 里,遗留层
# 只剩外壳。所以这里断言的是挂载契约,而不是端点字符串——端点由
@@ -2677,7 +2763,7 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("candidate.content_id||candidate.provider_id")
self.assertPageContains(".metadataevidence>div{display:grid;grid-template-columns:68px minmax(0,1fr)")
self.assertPageContains("/api/review/decision")
- self.assertPageContains("if(path==='/review')")
+ self.assertRoute('/review', "section:'review'", "openReview(push)")
self.assertPageContains('class="revieworigin"')
self.assertPageContains('data-review-open-item="${row.asset_id}"')
self.assertPageContains("openItem(+button.dataset.reviewOpenItem)")
@@ -2697,9 +2783,13 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageLacks("发行 ${esc(it.release_date)}")
def test_duplicates_page_is_part_of_the_combined_cleanup_section(self):
- self.assertPageContains("path==='/data-cleanup'||path==='/duplicates'||path==='/junk-files'")
- self.assertPageContains("if(section==='cleanup'){openDataCleanup();return}")
- self.assertPageContains("if(section==='dupes'){openDuplicates();return}")
+ # 数据管理、重复文件、垃圾文件是同一件事的三步,共用一个管理身份,
+ # 所以进任何一屏管理条都停在「数据管理」上。
+ self.assertRoute('/data-cleanup', "section:'cleanup'")
+ self.assertRoute('/duplicates', "section:'cleanup'", "openDuplicates(push)")
+ self.assertPageContains("return hit?.route.section||(state.state==='ads'?'cleanup':'');")
+ # openManage('cleanup') 该开数据管理本身:靠 /data-cleanup 在表里排在前面。
+ self.assertPageContains("const target=ROUTES.find(spec=>spec.section===section);")
self.assertPageContains("async function openDuplicates(push=true)")
def test_data_cleanup_groups_junk_duplicates_and_empty_folders_in_fieldsets(self):
@@ -2728,7 +2818,7 @@ class WebUiSourceTests(unittest.TestCase):
# 按钮一律靠右;左边有说明时说明推到最左。
self.assertPageContains("justify-content:flex-end;gap:8px;")
self.assertPageContains(".resourcesyncfooter>p,.resourceapplyrow>p{min-width:0;margin-right:auto}")
- self.assertPageContains("if(path==='/data-cleanup'){await openDataCleanup(false);return}")
+ self.assertRoute('/data-cleanup', "openDataCleanup(push)")
def test_fieldset_bars_keep_one_row_and_one_button_shape_on_narrow_screens(self):
"""窄屏下操作条仍是一行,按钮按内容宽、填 --surface,不铺满也不换第二种样式。
@@ -3096,7 +3186,7 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("${stacked?'<div class=\"partstack\">':''}")
self.assertPageContains("${stacked?'</div>':''}")
self.assertPageContains("openEditions(it.edition_group.seed_id,id,true,anchor)")
- self.assertPageContains("if(parts[0]==='editions'", "刷新或前进后退要能回到同一个版次")
+ self.assertRoute('/editions/:seed/:item', "openEditions(params.seed,params.item,push)")
def test_entity_pages_collapse_edition_groups_too(self):
"""资料页的网格也要折叠版次组。
@@ -3625,7 +3715,7 @@ class WebUiSourceTests(unittest.TestCase):
def test_resource_sync_lives_in_data_management_and_keeps_offline_sources_safe(self):
self.assertPageContains("${resourceSyncMarkup()}")
- self.assertPageContains("if(path==='/resource-sync'){await openResourceSync(false);return}")
+ self.assertRoute('/resource-sync', "openResourceSync(push)")
self.assertPageContains("route('/data-cleanup#resource-sync',!push)")
self.assertPageContains("api('/api/resource-sync/scan',{method:'POST'")
self.assertPageContains("api('/api/resource-sync/apply',{method:'POST'")
diff --git a/web/app.js b/web/app.js
index d0e442753..6bde10426 100644
--- a/web/app.js
+++ b/web/app.js
@@ -1,5 +1,6 @@
-import {$, ENTITY_ROUTES, LOC, ROUTE_ENTITIES, ROUTE_STATES, SITE_FAVICONS, STATE_LABELS, STATE_ROUTES, api, isAbort, mapLimit, brandIcon, entityPath, esc, faviconFallbackUrl, faviconUrl, linkHost, linkMarkUrl, fmtClock, fmtDur, fmtSize, foldName, icon, isCatalogPath, pageTitle, realDuration} from './js/core.js';
+import {$, ENTITY_ROUTES, LOC, ROUTE_ENTITIES, ROUTE_STATES, SITE_FAVICONS, STATE_LABELS, STATE_ROUTES, api, isAbort, mapLimit, brandIcon, entityPath, esc, faviconFallbackUrl, faviconUrl, linkHost, linkMarkUrl, fmtClock, fmtDur, fmtSize, foldName, icon, isCatalogPath, realDuration} from './js/core.js';
import { imageFallbackAttrs, wireImageFallbacks } from './js/image-fallback.js';
+import { matchRoute, routeLabel } from './js/routes.js';
import { initMiddleTruncate } from './js/middle-truncate.js';
import { tagLabel } from './js/tags.js';
import {
@@ -40,6 +41,87 @@ let edgeT=null;
let searchActive=-1;
/* ────────────────────────────────────────────────────────────────────────── */
+/* ── 路由表 ───────────────────────────────────────────────────────────────────
+ 一屏一条。`match` 的三种写法见 `web/js/routes.js`,其余字段:
+
+ - `open(params,push)`:进入这一屏。`push=false` 表示地址栏已经是它了——首屏
+ 恢复、popstate、换一批都是这种,此时不再 `route()`。
+ - `title`:document.title 用的标签,字符串或拿 params 算的函数;不写则用站名。
+ - `nav`:侧栏/抽屉里 `data-nav` 的键,同时决定高亮(`navOn`)和跳转(`navTo`)。
+ - `section`:管理区身份(`manageSection`),也是 `openManage` 的入口键。
+ - `refresh`:列表栏 ⟳「换一批」在这一屏的行为。`reopen` 重开自己;`skip` 不参与
+ ——追更页重画要联网,只能由它自己的按钮触发;不写则回统计页。
+ - `reload`:批量操作后就地重取(`reloadCurrentSurface`)。它和 `open` 的区别是
+ 要保留页内已经打好的输入,所以不能拿 `open` 顶替。
+
+ 顺序即优先级:先匹配上的赢,所以精确路径写在同前缀的动态路径前面。
+
+ 这张表替掉的是同一份知识的七个副本:`restoreRoute` 的分支链,加上 `navTo`、
+ `navOn`、`openManage`、`manageSection`、`reloadCurrentSurface`、`refreshAll`
+ 各自抄的那几条。加一屏原来要改七处,漏一处的症状还各不相同:URL 能进但侧栏不亮、
+ 点进去了但「换一批」把你扔回统计页、批量操作后回到首页而不是刚才那一屏。 */
+const ROUTES=[
+ /* 目录页:首页和四个筛选态是同一屏,路径只决定初始筛选,所以共用一个 open。
+ 四条筛选态直接由 STATE_ROUTES 生成——它同时是 `isCatalogPath` 的判据,
+ 两边各写一份就会有「路由认得、目录判定不认得」的半死路径。 */
+ {match:'/',open:()=>openCatalog('/')},
+ ...Object.entries(STATE_ROUTES).map(([key,path])=>({
+ match:path,nav:key,title:STATE_LABELS[key],open:()=>openCatalog(path)})),
+ {match:'/trash',section:'trash',open:(params,push)=>openTrash(push)},
+ {match:'/playlists',nav:'playlists',title:'播放列表',refresh:'reopen',
+ open:(params,push)=>openPlaylists(push)},
+ {match:'/playlists/:playlist/:item',nav:'playlists',title:'播放列表',
+ open:(params,push)=>openPlaylist(params.playlist,params.item,push)},
+ {match:'/mix/:seed/:item',title:'Mix',
+ open:(params,push)=>openMix(params.seed,params.item,push)},
+ {match:'/parts/:seed/:item',open:(params,push)=>openParts(params.seed,params.item,push)},
+ {match:'/editions/:seed/:item',open:(params,push)=>openEditions(params.seed,params.item,push)},
+ {match:'/item/:id',title:'作品',open:(params,push)=>openItem(params.id,push)},
+ /* 追更详情要先把列表铺好:详情页的返回、上一条/下一条都从那份列表来。 */
+ {match:'/follow/item/:id',title:'关注',open:async(params,push)=>{
+ await openFollow(push,true);await openFollowDetail(params.id,push)}},
+ /* 实体资料页。四种实体只有 kind 不同,名字里可能带斜杠,所以吃掉剩下全部段。 */
+ ...Object.entries(ROUTE_ENTITIES).map(([segment,kind])=>({
+ match:`/${segment}/:name*`,title:params=>params.name,
+ open:(params,push)=>openEntity(kind,params.name,push)})),
+ {match:'/performers',nav:'performers',title:'女优',
+ open:(params,push)=>openIndexRoute('performers',push),
+ reload:()=>openIndexRoute('performers',false,indexQuery())},
+ {match:'/creators',title:'创作者',
+ open:(params,push)=>openIndexRoute('creators',push),
+ reload:()=>openIndexRoute('creators',false,indexQuery())},
+ {match:'/tags',nav:'tags',title:'标签',
+ open:(params,push)=>openIndexRoute('tags',push),
+ reload:()=>openIndexRoute('tags',false,indexQuery())},
+ {match:'/stats',section:'stats',title:'统计',open:(params,push)=>openStats(push)},
+ {match:'/taste',section:'taste',title:'口味',refresh:'reopen',
+ open:(params,push)=>openTaste(push)},
+ {match:'/review',section:'review',title:'人工复核',refresh:'reopen',
+ open:(params,push)=>openReview(push)},
+ {match:'/data-cleanup',section:'cleanup',title:'数据管理',
+ open:(params,push)=>openDataCleanup(push)},
+ // 重复文件报数据管理的身份:它是那一屏的下一步,`openManage('cleanup')` 仍
+ // 应该开数据管理本身,靠的是 /data-cleanup 在表里排在前面。
+ {match:'/duplicates',section:'cleanup',title:'重复文件',refresh:'reopen',
+ open:(params,push)=>openDuplicates(push)},
+ // /resource-sync 是数据管理页上的一个锚点,没有自己的管理身份。
+ {match:'/resource-sync',title:'数据管理',open:(params,push)=>openResourceSync(push)},
+ {match:'/quality-goals',section:'quality',title:'高清版',refresh:'reopen',
+ open:(params,push)=>openQualityGoals(push)},
+ {match:'/follow',nav:'follow',title:'关注',refresh:'skip',
+ open:(params,push)=>openFollow(push),reload:()=>openFollow(false)},
+ {match:'/follow-manage',section:'follow',title:'关注管理',refresh:'skip',
+ open:(params,push)=>openFollowManage(push)},
+ {match:'/immerse',nav:'immerse',title:'沉浸模式',
+ open:(params,push)=>openTok(immerseStartId(),push)},
+];
+/* 登记一条新路由。ADR-0022 的迁移是逐屏搬到 `frontend/`:搬走的那一屏在自己的
+ 入口里登记,不必回来改这张表。挂在 window 上是因为 app.js 是入口模块,别的
+ bundle 没法 import 它。
+ 插在表尾,所以新路由要么是一条新路径,要么比现有条目更具体。 */
+const registerRoute=spec=>{ROUTES.push(spec);return spec};
+window.peachRegisterRoute=registerRoute;
+
const pageSkeletonHtml=(label,{cards=false,className='',variant=''}={})=>
skeletonHtml(label,{variant:variant||(cards?'cards':'panel'),className});
const followSkeletonHtml=(label='正在读取关注内容')=>`<div class="follow">
@@ -142,8 +224,10 @@ function javTitleHtml(it,value=it?.name){
(管理页不全宽)靠它切换,不用每个渲染函数自己记得加类。
调用方有传 path 也有传 href 的,这里统一归一成 pathname。 */
const syncPageTitle=path=>{
- document.title=pageTitle(path);
- document.body.dataset.surface=new URL(path,location.origin).pathname;
+ const url=new URL(path,location.origin);
+ const label=routeLabel(ROUTES,decodeURIComponent(url.pathname));
+ document.title=label?`${label} · Peach`:'Peach · 蜜桃';
+ document.body.dataset.surface=url.pathname;
paintNav();
};
/* 导航激活态必须在每次路由变化时重算:抽屉与窄栏的按钮是 buildBars 时
@@ -5293,16 +5377,12 @@ function renderSidebarOrderSetting(){
};
});
}
+/* 当前在哪个管理区。路由表里的 `section` 是唯一判据;垃圾文件那一屏没有自己的
+ 身份,它是数据管理的一部分,`state.state` 才是判据(`/junk-files` 从启动那一刻
+ 起 state 就是 `ads`,首页带 `?state=ads` 也一样)。 */
function manageSection(){
- const path=decodeURIComponent(location.pathname);
- if(path==='/stats')return 'stats';
- if(path==='/taste')return 'taste';
- if(path==='/review')return 'review';
- if(path==='/trash')return 'trash';
- if(path==='/data-cleanup'||path==='/duplicates'||path==='/junk-files'||state.state==='ads')return 'cleanup';
- if(path==='/quality-goals')return 'quality';
- if(path==='/follow-manage')return 'follow';
- return '';
+ const hit=matchRoute(ROUTES,decodeURIComponent(location.pathname));
+ return hit?.route.section||(state.state==='ads'?'cleanup':'');
}
function buildManageBar(){
const current=manageSection(),bar=$('#managebar');
@@ -5376,17 +5456,14 @@ function paintListTitle(){
const label=!manageSection()&&isCatalogPath(path)?STATE_LABELS[state.state]||'':'';
el.hidden=!label;if(label)el.textContent=label;
}
+/* 进某个管理区。入口就是路由表里 `section` 等于它的第一条,所以这里不再有一份
+ 「section → 打开哪个函数」的副本。 */
function openManage(section='stats'){
- if(section==='stats'){openStats();return}
- if(section==='taste'){openTaste();return}
- if(section==='review'){openReview();return}
- if(section==='cleanup'){openDataCleanup();return}
- // 旧直达 URL 继续保留;它们共享同一个「数据管理」导航身份。
- if(section==='dupes'){openDuplicates();return}
- if(section==='quality'){openQualityGoals();return}
- if(section==='follow'){openFollowManage();return}
- state.orient='';state.state=section==='trash'?'trash':'ads';
- route(section==='trash'?'/trash':junkPath());
+ const target=ROUTES.find(spec=>spec.section===section);
+ if(target){target.open({},true);return}
+ /* 认不出的 section 一律落到垃圾文件:统计页那颗「查看垃圾文件」传的就是 `ads`,
+ 而垃圾文件是目录页的一个筛选态,没有自己的 section。 */
+ state.orient='';state.state='ads';route(junkPath());
showHomeSurfaces();buildEdge();buildBars();load(true);
}
/* JAV 模式。只有带番号的作品才有官方封套,所以版式切换只在这个语境里出现——
@@ -5448,32 +5525,28 @@ async function reloadCurrentSurface(){
await updateEntityCollection(kind,name,parseEntityFilters(location.search),false);
return;
}
- const path=decodeURIComponent(location.pathname);
- if(path==='/performers'||path==='/creators'||path==='/tags'){
- await openIndex(path.slice(1),$('#iq')?.value.trim()||'',false);
- return;
- }
- if(path==='/follow'){await openFollow(false);return}
+ const hit=matchRoute(ROUTES,decodeURIComponent(location.pathname));
+ if(hit?.route.reload){await hit.route.reload();return}
await load(true);
}
function navOn(k){
const path=decodeURIComponent(location.pathname);
+ const nav=matchRoute(ROUTES,path)?.route.nav||'';
const directSection=DIRECT_MANAGE_NAV[k];
if(directSection)return manageSection()===directSection;
if(k==='manage'){
const current=manageSection();
return !!current&&!orderedEdgeIcons().some(([key])=>DIRECT_MANAGE_NAV[key]===current);
}
- if(k==='performers'||k==='tags')return path==='/'+k;
- if(k==='immerse')return path==='/immerse';
- if(k==='playlists')return path==='/playlists'||path.startsWith('/playlists/');
- if(k==='follow')return path==='/follow';
+ // JAV 和竖屏不是路径,是内存里的筛选开关,所以这两条只能问 state。
if(k==='jav')return javActive();
if(k==='shorts')return state.orient==='竖屏';
// 首页只在真的停在首页列表上时亮:管理区、索引页、实体页都不算,
// 否则它会和当前所在的入口同时高亮。
if(k==='')return path==='/'&&!manageSection()&&!state.state&&!javActive()&&state.orient!=='竖屏';
- if(STATE_ROUTES[k])return path===STATE_ROUTES[k]&&state.orient!=='竖屏';
+ // 目录页的四个筛选态共用一屏,竖屏是压在它们之上的另一层筛选。
+ if(STATE_ROUTES[k])return nav===k&&state.orient!=='竖屏';
+ if(nav)return nav===k;
return path==='/'&&state.state===k&&state.orient!=='竖屏';
}
/* 窄栏与抽屉共用同一套跳转。两边曾各写一份分支,抽屉那份漏了追更和播放列表,
@@ -5481,13 +5554,12 @@ function navOn(k){
function navTo(k){
closeDrawerAfterNav(); // 点了就收起抽屉,且短暂禁止悬停把它立刻弹回
if(DIRECT_MANAGE_NAV[k]){openManage(DIRECT_MANAGE_NAV[k]);return}
- if(k==='immerse'){openTok();return}
- if(k==='playlists'){openPlaylists();return}
- if(k==='follow'){openFollow();return}
if(k==='manage'){openManage();return}
if(k==='jav'){toggleJavMode();return}
if(k===''){openHome();return}
- if(k==='performers'||k==='tags'){setSelectMode(false,true);openIndex(k);return}
+ // 有自己路径的入口(追更、播放列表、沉浸模式、索引页)从路由表进。
+ const target=ROUTES.find(spec=>spec.nav===k&&!STATE_ROUTES[k]);
+ if(target){target.open({},true);return}
if(k==='shorts'){state.orient='竖屏';state.state=''}else{state.orient='';state.state=k}
route(homePath());
showHomeSurfaces();
@@ -6378,6 +6450,9 @@ async function openTok(startId,push=true){
}
async function tokShow(dir){
const it=tokList[tokIdx];if(!it||tokSwitching)return;
+ /* 当前这一条也过一遍 route():竖划十条之后刷新页面,落回来的该是同一条片子,
+ 而不是重新抽一批。用 replace——每划一下都往历史里塞一条,后退键就废了。 */
+ route('/immerse?id='+it.id,true);
tokSwitching=true;setTokLoading(true,dir?'切换中…':'加载中…',it);
try{
const full=await api('/api/item?id='+it.id);
@@ -6671,13 +6746,12 @@ async function refreshAll(automatic=false){
if(automatic&&(document.hidden||!isCatalogPath(decodeURIComponent(location.pathname))||
!$('#stage').hidden||!$('#tok').hidden||selectMode||selected.size||document.activeElement===$('#q')))return false;
if(!$('#stats').hidden){
- if(location.pathname==='/review'){await openReview(false);return}
- if(location.pathname==='/taste'){await openTaste(false);return}
- if(location.pathname==='/duplicates'){await openDuplicates(false);return}
- if(location.pathname==='/quality-goals'){await openQualityGoals(false);return}
- if(location.pathname==='/playlists'){await openPlaylists(false);return}
- /* 追更页不参与换批:重画要重新取数,联网检查只能由自己的明确按钮触发。 */
- if(location.pathname==='/follow'||location.pathname==='/follow-manage')return;
+ /* 管理区的换批行为写在路由表的 `refresh` 上:`reopen` 重开自己,
+ `skip` 不参与(追更页重画要联网,只能由它自己的按钮触发),
+ 没写的(统计、数据管理、资源同步)落到统计页。 */
+ const hit=matchRoute(ROUTES,decodeURIComponent(location.pathname));
+ if(hit?.route.refresh==='skip')return;
+ if(hit?.route.refresh==='reopen'){await hit.route.open(hit.params,false);return}
await openStats(false);return
}
if(!$('#index').hidden){return}
@@ -6739,63 +6813,69 @@ function wireDrag(el){
function wireAllDrag(){['#tagbar','#srow','#nrow'].forEach(s=>wireDrag($(s)));
document.querySelectorAll('.tier').forEach(wireDrag)}
+/* 目录页(首页 + 四个筛选态):筛选全部从 URL 读,路径只决定初始筛选态。
+ `enteringHome` 判的是「从别处回到首页」:顶部三层有 30 秒会话缓存,不作废的话
+ 回到首页看到的还是上一次那批人。判据是 `lastRoutePath`,所以 `restoreRoute`
+ 要等派发完再更新它。 */
+function openCatalog(path){
+ const params=new URLSearchParams(location.search);
+ const enteringHome=path==='/'&&lastRoutePath!=='/';
+ if(enteringHome){barsDataCache=null;barsDataPromise=null}
+ if(path==='/junk-files'){
+ junkKind=cleanJunkKind(params.get('type')||'');
+ junkView=params.get('view')==='dismissed'?'dismissed':'pending';
+ }
+ state={...state,loc:params.get('loc')||'local,115',creator:params.get('creator')||'',studio:params.get('studio')||'',
+ tag:cleanTagFilter(params.get('tag')),tag_match:params.get('tag_match')==='any'?'any':'all',len:params.get('len')||'',
+ dur_min:params.get('dur_min')||'',dur_max:params.get('dur_max')||'',orient:params.get('orient')||'',
+ state:ROUTE_STATES[path]||params.get('state')||'',sort:cleanSort(params.get('sort')),
+ seed:params.get('seed')||(enteringHome?rollSeed():state.seed||rollSeed()),q:params.get('q')||'',jav:params.get('jav')||''};
+ $('#q').value=state.q;buildEdge();buildBars();load(true);
+}
+/* 回收站。它和目录页共用同一张网格,只是筛选被钉死成 `trash`。 */
+function openTrash(push){
+ if(push)route('/trash');
+ state={...state,creator:'',studio:'',tag:'',orient:'',state:'trash',q:''};$('#q').value='';
+ showHomeSurfaces();buildEdge();buildBars();load(true);
+}
+/* 索引页(女优/创作者/标签)三条路由共用。
+ `push=true` 是从导航点进来:退出选择模式、不带搜索词从头开始。
+ `push=false` 是地址栏已经在这一屏:视图状态从 URL 读。
+ `q` 显式传入时优先——批量操作后的就地重取要保留搜索框里已经打好的词。 */
+function indexQuery(){return $('#iq')?.value.trim()||''}
+function openIndexRoute(kind,push,q=null){
+ if(push){setSelectMode(false,true);return openIndex(kind)}
+ const params=new URLSearchParams(location.search);
+ if(kind==='tags'){
+ tagIndexScope=params.get('scope')==='online'?'online':'local';
+ tagIndexMode=params.get('view')==='cloud'?'cloud':'alphabet';
+ const category=params.get('category')||'all';
+ const categories=tagIndexScope==='online'?ONLINE_TAG_CATEGORIES:TAG_CATEGORIES;
+ tagIndexCategory=categories.some(([key])=>key===category)?category:'all';
+ }
+ return openIndex(kind,q??(params.get('q')||''),false);
+}
+/* 沉浸模式当前这一条写在 `?id=`(见 tokShow),刷新和后退都该回到同一条片子。 */
+function immerseStartId(){
+ const id=new URLSearchParams(location.search).get('id');
+ return /^\d+$/.test(id||'')?Number(id):undefined;
+}
+
async function restoreRoute(){
surfaceEpoch++;
syncPageTitle(location.href);
- const path=decodeURIComponent(location.pathname),parts=path.split('/').filter(Boolean);
- const previousPath=lastRoutePath;lastRoutePath=path;
+ const path=decodeURIComponent(location.pathname);
if(path==='/'&&new URLSearchParams(location.search).get('state')==='ads'){
route(junkPath(),true);await restoreRoute();return;
}
- if(isCatalogPath(path)){
- const params=new URLSearchParams(location.search);
- const enteringHome=path==='/'&&previousPath!=='/';
- if(enteringHome){barsDataCache=null;barsDataPromise=null}
- if(path==='/junk-files'){
- junkKind=cleanJunkKind(params.get('type')||'');
- junkView=params.get('view')==='dismissed'?'dismissed':'pending';
- }
- state={...state,loc:params.get('loc')||'local,115',creator:params.get('creator')||'',studio:params.get('studio')||'',
- tag:cleanTagFilter(params.get('tag')),tag_match:params.get('tag_match')==='any'?'any':'all',len:params.get('len')||'',
- dur_min:params.get('dur_min')||'',dur_max:params.get('dur_max')||'',orient:params.get('orient')||'',
- state:ROUTE_STATES[path]||params.get('state')||'',sort:cleanSort(params.get('sort')),
- seed:params.get('seed')||(enteringHome?rollSeed():state.seed||rollSeed()),q:params.get('q')||'',jav:params.get('jav')||''};
- $('#q').value=state.q;buildEdge();buildBars();load(true);return;
- }
- if(path==='/trash'){
- state={...state,creator:'',studio:'',tag:'',orient:'',state:'trash',q:''};$('#q').value='';
- buildEdge();buildBars();load(true);return;
- }
- if(path==='/playlists'){await openPlaylists(false);return}
- if(parts[0]==='playlists'&&/^\d+$/.test(parts[1]||'')&&/^\d+$/.test(parts[2]||'')){await openPlaylist(+parts[1],+parts[2],false);return}
- if(parts[0]==='mix'&&/^\d+$/.test(parts[1]||'')&&/^\d+$/.test(parts[2]||'')){await openMix(+parts[1],+parts[2],false);return}
- if(parts[0]==='parts'&&/^\d+$/.test(parts[1]||'')&&/^\d+$/.test(parts[2]||'')){await openParts(+parts[1],+parts[2],false);return}
- if(parts[0]==='editions'&&/^\d+$/.test(parts[1]||'')&&/^\d+$/.test(parts[2]||'')){await openEditions(+parts[1],+parts[2],false);return}
- if(parts[0]==='item'&&/^\d+$/.test(parts[1]||'')){await openItem(+parts[1],false);return}
- if(parts[0]==='follow'&&parts[1]==='item'&&/^\d+$/.test(parts[2]||'')){
- await openFollow(false,true);await openFollowDetail(+parts[2],false);return}
- const entityKind=ROUTE_ENTITIES[parts[0]];
- if(entityKind&&parts.length>=2){await openEntity(entityKind,parts.slice(1).join('/'),false);return}
- if(path==='/performers'||path==='/creators'||path==='/tags'){
- const params=new URLSearchParams(location.search);
- if(path==='/tags'){
- tagIndexScope=params.get('scope')==='online'?'online':'local';
- tagIndexMode=params.get('view')==='cloud'?'cloud':'alphabet';
- const category=params.get('category')||'all';
- const categories=tagIndexScope==='online'?ONLINE_TAG_CATEGORIES:TAG_CATEGORIES;
- tagIndexCategory=categories.some(([key])=>key===category)?category:'all'}
- await openIndex(path.slice(1),params.get('q')||'',false);return}
- if(path==='/stats'){await openStats(false);return}
- if(path==='/taste'){await openTaste(false);return}
- if(path==='/review'){await openReview(false);return}
- if(path==='/data-cleanup'){await openDataCleanup(false);return}
- if(path==='/duplicates'){await openDuplicates(false);return}
- if(path==='/resource-sync'){await openResourceSync(false);return}
- if(path==='/quality-goals'){await openQualityGoals(false);return}
- if(path==='/follow'){await openFollow(false);return}
- if(path==='/follow-manage'){await openFollowManage(false);return}
- if(path==='/immerse'){await openTok(undefined,false);return}
- showHomeSurfaces();disposeStage(false);
+ /* 唯一的派发点:路径匹配哪条路由,就把那一屏打开。`push=false`——地址栏本来
+ 就是它,再 `route()` 一次会往历史里塞一条重复记录。
+ `lastRoutePath` 等派发完再更新:目录页要拿它判断是不是刚从别处回到首页。 */
+ const hit=matchRoute(ROUTES,path);
+ try{
+ if(hit)await hit.route.open(hit.params,false);
+ else{showHomeSurfaces();disposeStage(false)}
+ }finally{lastRoutePath=path}
}
window.addEventListener('popstate',restoreRoute);
buildEdge();
diff --git a/web/js/core.js b/web/js/core.js
index afdae0130..7d8da5883 100644
--- a/web/js/core.js
+++ b/web/js/core.js
@@ -43,16 +43,6 @@ const mapLimit=async(items,limit,run)=>{
await Promise.all(Array.from({length:workers},worker));
return results;
};
-const pageTitle=path=>{
- const url=new URL(path,location.origin),parts=decodeURIComponent(url.pathname).split('/').filter(Boolean);
- const fixed={stats:'统计',taste:'口味',review:'人工复核','data-cleanup':'数据管理',duplicates:'重复文件','quality-goals':'高清版',
- follow:'关注','follow-manage':'关注管理',playlists:'播放列表',performers:'女优',studios:'厂牌',
- creators:'创作者',series:'系列',tags:'标签',unseen:'没看过','watch-later':'稍后看',flagged:'已标记',
- immerse:'沉浸模式',mix:'Mix',item:'作品','resource-sync':'数据管理','junk-files':'垃圾文件'};
- const label=parts.length>1&&['performers','studios','creators','series'].includes(parts[0])
- ? parts.slice(1).join('/') : fixed[parts[0]];
- return label?`${label} · Peach`:'Peach · 蜜桃';
-};
const STATE_ROUTES={fresh:'/unseen',later:'/watch-later',flagged:'/flagged',ads:'/junk-files'};
const ROUTE_STATES=Object.fromEntries(Object.entries(STATE_ROUTES).map(([state,path])=>[path,state]));
const STATE_LABELS={fresh:'没看过',later:'稍后看',flagged:'已标记',ads:'垃圾文件'};
@@ -115,7 +105,6 @@ export {
api,
isAbort,
mapLimit,
- pageTitle,
STATE_ROUTES,
ROUTE_STATES,
STATE_LABELS,
diff --git a/web/js/routes.js b/web/js/routes.js
new file mode 100644
index 000000000..7d7ee31b7
--- /dev/null
+++ b/web/js/routes.js
@@ -0,0 +1,62 @@
+/* 路由匹配:路径字符串进、参数出。不碰 DOM,也不认识任何一个页面函数。
+
+ 以前「这个路径是哪一屏」这件事在 app.js 里写了七遍:`restoreRoute()` 一条
+ 二十五分支的 if 链,`navTo`/`navOn`/`openManage`/`manageSection`/
+ `reloadCurrentSurface`/`refreshAll` 各自再抄一份自己关心的那几条。加一屏要改
+ 七处,漏一处的症状各不相同:URL 能进但侧栏不亮、点进去了但换一批把你扔回统计页、
+ 批量操作后回到首页而不是刚才那一屏。真实踩过的就有抽屉漏了追更和播放列表那次。
+
+ 现在只有一张 ROUTES 表(在 app.js 里,因为它要引用各个 `open*`),匹配与取参
+ 这段纯逻辑放在这里,可以单独读、单独测。
+
+ `match` 的写法只有三种,故意不上正则——路由是给人读的清单,不是模式语言:
+
+ - `'/stats'`:精确路径。
+ - `'/item/:id'`:`:name` 吃掉一段,且只吃数字。原来每条动态路由都自己写
+ `/^\d+$/.test(parts[1]||'')`,忘写的那条会把 `/item/abc` 当合法 id 送进
+ `+parts[1]` 变成 `NaN`。
+ - `'/performers/:name*'`:`:name*` 吃掉剩下的全部段,至少一段。女优名字里有
+ 斜杠,所以实体页那条必须是「剩下全部」,不是「下一段」。 */
+
+const PARAM = /^:([A-Za-z_]\w*)(\*)?$/;
+
+/* 匹配成功返回参数对象(可能是空对象,它仍然是真值),失败返回 null。 */
+export function matchPath(pattern, path) {
+ const want = String(pattern).split('/').filter(Boolean);
+ const got = String(path).split('/').filter(Boolean);
+ const params = {};
+ for (let i = 0; i < want.length; i += 1) {
+ const named = PARAM.exec(want[i]);
+ if (!named) {
+ if (want[i] !== got[i]) return null;
+ continue;
+ }
+ const [, name, greedy] = named;
+ if (greedy) {
+ const tail = got.slice(i).join('/');
+ return tail ? { ...params, [name]: tail } : null;
+ }
+ if (!/^\d+$/.test(got[i] || '')) return null;
+ params[name] = Number(got[i]);
+ }
+ return got.length === want.length ? params : null;
+}
+
+/* 先登记先匹配。表里的顺序即优先级,所以精确路径写在同前缀的动态路径前面。 */
+export function matchRoute(routes, path) {
+ for (const route of routes) {
+ const params = matchPath(route.match, path);
+ if (params) return { route, params };
+ }
+ return null;
+}
+
+/* document.title 用的标签。`title` 可以是字符串,也可以是拿参数算的函数——
+ 实体页的标题就是路径里那个名字本身。没有 title 的路由返回空串,由调用方
+ 决定兜底文案。 */
+export function routeLabel(routes, path) {
+ const hit = matchRoute(routes, path);
+ if (!hit) return '';
+ const { title } = hit.route;
+ return String((typeof title === 'function' ? title(hit.params) : title) || '');
+}