Peach: Local-first video metadata scraper and media manager.
fix(web): 由路由树打开详情并恢复历史条目的背景页
longmeidao28ae17e91905
diff --git a/frontend/src/history/index.ts b/frontend/src/history/index.tsindex 387f9e753..6d04886af 100644--- a/frontend/src/history/index.ts+++ b/frontend/src/history/index.ts@@ -9,25 +9,22 @@* 监听者,而且要有监听者才挂 `popstate`:这里一建好就由本模块接上,再分发给各个订阅者,所以页面* 一加载就在数后退与前进,不等谁来订阅。*- * 每一次历史变化(壳写的、React 子树写的、后退前进)都领一个递增的序号 `seq`。壳写地址走- * `shellNavigate`,那一次的序号当场认领:壳写完地址自己打开那一屏,不再派发。后退前进与 React 子树- * 写的那几次留给 `<Router>`,由它在渲染到那个序号时报给 `routeSeen`,再派发给壳(`startRouting` 交进来的- * `restoreRoute`)。判据用序号不用地址:同一条目重放的 `popstate` 地址不变,壳照样要重开那一屏。- * 派发带上来由(`RouteOrigin`):启动那一次是 `'boot'`,之后都是 `'history'`。- *- * 没人认领的那几次另领一个开次代次(`openEpoch`):每一次都会派发、都要把那一页重开一遍,认领的写地址- * (壳写完自己打开,或页内 replace 写参数)不领。代次在通知订阅者之前就定了,路由根同步提交那一次渲染里- * 读到的已经是新代次,页面按它挂 key,一次打开只挂一次。 */+ * 每一次历史变化(壳写的、React 子树写的、后退前进)都领一个递增的序号 `seq`。壳写地址走 `shellNavigate`,+ * 那一次当场认领(`claimed`):页面元素保持代次,覆盖元素接走这一次的打开请求。后退前进、React+ * 子树写的与壳经 `peachHistory` 直接写的那几次没人认领,另领一个开次代次(`openEpoch`):每一次都要把那一页+ * 按地址重开一遍。代次在通知订阅者之前就定了,路由根同步提交那一次渲染里读到的已经是新代次,页面按它挂 key,+ * 一次打开只挂一次。判据用序号与代次不用地址:同一条目重放的 `popstate` 地址不变,那一页照样要重开。 */import { UNSAFE_createBrowserHistory, type Location, type NavigationType, type Navigator, type To } from 'react-router';-import { isOverlayPath, overlayState, type OverlayKind } from './overlay';+import { backgroundOf, isOverlayPath, overlayState, type BackgroundLocation, type OverlayKind } from './overlay';-/** 一次历史变化:动作、变化之后的地址、它领到的序号,和到这一次为止的开次代次。 */+/** 一次历史变化:动作、变化之后的地址、它领到的序号、到这一次为止的开次代次,和这一次是不是壳认领写的。 */export interface Navigation {action: NavigationType;location: Location;seq: number;openEpoch: number;+ claimed: boolean;}export type NavigationListener = (navigation: Navigation) => void;@@ -41,23 +38,18 @@ export interface PeachHistory extends Navigator {const browser = UNSAFE_createBrowserHistory({ v5Compat: true });let seq = 0;let openEpoch = 0;-let current: Navigation = { action: browser.action, location: browser.location, seq, openEpoch };+let current: Navigation = { action: browser.action, location: browser.location, seq, openEpoch, claimed: true };const listeners = new Set<NavigationListener>();-/* 已经派发过、或不该派发的最大序号。`claiming` 只在 `shellNavigate` 写地址那一下为真。 */-let claimed = 0;+/* `claiming` 只在 `shellNavigate` 写地址那一下为真。 */let claiming = false;-let dispatcher: RouteDispatcher | null = null;--/** 派发的来由:`'boot'` 是页面加载后的第一次(刷新、新标签页、深链都算),`'history'` 是之后的后退前进与- * React 子树写的地址。`usr` 跨刷新存活,壳要靠它分清条目里记的背景能不能读。 */-export type RouteOrigin = 'boot' | 'history';-export type RouteDispatcher = (origin: RouteOrigin) => Promise<void> | void;+/* 还停在页面加载时的那一条上:之后只经 replace 改写过(清理启动地址、页内写参数),没 push、没后退前进。 */+let onBootEntry = true;browser.listen(({ action, location }) => {seq += 1;- if (claiming) claimed = seq;- else openEpoch += 1;- current = { action, location, seq, openEpoch };+ if (!claiming) openEpoch += 1;+ if (action !== 'REPLACE') onBootEntry = false;+ current = { action, location, seq, openEpoch, claimed: claiming };for (const listener of [...listeners]) listener(current);});@@ -79,21 +71,16 @@ export interface ShellNavigateOptions {replace?: boolean;/** 新条目的 `usr` 状态。清理地址时传 `peachHistory.navigation.location.state`,原样保住当前那一份。 */state?: unknown;- /** 当场认领这一次(缺省)。传 `false` 时这一次像后退前进一样派发、领开次代次:壳要换到一页、又要由派发器- * 打开它(`actions.navigate`)。 */- claim?: boolean;}-/** 壳写地址:push 或 replace 一条。+/** 壳写地址:push 或 replace 一条,当场认领。** 路径先按当前地址解析成绝对的:壳传进来的有相对路径、有只带查询串的,也有整条 href,* `history.pushState` 本来就是这样解析的;React Router 的 `To` 只认路径,`#x` 这种会丢掉查询串。 */-export function shellNavigate(- path: string | URL, { replace = false, state, claim = true }: ShellNavigateOptions = {},-): void {+export function shellNavigate(path: string | URL, { replace = false, state }: ShellNavigateOptions = {}): void {const url = new URL(path, window.location.href);const to: To = `${url.pathname}${url.search}${url.hash}`;- claiming = claim;+ claiming = true;try {if (replace) browser.replace(to, state);else browser.push(to, state);@@ -102,28 +89,13 @@ export function shellNavigate(}}-let begin: () => void = () => {};-/** 壳开始路由的那一刻兑现。按匹配打开的页面元素等它再开页:壳启动时派发的同步那一段(标题、侧栏、- * 教程状态)先跑完,元素的开页排在它后面;之后每次挂上,开页都排进挂上那一轮的微任务里。 */-export const routingStarted: Promise<void> = new Promise((resolve) => { begin = resolve });--/** 壳启动时派发第一次,此后的派发交给 `routeSeen`。- *- * 到这一刻为止的历史变化都算启动这一次的:`<Router>` 先挂上的话,它挂上时报的那个序号已经过去,- * 不会再派发;后挂上的话,它读到的初值就是这里认领的序号。只调一次,这一次的来由是 `'boot'`。 */-export function startRouting(dispatch: RouteDispatcher): Promise<void> {- dispatcher = dispatch;- claimed = seq;- begin();- return Promise.resolve(dispatch('boot'));-}+/** 当前条目是不是页面加载时的那一条(刷新、新标签页、深链)。 */+export const bootEntry = (): boolean => onBootEntry;-/** `<Router>` 渲染到第 `seen` 次历史变化时报到这里:壳还没开始路由、或这一次已经认领过,就不派发。- * 派发出去的来由是 `'history'`。 */-export function routeSeen(seen: number): void {- if (!dispatcher || seen <= claimed) return;- claimed = seen;- void dispatcher('history');+/** 页面组按它匹配的背景:当前条目在 `usr` 里记的那一页。启动那一条不读(ADR-0031「详情条目记下压在哪一页+ * 上」):`usr` 跨刷新仍在,下面那一页却从没画过,刷新、新标签页与深链落在详情上一律当作没有背景。 */+export function navigationBackground(): BackgroundLocation | null {+ return onBootEntry ? null : backgroundOf(current.location.state);}/** 原地改写当前详情条目压着的详情种类:作品详情取数后转成关注详情时地址照旧是 `/item/:id`,内容换了。@@ -136,8 +108,8 @@ export function retagOverlay(overlay: OverlayKind): void {export {adoptOverlayState, backgroundOf, clearOverlayBackground, holdOverlayBackground, isOverlayPath, OVERLAY_PATHS,- overlayState, takeOverlayReturn,- type BackgroundLocation, type OverlayKind, type OverlayState,+ overlayState, overlayTarget, takeOverlayReturn,+ type BackgroundLocation, type OverlayKind, type OverlayPath, type OverlayState, type OverlayTarget,} from './overlay';export { ROUTE_META, routeMetaOf, type RouteMeta } from './route-meta';export {diff --git a/frontend/src/history/overlay.ts b/frontend/src/history/overlay.tsindex 1039a5322..5787bee9b 100644--- a/frontend/src/history/overlay.ts+++ b/frontend/src/history/overlay.ts@@ -5,9 +5,10 @@* 队列地址要等取完数才 push,背景仍是决定那一刻的,不是 push 那一刻的地址。详情之间换条沿用上一条的* 背景、不嵌套;只存路径与查询串,不存 DOM、对象或条目 `key`(刷新后对不上任何活条目)。*- * 读:后退前进落到详情条目上时,壳调 `adoptOverlayState` 接上这一条记的背景,打开详情的那一处再用- * `takeOverlayReturn` 取来处,关掉回到那一页。冷启动(刷新、新标签页、深链)不读:条目跨刷新仍带着- * `usr`,下面那页却只补画了目录网格,关掉照旧回各自的缺省来处。 */+ * 读:后退前进落到详情条目上时,路由树的覆盖元素(`react/router/pages/overlay.tsx`)调 `adoptOverlayState`+ * 接上这一条记的背景,壳打开详情的那一处再用 `takeOverlayReturn` 取来处,关掉回到那一页。冷启动(刷新、+ * 新标签页、深链)不读:条目跨刷新仍带着 `usr`,下面那页却从没画过,页面组照没有背景补画(`/item/:id` 补画+ * 目录网格),关掉回各自的缺省来处。 */import { matchPath } from 'react-router';/** 覆盖在页面上的那几种地址。不进 `isRoutedPath`:页面宿主不画它们。 */@@ -16,8 +17,35 @@ export const OVERLAY_PATHS = ['/follow/item/:id',] as const;+export type OverlayPath = typeof OVERLAY_PATHS[number];+export type OverlayKind = 'item' | 'follow';+/** 一条覆盖地址要打开的那一条:作品详情、关注详情,或四种队列里的一条(`key` 是种子或播放列表)。 */+export type OverlayTarget =+ | { kind: 'item' | 'follow'; id: number }+ | { kind: 'queue'; queue: 'mix' | 'parts' | 'editions' | 'playlist'; key: number; item: number };++const QUEUES = { '/mix/:seed/:item': 'mix', '/parts/:seed/:item': 'parts', '/editions/:seed/:item': 'editions',+ '/playlists/:playlist/:item': 'playlist' } as const;++/** 地址匹配哪一条覆盖路径;参数要全是数字,`/item/abc` 不算。 */+export function overlayMatch(pathname: string): { path: OverlayPath; target: OverlayTarget } | null {+ for (const path of OVERLAY_PATHS) {+ const match = matchPath(path, pathname);+ if (!match) continue;+ const values = Object.values(match.params);+ if (!values.every((value) => /^\d+$/.test(value ?? ''))) return null;+ const [first, second] = values.map(Number) as [number, number];+ if (path === '/item/:id' || path === '/follow/item/:id') return { path, target: { kind: path === '/item/:id' ? 'item' : 'follow', id: first } };+ return { path, target: { kind: 'queue', queue: QUEUES[path], key: first, item: second } };+ }+ return null;+}++/** 地址要打开的那一条覆盖;不是覆盖地址或参数不是数字时是 null。 */+export const overlayTarget = (pathname: string): OverlayTarget | null => overlayMatch(pathname)?.target ?? null;+export interface BackgroundLocation {pathname: string;search: string;diff --git a/frontend/src/history/route-meta.ts b/frontend/src/history/route-meta.tsindex 77d97eed8..ad1307101 100644--- a/frontend/src/history/route-meta.ts+++ b/frontend/src/history/route-meta.ts@@ -1,18 +1,19 @@-/* 路由树那一侧的路由元数据(ADR-0031「React Router 外壳阶段接管」):标题、侧栏键、管理区身份与「换一批」的- * 行为,按精确路径登记。壳的读者(标题、侧栏高亮与跳转、管理区身份、换一批)先查这里,没有再回落到壳的- * `ROUTES` 表;一条路径只在一边登记。+/* 路由元数据(ADR-0031「React Router 外壳阶段接管」):标题、侧栏键、管理区身份与「换一批」的行为,按路径登记,+ * 全站只有这一张。壳的读者(标题、侧栏高亮与跳转、管理区身份、换一批)都查这里。*- * 放在 `@peach/history` 而不随 `managed-routes.tsx` 进 React 包:壳启动时就要读(冷启动的管理区页头、- * 第一次派发的标题),那时 React 包可能还没到。路由树经 `@peach/history` 读的也是这一份。+ * 放在 `@peach/history` 而不随 `managed-routes.tsx` 进 React 包:壳启动时就要读(冷启动的管理区页头与标题),+ * 那时 React 包可能还没到。路由树经 `@peach/history` 读的也是这一份。*- * 字段同壳的 `ROUTES` 表:`title` 是 document.title 用的标签;`nav` 是侧栏 `data-nav` 的键;`section` 是管理区- * 身份,同一身份按登记顺序取第一条作入口(数据管理排在重复文件与来源和凭证前面);`refresh` 是列表栏- * 「换一批」在这一页的行为,`reopen` 重开自己、`skip` 不参与,不写则回统计页;`reload` 是批量写回之后的就地- * 重取,`reopen` 让这一页按当前地址从头重开(索引页与资料页)。+ * 字段:`title` 是 document.title 用的标签;`nav` 是侧栏 `data-nav` 的键;`section` 是管理区身份,同一身份按+ * 登记顺序取第一条作入口(数据管理排在重复文件与来源和凭证前面);`refresh` 是列表栏「换一批」在这一页的行为,+ * `reopen` 重开自己、`skip` 不参与,不写则回统计页;`reload` 是批量写回之后的就地重取,`reopen` 让这一页按当前+ * 地址从头重开(索引页与资料页)。同一个侧栏键按登记顺序取第一条作入口:播放列表页排在播放列表队列前面。*- * 资料页按模式登记(`/performers/*`,同 `ENTITY_ROUTES`),标题是地址上的名字。`routeMetaOf` 先查精确路径,- * 没有再按去掉空段之后的各段找:只剩一段查那一段的精确路径(`/performers/`),多于一段按第一段找模式,名字是- * 剩下各段连起来的那一串(读者交进来的是解码过的路径),同壳的 `matchPath`。 */+ * 资料页按模式登记(`/performers/*`,同 `ENTITY_ROUTES`),标题是地址上的名字;覆盖的六条按 `OVERLAY_PATHS` 的+ * 写法登记,参数只认数字。`routeMetaOf` 先查精确路径,再查覆盖路径,没有再按去掉空段之后的各段找:只剩一段查+ * 那一段的精确路径(`/performers/`),多于一段按第一段找模式,名字是剩下各段连起来的那一串(读者交进来的是+ * 解码过的路径,名字里的斜杠吃掉剩下全部段,空尾段不算)。 */+import { overlayMatch } from './overlay';export interface RouteMeta {readonly title?: string;@@ -56,11 +57,22 @@ export const ROUTE_META: Readonly<Record<string, RouteMeta>> = {'/flagged': { nav: 'flagged', title: '已标记' },'/junk-files': { nav: 'ads', title: '垃圾文件' },'/trash': { section: 'trash' },+ // 覆盖:详情、四种队列与关注详情。分卷与版本队列没有自己的标签。+ '/playlists/:playlist/:item': { nav: 'playlists', title: '播放列表' },+ '/mix/:seed/:item': { title: 'Mix' },+ '/parts/:seed/:item': {},+ '/editions/:seed/:item': {},+ '/item/:id': { title: '作品' },+ '/follow/item/:id': { title: '关注' },+ // 沉浸模式进页面组,不算覆盖。+ '/immerse': { nav: 'immerse', title: '沉浸模式' },};-/** 这条路径在路由树一侧登记的元数据;没登记是 `null`,由壳回落到自己的表。 */+/** 这条路径登记的元数据;没登记是 `null`。 */export function routeMetaOf(path: string): RouteMeta | null {if (Object.hasOwn(ROUTE_META, path)) return ROUTE_META[path]!;+ const overlay = overlayMatch(path);+ if (overlay) return ROUTE_META[overlay.path]!;const [segment, ...rest] = path.split('/').filter(Boolean);if (!segment) return null;if (!rest.length) return Object.hasOwn(ROUTE_META, `/${segment}`) ? ROUTE_META[`/${segment}`]! : null;diff --git a/frontend/src/islands.ts b/frontend/src/islands.tsindex f111dec30..428abad82 100644--- a/frontend/src/islands.ts+++ b/frontend/src/islands.ts@@ -171,9 +171,9 @@ export function loadGlowPicker(host: ReactBundle.GlowPickerHost): Promise<void>return glowPicker;}-/* 客户端导航(`react/router/`):React Router 接管全站那一份历史,后退前进由它派发给壳;管理区、索引页与资料页由它画- * (`openManagedRoute`)。壳启动时装载、交进自己的能力,跟侧栏共用同一次 `@peach/react` 请求;包到之前的- * 后退前进等它挂上时补派,包到之前打开的那一页等它到了再取数。包取不回来时,等着的那一页跟着失败。+/* 客户端导航(`react/router/`):React Router 接管全站那一份历史,每一页、沉浸与详情都由路由树按匹配打开;管理区、+ * 索引页与资料页由它画(`openManagedRoute`)。壳启动时装载、交进自己的能力,跟侧栏共用同一次 `@peach/react` 请求;+ * 包到之前的后退前进等它挂上时按那一刻的地址打开,包到之前打开的那一页等它到了再取数。包取不回来时,等着的那一页跟着失败。* 壳在装载之前就打开的附属面(搜索下拉、首屏骨架里的筛选条)当场发出包的请求,跟这里是同一个模块。 */let router: Promise<void> | null = null;// 装载失败由 `loadRouter` 那一份报出,等着的打开跟着它失败;这里只管提早发出请求。diff --git a/frontend/src/react/bundle.d.ts b/frontend/src/react/bundle.d.tsindex 56914d942..e0c4311a4 100644--- a/frontend/src/react/bundle.d.ts+++ b/frontend/src/react/bundle.d.ts@@ -522,8 +522,8 @@ export declare function configureGlowPicker(host: GlowPickerHost): void;export type { ManagedOpenProps, ManagedPath, ShellActions } from './router/shell-actions';-/** 挂上客户端导航(`router/router.tsx`):React Router 接管 `@peach/history`,后退前进与 React 子树里的- * `navigate` 由它派发给壳;管理区、索引页与资料页由它画,经 `actions` 回到壳。重复调用是空操作。 */+/** 挂上客户端导航(`router/router.tsx`):React Router 接管 `@peach/history`,每一页、沉浸与详情都由它按匹配打开;+ * 管理区、索引页与资料页由它画,经 `actions` 回到壳。重复调用是空操作。 */export declare function configureRouter(actions: ShellActions): void;/** 路由树那几页的首屏取数(`@peach/history` 的 `openManagedRoute` 经 `connectManagedRoutes` 调它)。 */diff --git a/frontend/src/react/router/managed-routes.tsx b/frontend/src/react/router/managed-routes.tsxindex 761a7c07c..3c8e48415 100644--- a/frontend/src/react/router/managed-routes.tsx+++ b/frontend/src/react/router/managed-routes.tsx@@ -1,5 +1,5 @@-/* 由路由画的那几页、页面里的附属面与常驻面:登记键到首屏取数与画法的对照表,七张;另有一张旧直达地址的- * 改写表 `REDIRECT_ROUTES`。+/* 由路由画的那几页、页面里的附属面与常驻面:登记键到首屏取数与画法的对照表,七张;另有旧直达地址的+ * 改写表 `REDIRECT_ROUTES` 和沉浸模式的 `IMMERSE_ROUTES`,只挂元素。** `MANAGED_ROUTES` 是管理区那几页(画进 `#stats`),键是精确路径,每条带页面组按匹配挂上的元素;* `BROWSE_ROUTES` 是同样画进 `#stats` 的播放列表页与关注页;`INDEX_ROUTES` 是索引页、`ENTITY_ROUTES` 是资料页(都画进 `#index`),资料页按模式登记@@ -9,7 +9,7 @@* 与附属面是壳那一整份 props;回执与换到还归壳的那几屏走 `ShellActions`。* 管理区几页之间的跳转走 `go`:落在 `MANAGED_ROUTES` 上的交给 React Router 的 `navigate`,其余交壳。另外* 四张表的页面不走 `go`:它们在页内写地址一律由壳认领(`routeIndex`、资料页与关注页的 `actions.route`、- * 目录的换筛选、垃圾队列的换分类),跨页也交壳,派发次数同壳自己打开。 */+ * 目录的换筛选、垃圾队列的换分类),跨页也交壳,打开次数同壳自己打开。 */import type { ReactElement } from 'react';import { javDisplayName, javTitleHtml } from '@peach/legacy/jav-title';@@ -65,6 +65,7 @@ import { DEFAULT_WINDOW, prefetchTaste } from '../taste/taste';import { TastePage } from '../taste/taste-page';import { CatalogMatch } from './pages/catalog';import { FollowMatch, PlaylistsMatch } from './pages/follow';+import { ImmerseMatch } from './pages/immerse';import { EntityMatch, IndexMatch } from './pages/index-entity';import { ManagedMatch, ResourceSyncRedirect } from './pages/managed';import type {@@ -202,6 +203,11 @@ export const REDIRECT_ROUTES: Readonly<Record<string, { element: ReactElement }>'/resource-sync': { element: <ResourceSyncRedirect /> },};+/** 沉浸模式:页面组按匹配挂上元素(`pages/immerse.tsx`),元素交壳打开常驻面 `immerse`,自己不画。 */+export const IMMERSE_ROUTES: Readonly<Record<string, { element: ReactElement }>> = {+ '/immerse': { element: <ImmerseMatch /> },+};+/* 两页都由元素按匹配打开(`pages/follow.tsx`)。播放列表页:首屏每次都向服务端重取(首页刚存的 Mix 进来就要看得到)。停在这一页时壳要求重读,元素经 `updateManagedRoute` 推一个新的 `revision`,页面只重取、不重挂。点开一份进舞台、翻页门槛与回执都归壳。diff --git a/frontend/src/react/router/pages/catalog.tsx b/frontend/src/react/router/pages/catalog.tsxindex 34387926b..78b2dbd4f 100644--- a/frontend/src/react/router/pages/catalog.tsx+++ b/frontend/src/react/router/pages/catalog.tsx@@ -2,26 +2,27 @@* 垃圾文件)时挂上,按地址重建目录筛选(`@peach/shell` 的 `state`),再交壳收舞台以外的事:搜索框、侧栏与顶栏、* 顶部三层和取数(`ShellActions.catalog`)。*- * 元素按页面挂 key:首页、三个筛选态与回收站画的是同一张网格,共用一个元素;垃圾文件是另一页。换筛选、后退前进与- * 壳要求重开都不重挂,元素在每一轮变化之后的微任务里按下面的次序判断做哪一件:+ * 元素按页面挂 key:首页、三个筛选态与回收站画的是同一张网格,共用一个元素;垃圾文件是另一页。没有背景的作品与+ * 队列地址(深链、刷新)也挂这个元素。换筛选、后退前进与壳要求重开都不重挂,元素在每一轮变化之后的微任务里按下面的+ * 次序判断做哪一件:+ * - 详情压在上面:条目记了背景(页面组按背景匹配)就什么都不做,下面那一页一直画着;没有背景时补画一次目录网格+ * (`ShellActions.catalog.fill`),详情下面不留一张永远在读的骨架。* - 壳要求按当前地址从头重开(`pageOpens` 加一:启动、深链详情关掉补画来处、从管理条进回收站):整页打开。* - 领了新的开次代次(后退前进、不认领的跳转):整页打开;后退前进从别处回到首页时作废顶部三层的缓存、重掷取样种子,* 在目录里换来换去沿用这一粒。地址上写了 `seed` 就用它。- * - 壳认领写了地址(换筛选、换排序、换一批、回首页):筛选已经由壳写进 `state`,只重取。- * - 详情压在上面(页面组按背景匹配):什么都不做;关掉详情回到压着的那一份地址、筛选也没变时不重取,下面那一页- * 一直画着。+ * - 壳认领写了地址(换筛选、换排序、换一批、回首页):筛选已经由壳写进 `state`,只重取;关掉详情回到压着的那一份+ * 地址、筛选也没变时不重取。这一页要是还没开过(后退落到压在别处之上的详情,挂上时就被盖着),整页打开。* `pageOpens` 还是 0 时壳没开始路由,元素只挂着。挂上那一刻按那一次历史变化认没认领分别算作后两种;路由根晚于* 壳开始路由才装上时,挂上那一刻算第一种。*- * 整页打开先收舞台。`?state=ads` 落在首页上时不打开,改写成垃圾文件的地址(不加条目),由垃圾文件那一页的元素接着- * 打开。卸载时去处不是目录、详情、沉浸或资料页,就收起 `#grid`、首页新作行与处理横幅:那三处离开目录也留着它们。- * 判断、改写与收起都排进微任务:路由根在历史变化的同一次调用里同步提交,派发点(`RouteDispatch`)在同一次提交里- * 排的那个微任务先跑,壳的 `restoreRoute` 写好标题与侧栏之后,这里才动。 */+ * `?state=ads` 落在首页上时不打开,改写成垃圾文件的地址(不加条目),由垃圾文件那一页的元素接着打开。卸载时去处+ * 不是目录、详情、沉浸或资料页,就收起 `#grid`、首页新作行与处理横幅:那三处离开目录也留着它们。判断、改写与收起+ * 都排进微任务:路由根在历史变化的同一次调用里同步提交,壳订阅历史早于路由根,它写标题与侧栏的那一轮排在前面。 */import { useContext, useEffect, useRef, useSyncExternalStore } from 'react';import { useLocation } from 'react-router';import { appSettingsStore } from '@peach/appearance';-import { backgroundOf, isOverlayPath, peachHistory, shellNavigate } from '@peach/history';+import { isOverlayPath, navigationBackground, overlayTarget, peachHistory, shellNavigate } from '@peach/history';import { cleanTagFilter, isCatalogPath, newSeed, ROUTE_STATES } from '@peach/legacy/core';import { pageOpens, state, subscribeShell, writeShell, type CatalogFilters } from '@peach/shell';@@ -48,7 +49,8 @@ peachHistory.listen((navigation) => {/* 首页上的 `?state=ads` 改写成垃圾文件地址那一下:垃圾文件那一页的元素挂上时取走,整页打开。 */let junkRedirect = false;-/** 元素上一次处理到哪儿:序号、开次代次、重开次数,那一刻有没有详情压着、页面组画的是哪一份地址与哪一套筛选。 */+/** 元素上一次处理到哪儿:序号、开次代次、重开次数,那一刻有没有详情压着、页面组画的是哪一份地址与哪一套筛选,+ * 这一页开过没有。 */interface Seen {seq: number;epoch: number;@@ -56,16 +58,17 @@ interface Seen {covered: boolean;address: string;filters: string;+ opened: boolean;}-function seen(): Seen {+function seen(opened: boolean): Seen {const { seq, openEpoch, location } = peachHistory.navigation;const covered = isOverlayPath(location.pathname);- const shown = (covered ? backgroundOf(location.state) : null) ?? location;+ const shown = navigationBackground() ?? location;const filters = state ?? {};return {seq, epoch: openEpoch, opens: pageOpens, covered, address: `${shown.pathname}${shown.search}`,- filters: JSON.stringify(filters, Object.keys(filters).sort()),+ filters: JSON.stringify(filters, Object.keys(filters).sort()), opened,};}@@ -93,18 +96,22 @@ function filtersAt(pathname: string, search: string, entering: boolean, shell: C/** 判断这一轮做哪一件,做掉;`mark` 换成这一刻。 */function settle(mark: Seen, actions: ShellActions): void {const was = { ...mark };- const now = seen();+ const now = seen(was.opened);Object.assign(mark, now);const shell = actions.catalog;- if (!shell || now.opens === 0 || now.covered) return;+ if (!shell || now.opens === 0) return;+ if (now.covered) {+ if (!navigationBackground()) shell.fill();+ return;+ }let entering = false;if (now.opens === was.opens) {- if (now.epoch === was.epoch) {+ if (now.epoch === was.epoch && was.opened) {if (now.seq === was.seq || (was.covered && now.address === was.address && now.filters === was.filters)) return;shell.load();return;}- entering = peachHistory.navigation.action === 'POP' && last.from !== '/';+ if (now.epoch !== was.epoch) entering = peachHistory.navigation.action === 'POP' && last.from !== '/';}const { pathname, search } = peachHistory.navigation.location;if (pathname === '/' && new URLSearchParams(search).get('state') === 'ads') {@@ -116,7 +123,7 @@ function settle(mark: Seen, actions: ShellActions): void {const retitle = junkRedirect;junkRedirect = false;entering &&= pathname === '/';- actions.closeStage();+ mark.opened = true;writeShell({ state: filtersAt(pathname, search, entering, shell) });shell.open(pathname, { entering, retitle });}@@ -137,7 +144,7 @@ function CatalogOpen() {useEffect(() => {const own = live.current;own.mounted = true;- const now = seen();+ const now = seen(!isOverlayPath(peachHistory.navigation.location.pathname));/* 挂上这一刻就记下:之后壳在同一轮里要求重开(`pageOpens` 加一),微任务里比得出来。 */if (!now.covered && now.opens > 0) {if (junkRedirect || last.seq === initialSeq) now.opens = -1;@@ -165,8 +172,10 @@ function CatalogOpen() {return null;}-/** 目录六条路径共用的元素:首页、三个筛选态与回收站一个 key,垃圾文件另一个;页面组按背景匹配时取背景那一页。 */+/** 目录六条路径共用的元素:首页、三个筛选态与回收站一个 key,垃圾文件另一个;页面组按背景匹配时取背景那一页。+ * 覆盖地址的参数不是数字(`/item/abc`)时什么都不挂:那不是一条详情,下面也不补画。 */export function CatalogMatch() {const { pathname } = useLocation();+ if (isOverlayPath(pathname) && !overlayTarget(pathname)) return null;return <CatalogOpen key={pathname === '/junk-files' ? '/junk-files' : '/'} />;}diff --git a/frontend/src/react/router/pages/follow.tsx b/frontend/src/react/router/pages/follow.tsxindex 3a38c9cc3..9709dcdeb 100644--- a/frontend/src/react/router/pages/follow.tsx+++ b/frontend/src/react/router/pages/follow.tsx@@ -3,7 +3,7 @@** 什么时候打开同索引页(`usePageOpen`):挂上、领了开次代次(后退前进与不认领的跳转)、壳要求按当前地址重开* (`@peach/shell` 的 `pageOpens` 加一)各一次;`pageOpens` 还是 0 时壳没开始路由,元素只挂着;那一刻被详情压着- * (页面组按背景匹配)就不动,下面那一页早就画着。每次打开先收舞台。+ * (页面组按背景匹配)就不动,关掉详情时这一页没画着才打开。** 关注页不按代次挂 key,「回到」与「重新进入」都是同一个元素再开一次,交壳按地址读一遍筛选(`refresh`):* - 关注页还画在 `#stats` 里(资料页压过来时壳只藏起它)就铺开它,就地推筛选、取样种子与一个新的刷新代次:列表@@ -12,7 +12,8 @@* 没变时首屏命中缓存,列表不重取。* 重新进入(已在关注页再点侧栏、检查更新之后去看)由壳决定:重掷取样种子、滚动清零、回到干净的 `/follow`,再* 要求重开。关掉关注详情回列表由壳认领写地址、只推筛选,元素不动。深链直接进关注详情时页面组没有背景,不挂这个- * 元素,列表等关掉详情才打开。+ * 元素,列表等关掉详情才打开。后退前进落到压在列表上的关注详情、列表却没画着(中间去过别的页)时,交壳让出+ * `#stats`(`ShellActions.follow.ground`),不画列表。** 播放列表页每次打开都整页重开、取最新的那一份。停在这一页时壳要求重读(顶栏「换一批」)就写一个新的刷新代次* (`playlistsRevision`),元素推给画着的那一页,页面重取、不重挂。@@ -21,7 +22,7 @@* 接着用。 */import { useContext, useEffect, useRef, useSyncExternalStore } from 'react';-import { managedEntry, openManagedRoute, updateManagedRoute } from '@peach/history';+import { managedEntry, openManagedRoute, peachHistory, updateManagedRoute } from '@peach/history';import { revealSkeleton } from '@peach/legacy/ui';import { followScrollY, playlistsRevision, subscribeShell } from '@peach/shell';@@ -48,7 +49,6 @@ async function openFollow(actions: ShellActions, live: () => boolean) {const stats = statsHost();const shell = actions.follow;if (!stats || !shell) return;- actions.closeStage();if (shell.refresh()) return;const restoreY = followScrollY;actions.surfaceChanged('follow', '/follow');@@ -57,11 +57,23 @@ async function openFollow(actions: ShellActions, live: () => boolean) {if (live()) window.scrollTo(restoreY ? { top: restoreY, behavior: 'instant' } : { top: 0, behavior: 'smooth' });}+/* `#stats` 里画着、露着的是关注页。 */+function followShown(): boolean {+ const stats = statsHost();+ const entry = stats ? managedEntry(stats) : null;+ return !!stats && !stats.hidden && !!entry && entry.path === '/follow' && entry.host.isConnected;+}+/** 关注页的元素。 */export function FollowMatch() {const actions = useContext(ShellActionsContext);usePageOpen(useOpenEpoch(), (_fresh, live) => {if (actions) void openFollow(actions, live);+ }, {+ shown: followShown,+ onCovered: () => {+ if (peachHistory.navigation.location.pathname.startsWith('/follow/item/')) actions?.follow?.ground();+ },});return null;}@@ -77,7 +89,6 @@ function playlistsShown(stats: HTMLElement | null): stats is HTMLElement {async function openPlaylists(actions: ShellActions, live: () => boolean) {const stats = statsHost();if (!stats) return;- actions.closeStage();actions.surfaceChanged('playlists', '/playlists');paintManagementPlaceholder(stats, managementSkeletonHtml('/playlists', { followLayout: '', followSort: '', followDir: '' }));await openManagedRoute('/playlists', { revision: playlistsRevision }, { container: stats, isCurrent: live });@@ -97,6 +108,6 @@ export function PlaylistsMatch() {}, [revision]);usePageOpen(useOpenEpoch(), (_fresh, live) => {if (actions) void openPlaylists(actions, live);- });+ }, { shown: () => { const stats = statsHost(); return playlistsShown(stats) && !stats.hidden } });return null;}diff --git a/frontend/src/react/router/pages/immerse.tsx b/frontend/src/react/router/pages/immerse.tsxnew file mode 100644index 000000000..b71463d46--- /dev/null+++ b/frontend/src/react/router/pages/immerse.tsx@@ -0,0 +1,30 @@+/* 沉浸模式的页面元素(ADR-0031):`/immerse` 在页面组里,不算覆盖、不带背景。+ *+ * 启动与没人认领的历史变化落在 `/immerse` 上时,从地址上的 `?id=` 那一条打开沉浸(`ShellActions.openImmerse`);+ * 顶栏按钮认领写地址后也由元素打开。沉浸里每换一条由壳认领 replace 写 `?id=`,元素按开次代次挂 key,+ * 不重挂、不重开,条目数不变。+ *+ * 卸下不收沉浸:后退离开 `/immerse` 时沉浸照旧开着,由 Escape 或关闭键收起,收起时壳回首页并写一条地址。 */+import { useContext, type ReactNode } from 'react';++import { peachHistory } from '@peach/history';++import { ShellActionsContext, useOpenEpoch } from '../router';+import { useRouteOpen } from './overlay';++/* 地址上的那一条:`?id=` 是数字才算,不然从头开始。 */+function startId(): number | undefined {+ const id = new URLSearchParams(peachHistory.navigation.location.search).get('id');+ return /^\d+$/.test(id || '') ? Number(id) : undefined;+}++function ImmerseOpen() {+ const actions = useContext(ShellActionsContext);+ useRouteOpen(() => { actions?.openImmerse(startId()) }, true);+ return null;+}++/** `/immerse` 的元素。 */+export function ImmerseMatch(): ReactNode {+ return <ImmerseOpen key={useOpenEpoch()} />;+}diff --git a/frontend/src/react/router/pages/index-entity.tsx b/frontend/src/react/router/pages/index-entity.tsxindex 506258c6c..b6aa3671b 100644--- a/frontend/src/react/router/pages/index-entity.tsx+++ b/frontend/src/react/router/pages/index-entity.tsx@@ -2,7 +2,7 @@* `INDEX_ROUTES` 或 `ENTITY_ROUTES` 时挂上,从地址读出这一页是谁、带什么参数,再按地址打开那一页。** 元素自己什么都不画:页面经 `openManagedRoute` 登记进 `#index`,由 `ManagedSurface` 画。打开前先报- * `surfaceChanged` 让壳收起别的面、铺开首页那一侧,再收舞台、铺骨架,首屏取齐那一刻骨架与整页一起换掉。+ * `surfaceChanged` 让壳收起别的面、铺开首页那一侧,再铺骨架,首屏取齐那一刻骨架与整页一起换掉。** 什么时候打开:* - 索引元素按开次代次(`useOpenEpoch()`)挂 key:后退前进与不认领的跳转各领一个代次,就重挂、按地址重开;@@ -11,16 +11,16 @@* 推给画着的那一页,那一页没画着才整页重开。* - 壳要求按当前地址从头重开(`@peach/shell` 的 `pageOpens` 加一:批量写回之后、点开的正是画着的那一位)时,* 两种元素都整页重开。`pageOpens` 还是 0 时壳没开始路由,元素只挂着。- * - 挂上或领代次那一刻这一页被详情压着(页面组按背景匹配):下面那一页早就画着,不重开。+ * - 挂上或领代次那一刻这一页被详情压着(页面组按背景匹配):不重开。关掉详情时这一页要是没开过、下面也没画着+ * (后退落到压在别处之上的详情才挂上),按地址整页打开;画着就不动。** 打开排进微任务:路由根在历史变化的同一次调用里同步提交,打开时收起上一页与画首帧都要同步提交,在提交阶段里- * 做会出 flushSync 告警。派发点(`RouteDispatch`)在同一次提交里排的那个微任务先跑,壳的 `restoreRoute` 写好- * 标题与侧栏之后,这里才打开。 */+ * 做会出 flushSync 告警。壳订阅历史早于路由根,它写标题与侧栏的那一轮排在前面。 */import { useContext, useEffect, useLayoutEffect, useRef, useSyncExternalStore } from 'react';import { useLocation } from 'react-router';import { appSettingsStore } from '@peach/appearance';-import { backgroundOf, managedEntry, openManagedRoute, peachHistory, updateManagedRoute } from '@peach/history';+import { isOverlayPath, managedEntry, openManagedRoute, peachHistory, updateManagedRoute } from '@peach/history';import { ROUTE_ENTITIES } from '@peach/legacy/core';import { pageOpens, selectMode, subscribeShell, writeShell } from '@peach/shell';@@ -33,13 +33,25 @@ const readOpens = () => pageOpens;const readSelectMode = () => selectMode;const indexHost = () => document.getElementById('index');+/** `usePageOpen` 的两个可选判断。`shown()`:这一页此刻画着没有,没开过的元素在详情关掉时据此决定要不要打开。+ * `onCovered()`:挂上或领代次那一刻被详情压着时调一次。 */+export interface PageOpenOptions {+ readonly shown?: () => boolean;+ readonly onCovered?: () => void;+}+/** 这一格什么时候按地址打开。`run(fresh, live)`:`fresh` 为真是整页打开(挂上、壳要求重开),为假是同一个* 元素领了新代次;`live()` 在元素卸下或又开了一次之后回 false。关注页与播放列表页的元素也用它。 */-export function usePageOpen(epoch: number, run: (fresh: boolean, live: () => boolean) => void): void {+export function usePageOpen(+ epoch: number, run: (fresh: boolean, live: () => boolean) => void, options: PageOpenOptions = {},+): void {const opens = useSyncExternalStore(subscribeShell, readOpens);- const seen = useRef({ mounted: true, epoch: -1, opens: -1, run: 0 });- const latest = useRef(run);- useLayoutEffect(() => { latest.current = run });+ /* 每次导航都重渲染一次,详情压上来、撤下去都看得见。页面组给的是背景那一份地址,压没压着看真实地址。 */+ useLocation();+ const covered = isOverlayPath(peachHistory.navigation.location.pathname);+ const seen = useRef({ mounted: true, epoch: -1, opens: -1, run: 0, opened: false });+ const latest = useRef({ run, options });+ useLayoutEffect(() => { latest.current = { run, options } });useEffect(() => {const mark = seen.current;mark.mounted = true;@@ -49,16 +61,28 @@ export function usePageOpen(epoch: number, run: (fresh: boolean, live: () => booif (opens === 0) return;queueMicrotask(() => {const mark = seen.current;+ if (!mark.mounted) return;/* 读这一刻的 `pageOpens`:壳写地址挂上这一格、紧接着要求重开时,两边合成一次打开。 */- if (!mark.mounted || (mark.epoch === epoch && mark.opens === pageOpens)) return;- const fresh = mark.opens !== pageOpens;+ const stale = mark.epoch !== epoch || mark.opens !== pageOpens;+ let fresh = mark.opens !== pageOpens;mark.epoch = epoch;mark.opens = pageOpens;- if (backgroundOf(peachHistory.navigation.location.state)) return;+ if (isOverlayPath(peachHistory.navigation.location.pathname)) {+ if (stale) latest.current.options.onCovered?.();+ return;+ }+ if (!stale) {+ if (mark.opened || latest.current.options.shown?.()) {+ mark.opened = true;+ return;+ }+ fresh = true;+ }+ mark.opened = true;const mine = ++mark.run;- latest.current(fresh, () => mark.mounted && mark.run === mine);+ latest.current.run(fresh, () => mark.mounted && mark.run === mine);});- }, [epoch, opens]);+ }, [epoch, opens, covered]);}/* ── 索引 ── */@@ -68,7 +92,6 @@ async function openIndex(actions: ShellActions, kind: IndexPageKind, search: strif (!host) return;const path = `/${kind}` as const;actions.surfaceChanged('index', path);- actions.closeStage();const params = indexParams(kind, search);const layout = peopleLayoutOf(appSettingsStore().value.peopleLayout);paintIndexSkeleton(host, params, layout);@@ -79,13 +102,20 @@ async function openIndex(actions: ShellActions, kind: IndexPageKind, search: strif (painted && live()) actions.surfaceShown?.('index', path);}+/* `#index` 里画着、露着的是这一页索引。 */+function indexShown(path: string): boolean {+ const host = indexHost();+ const entry = host ? managedEntry(host) : null;+ return !!host && !host.hidden && !!entry && entry.path === path && entry.host.isConnected;+}+function IndexOpen({ epoch }: { epoch: number }) {const actions = useContext(ShellActionsContext);const location = useLocation();+ const kind = location.pathname.split('/').filter(Boolean)[0] as IndexPageKind;usePageOpen(epoch, (_fresh, live) => {- const kind = location.pathname.split('/').filter(Boolean)[0] as IndexPageKind;if (actions) void openIndex(actions, kind, location.search, live);- });+ }, { shown: () => indexShown(`/${kind}`) });return null;}@@ -144,7 +174,6 @@ async function openEntity(if (!host) return;const { segment, kind, name } = target;actions.surfaceChanged('entity', pathname);- actions.closeStage();await shell.loading(kind, name, live);if (!live()) return;writeShell({ entityJavLayout: false });@@ -187,7 +216,7 @@ function EntityOpen({ target }: { target: { segment: string; kind: string; name:if (!actions || !shell) return;if (!fresh && shell.refresh(target.kind, target.name, location.search)) return;void openEntity(actions, shell, target, location.pathname, location.search, live);- });+ }, { shown: () => entityShown() && !indexHost()?.hidden });return null;}diff --git a/frontend/src/react/router/pages/managed.tsx b/frontend/src/react/router/pages/managed.tsxindex e9fd7121d..995c91523 100644--- a/frontend/src/react/router/pages/managed.tsx+++ b/frontend/src/react/router/pages/managed.tsx@@ -1,24 +1,27 @@/* 管理区十一页与 `/resource-sync` 的页面元素:页面组按匹配挂上它们,挂上就打开那一页(ADR-0031「管理区页面由* 路由树按匹配打开」)。*- * 一次打开:等壳开始路由(`routingStarted`),收舞台,经 `surfaceChanged` 让壳收起别的面、铺开管理区,铺这一页的+ * 一次打开:等壳开始路由(`@peach/shell` 的 `pageOpens` 大于 0),经 `surfaceChanged` 让壳收起别的面、铺开管理区,铺这一页的* 骨架(与壳冷启动铺的是同一张,键相同就不重画),按需问一次 `/healthz`,再走 `openManagedRoute` 取齐首屏、* 在同一个任务里换成整页。首帧 props 由元素自己从地址、偏好与壳的状态算。*- * 按开次代次挂 key:派发一次就是打开一次,同一路径再打开就重挂重取;认领的写地址(复核页换分类、关注管理换页签)- * 代次不变,不重开。详情压在上面时页面组还匹配这一页:key 停在压上来之前那一次,页面不拆;经背景匹配挂上的- * (启动就落在详情上)不打开,背景页不补画。+ * 按开次代次挂 key:没人认领的历史变化一次就是打开一次,同一路径再打开就重挂重取;认领的写地址(复核页换分类、+ * 关注管理换页签)代次不变,不重开。详情压在上面时页面组还匹配这一页:key 停在压上来之前那一次,页面不拆;经背景+ * 匹配挂上的(后退落到压在这一页上的详情)先不打开,详情撤下时按那一刻的代次挂 key 打开。** 卸载时这一页还画在 `#stats` 里、壳也没藏起它,才收起;资料页、首页压过来时壳只藏起 `#stats`,页面照旧活着,* 等下一次认领表面才收。收起排进微任务:卸载发生在路由根同步提交的那一次里。 */-import { useContext, useEffect, useRef } from 'react';+import { useContext, useEffect, useRef, useSyncExternalStore } from 'react';+import { useLocation } from 'react-router';import { appSettingsStore } from '@peach/appearance';import {- isOverlayPath, managedEntry, openManagedRoute, peachHistory, releaseManagedRoute, routingStarted, shellNavigate,+ isOverlayPath, managedEntry, openManagedRoute, peachHistory, releaseManagedRoute, shellNavigate,} from '@peach/history';import { api, isAbort } from '@peach/legacy/core';-import { cameFromSetup, configurationRequestedSection, runtimeConfigurable, state, writeShell } from '@peach/shell';+import {+ cameFromSetup, configurationRequestedSection, pageOpens, runtimeConfigurable, state, subscribeShell, writeShell,+} from '@peach/shell';import { managementSkeletonHtml, paintManagementPlaceholder } from '../../../management-placeholder';import { isReviewCategory } from '../../review/review';@@ -43,6 +46,10 @@ interface Runtime {const FOLLOW_MANAGE_TABS = ['list', 'add', 'feeds', 'wants', 'source'];+const readStarted = () => pageOpens > 0;+/** 壳开始路由没有(`pageOpens` 大于 0)。 */+const useRoutingStarted = (): boolean => useSyncExternalStore(subscribeShell, readStarted);+/* `/resource-sync` 改写过来的那一次数据管理页,打开后滚到资源同步那一块;取一次就清。 */let resourceSyncPending = false;@@ -117,7 +124,6 @@ const SCROLL_WHEN_CURRENT = new Set<ManagedPath>(['/review', '/quality-goals', 'async function openPage(path: ManagedPath, actions: ShellActions, run: Run): Promise<void> {const stats = document.getElementById('stats');if (!stats) return;- actions.closeStage();actions.surfaceChanged('management', path);if (path === '/taste') {writeShell({@@ -156,43 +162,53 @@ async function openPage(path: ManagedPath, actions: ShellActions, run: Run): Pro/** 管理区一页的元素。 */export function ManagedMatch({ path }: { path: ManagedPath }) {const epoch = useOpenEpoch();+ // 每次导航都重渲染一次:详情撤下的那一次认领写地址不领代次,也要看得见。+ useLocation();const covered = isOverlayPath(peachHistory.navigation.location.pathname);- const opening = useRef(epoch);+ const opening = useRef<number | null>(covered ? null : epoch);if (!covered) opening.current = epoch;// 路径也进 key:认领的写地址从一页换到另一页(配置页改写到数据管理页)时代次不变,页面组在同一个位置换了路由。- return <ManagedPage key={`${path} ${opening.current}`} path={path} covered={covered} />;+ return <ManagedPage key={`${path} ${opening.current ?? 'covered'}`} path={path} covered={opening.current === null} />;}function ManagedPage({ path, covered }: { path: ManagedPath; covered: boolean }) {const actions = useContext(ShellActionsContext);+ const started = useRoutingStarted();+ const run = useRef<Run | null>(null);useEffect(() => {- if (covered || !actions) return undefined;- const run: Run = { live: true, revision: 0, controller: new AbortController() };- void routingStarted.then(() => (run.live ? openPage(path, actions, run) : undefined));- return () => {- run.live = false;- run.controller.abort();- const stats = document.getElementById('stats');- queueMicrotask(() => {- if (stats && run.revision && !stats.hidden && managedEntry(stats)?.revision === run.revision) releaseManagedRoute(stats);- });- };- // 每次挂上只打开一次:详情压上来、关掉时 `covered` 变了也不重开。+ if (covered || !actions || !started || run.current) return;+ const current: Run = { live: true, revision: 0, controller: new AbortController() };+ run.current = current;+ queueMicrotask(() => { if (current.live) void openPage(path, actions, current) });+ // 每次挂上只打开一次:壳开始路由那一刻,或挂上时已经开始了。+ }, [started]);+ useEffect(() => () => {+ const current = run.current;+ if (!current) return;+ current.live = false;+ current.controller.abort();+ const stats = document.getElementById('stats');+ queueMicrotask(() => {+ if (stats && current.revision && !stats.hidden && managedEntry(stats)?.revision === current.revision) releaseManagedRoute(stats);+ });}, []);return null;}/** 旧直达地址 `/resource-sync`:改写成数据管理页的资源同步锚点,不加历史条目,再由数据管理页的元素打开。 */export function ResourceSyncRedirect() {+ const started = useRoutingStarted();+ const done = useRef(false);useEffect(() => {- if (isOverlayPath(peachHistory.navigation.location.pathname)) return undefined;+ if (!started || done.current || isOverlayPath(peachHistory.navigation.location.pathname)) return undefined;+ done.current = true;let live = true;- void routingStarted.then(() => {+ queueMicrotask(() => {if (!live) return;resourceSyncPending = true;shellNavigate('/data-cleanup#resource-sync', { replace: true });});return () => { live = false };- }, []);+ }, [started]);return null;}diff --git a/frontend/src/react/router/pages/overlay.tsx b/frontend/src/react/router/pages/overlay.tsxnew file mode 100644index 000000000..1774abc8e--- /dev/null+++ b/frontend/src/react/router/pages/overlay.tsx@@ -0,0 +1,103 @@+/* 覆盖组的元素(ADR-0031「详情条目记下压在哪一页上」):作品详情、四种队列与关注详情各一条路径+ * (`OVERLAY_PATHS`),覆盖组按真实地址匹配,挂上就把那一条送进舞台,卸下去处不是覆盖地址就收起舞台。+ *+ * 什么时候打开:+ * - 启动(刷新、新标签页、深链):壳开始路由(`@peach/shell` 的 `pageOpens` 从 0 变成 1)那一刻打开;路由根晚于+ * 壳开始路由才装上、地址还停在启动那一条上时,挂上就打开。启动那一条不读背景,关掉回各自的缺省来处。+ * - 没人认领的历史变化(后退前进、React 子树与壳经 `peachHistory` 直接写的地址):接上条目记的背景+ * (`adoptOverlayState`),再打开。元素按导航序号挂 key,地址没变的后退(同一条目重放、`history.state` 为空)+ * 也领一个新代次,重挂、再开一次。+ * - 壳认领写的地址:点卡片把一次性打开请求交给覆盖元素,挂上后取走;队列取齐后写地址与转换详情种类只改条目。+ * 打开与收起都交壳(`ShellActions.openOverlay`、`closeStage`):取数、来处与舞台句柄都还在壳里。+ *+ * 页面组那一侧(`router.tsx`):有背景时按背景匹配,背景页不重挂;没有背景的覆盖地址也挂一格,作品与队列补画+ * 目录网格(目录元素),关注详情只让出 `#stats`(`FollowDetailGround`),不画列表。+ *+ * 打开、收起与让位都排进微任务:路由根在历史变化的同一次调用里同步提交,壳打开舞台要同步画,在提交阶段里画会+ * 出 flushSync 告警。壳在路由根之前订阅历史,它的标题与侧栏那一轮排在前面。 */+import { useContext, useEffect, useRef, useSyncExternalStore, type ReactNode } from 'react';++import {+ adoptOverlayState, bootEntry, clearOverlayBackground, isOverlayPath, overlayTarget, peachHistory, type OverlayPath,+} from '@peach/history';+import { pageOpens, queueOpens, subscribeShell } from '@peach/shell';++import { ShellActionsContext, useOpenEpoch } from '../router';++const readOpens = () => pageOpens;+const readQueueOpens = () => queueOpens;++/** 队列尚未定下条目时的打开意图:路由树接手,等待首屏确定实际地址;不在历史里放临时条目。 */+export function QueueRequests(): ReactNode {+ const actions = useContext(ShellActionsContext);+ const requests = useSyncExternalStore(subscribeShell, readQueueOpens);+ const opens = useSyncExternalStore(subscribeShell, readOpens);+ useEffect(() => {+ if (!requests || !opens) return;+ let live = true;+ queueMicrotask(() => { if (live) actions?.openQueueRequest?.() });+ return () => { live = false };+ }, [requests, opens, actions]);+ return null;+}++/** 挂上的这一格要不要按地址打开、什么时候打开。`run(boot)` 只跑一次:`boot` 为真是启动那一次(壳开始路由时,+ * 或路由根晚装上时地址还是启动那一条),为假是一次历史变化。`claimedOpens` 允许认领写地址的打开请求。+ * 覆盖元素按导航序号挂 key;沉浸元素按开次代次挂 key。 */+export function useRouteOpen(run: (boot: boolean) => void, claimedOpens = false): void {+ const opens = useSyncExternalStore(subscribeShell, readOpens);+ const pending = useRef<'boot' | 'history' | null | undefined>(undefined);+ if (pending.current === undefined) {+ const { claimed } = peachHistory.navigation;+ pending.current = pageOpens === 0 || bootEntry() ? 'boot' : claimed && !claimedOpens ? null : 'history';+ }+ const latest = useRef(run);+ useEffect(() => { latest.current = run });+ const live = useRef(true);+ useEffect(() => {+ live.current = true;+ return () => { live.current = false };+ }, []);+ useEffect(() => {+ const origin = pending.current;+ if (!origin || opens === 0) return;+ pending.current = null;+ queueMicrotask(() => { if (live.current) latest.current(origin === 'boot') });+ }, [opens]);+}++/* 一条覆盖地址的元素:挂上按地址打开那一条,卸下去处不再是覆盖地址就收起舞台(正在放的视频照旧进小窗)。 */+function OverlayOpen() {+ const actions = useContext(ShellActionsContext);+ useRouteOpen((boot) => {+ const target = overlayTarget(peachHistory.navigation.location.pathname);+ if (!actions || !target) return;+ clearOverlayBackground();+ if (!boot) adoptOverlayState(peachHistory.navigation.location.state);+ actions.openOverlay(target);+ }, true);+ useEffect(() => () => {+ queueMicrotask(() => {+ if (!isOverlayPath(peachHistory.navigation.location.pathname)) actions?.closeStage();+ });+ }, []);+ return null;+}++/** 覆盖组一条路径的元素:每次导航各挂一次,同一条目重放也能再打开。 */+export function OverlayMatch({ path }: { path: OverlayPath }): ReactNode {+ useOpenEpoch();+ return <OverlayOpen key={`${path} ${peachHistory.navigation.seq}`} />;+}++/* 页面组里没有背景的关注详情(深链、刷新与没记背景的条目):不画列表,只让出 `#stats`;列表等关掉详情才打开。 */+function FollowGroundOpen() {+ const actions = useContext(ShellActionsContext);+ useRouteOpen(() => { actions?.follow?.ground() });+ return null;+}++/** 页面组 `/follow/item/:id` 的元素,按页面开次代次挂 key。 */+export function FollowDetailGround(): ReactNode {+ return <FollowGroundOpen key={useOpenEpoch()} />;+}diff --git a/frontend/src/react/router/router.tsx b/frontend/src/react/router/router.tsxindex 40672b113..10b3cd4f7 100644--- a/frontend/src/react/router/router.tsx+++ b/frontend/src/react/router/router.tsx@@ -1,24 +1,24 @@/* 客户端导航(ADR-0031「React Router 外壳阶段接管」):React Router 的 Declarative 模式接管 history。* 管理区那几页、播放列表页与关注页、索引页与资料页、目录网格与垃圾队列,以及页面里的附属面(首页筛选条、* 首页新作行、目录页处理横幅、顶栏搜索下拉)与常驻面(底部批量条、侧栏配色卡、管理区页头、沉浸模式、设置面板、- * 侧栏、详情舞台)(`managed-routes.tsx`)由这棵树画。管理区、索引与资料页和目录由页面组按匹配打开- * (`pages/managed.tsx`、`pages/index-entity.tsx`、`pages/catalog.tsx`),其余页面仍由壳的 `ROUTES` 表打开。+ * 侧栏、详情舞台)(`managed-routes.tsx`)由这棵树画。每一页、沉浸模式与详情覆盖都由路由按匹配打开+ * (`pages/` 下各元素),壳不接派发:它只订阅历史同步标题与侧栏,换页时写地址。** 用底层的 `<Router>`,history 是 `@peach/history` 那一份:壳在 React 包到之前就要写地址,`<BrowserRouter>`* 自己建的 history 只听 `popstate`,看不见壳 push 进去的条目。也不用 `unstable_HistoryRouter`:它的更新- * 默认包在 `startTransition` 里,接连两次变化会并成一次渲染,后退前进就少派发一次。+ * 默认包在 `startTransition` 里,接连两次变化会并成一次渲染,后退前进就少开一次。*- * 派发点与管理区宿主是两组 `<Routes>` 的兄弟,从头活到尾:后退前进照旧派发给壳,还归壳的那几屏由壳的准备动作- * (收起舞台、铺骨架、认领表面)打开;画着的页面跟着登记的那几条走(`@peach/history` 的+ * 页面宿主是两组 `<Routes>` 的兄弟,从头活到尾:画着的页面跟着登记的那几条走(`@peach/history` 的* `openManagedRoute`,每个容器一条),详情舞台压在上面、地址换成 `/item/:id` 时它留在原处。*- * 路由分两组:页面组按条目自己记的背景(`usr.backgroundLocation`)匹配,详情压在哪一页上就还匹配那一页;- * 覆盖组按真实地址匹配详情与队列那几条(`OVERLAY_PATHS`)。页面组里管理区、关注、索引、资料与目录五组挂着按地址- * 打开那一页的元素(`pages/managed.tsx`、`pages/follow.tsx`、`pages/index-entity.tsx`、`pages/catalog.tsx`),其余- * 具体路由只声明路径;`path="*"` 不按路径设 key,同一个实例在非管理区地址之间从头活到尾。+ * 路由分两组:页面组按条目自己记的背景(`usr.backgroundLocation`,启动那一条不读)匹配,详情压在哪一页上就还+ * 匹配那一页,背景页不重挂;覆盖组按真实地址匹配详情与队列那几条(`OVERLAY_PATHS`,`pages/overlay.tsx`)。页面组+ * 里管理区、关注、索引、资料、目录与沉浸各挂按地址打开那一页的元素(`pages/managed.tsx`、`pages/follow.tsx`、+ * `pages/index-entity.tsx`、`pages/catalog.tsx`、`pages/immerse.tsx`);没有背景的覆盖地址也在页面组里挂一格:+ * 作品与队列补画目录网格,关注详情只让出 `#stats`。`path="*"` 是认不出的地址,什么都不打开。*- * 一处渲染错误只带走抛错的那一面:每一面各套一层错误边界(`SurfaceBoundary`),根上不套,派发点与两组- * `<Routes>` 不随某一面卸掉。错误经根的 `onCaughtError` 交给 `reportError`,每次一条。 */+ * 一处渲染错误只带走抛错的那一面:每一面各套一层错误边界(`SurfaceBoundary`),根上不套,两组 `<Routes>` 不随+ * 某一面卸掉。错误经根的 `onCaughtError` 交给 `reportError`,每次一条。 */import {Component, createContext, memo, useContext, useLayoutEffect, useMemo, useRef, useState, type ReactNode,type RefObject,@@ -28,21 +28,20 @@ import { createRoot, type Root, type RootOptions } from 'react-dom/client';import { Route, Router, Routes, useLocation, useNavigate, type NavigateFunction } from 'react-router';import {- backgroundOf, failManagedRoute, listenManagedEntry, managedEntries, OVERLAY_PATHS, peachHistory, routeSeen,+ failManagedRoute, listenManagedEntry, managedEntries, navigationBackground, OVERLAY_PATHS, peachHistory,type ManagedEntry, type Navigation,} from '@peach/history';import { Providers } from '../providers';import {- BROWSE_ROUTES, CATALOG_PATHS, CATALOG_ROUTES, ENTITY_ROUTES, INDEX_ROUTES, MANAGED_ROUTES, REDIRECT_ROUTES, isManagedPath, isRoutedPath,- managedPage,+ BROWSE_ROUTES, CATALOG_PATHS, CATALOG_ROUTES, ENTITY_ROUTES, IMMERSE_ROUTES, INDEX_ROUTES, MANAGED_ROUTES, REDIRECT_ROUTES,+ isManagedPath, isRoutedPath, managedPage,} from './managed-routes';+import { FollowDetailGround, OverlayMatch, QueueRequests } from './pages/overlay';import type { ShellActions } from './shell-actions';-/* 每次历史变化的序号。地址没变的 `popstate`(同一条目重放)不会让 Router 的 location 变,- * 但壳一向在每个 `popstate` 上重开那一屏,所以派发跟的是这个序号,不是 location。 */-const NavigationSeq = createContext(0);-/* 开次代次(`@peach/history` 的 `openEpoch`):没人认领的历史变化各领一个,认领的写地址不领。 */+/* 开次代次(`@peach/history` 的 `openEpoch`):没人认领的历史变化各领一个,认领的写地址不领。地址没变的+ * `popstate`(同一条目重放)不会让 Router 的 location 变,代次照样变,按它挂 key 的元素照样重开。 */const OpenEpoch = createContext(0);/** 当前这一页是第几次打开:页面元素按它挂 key,重开就重挂,认领的写地址(页内 replace 写参数)不重挂。 */@@ -53,7 +52,7 @@ export const ShellActionsContext = createContext<ShellActions | null>(null);/** 路由根在历史变化的同一调用里同步提交(`flushSync`):`shellNavigate` 与后退前进返回时,两组 `<Routes>`* 的匹配已经换成新地址,上一页的元素已经卸掉,壳接着往同一个容器里写骨架不会撕掉 React 还管着的节点。- * 派发不在这一次提交里跑:`RouteDispatch` 把它排进提交之后的微任务。 */+ * 元素的打开不在这一次提交里跑,各自排进提交之后的微任务。 */export function PeachRouter({ children }: { children: ReactNode }) {const [navigation, setNavigation] = useState<Navigation>(() => peachHistory.navigation);useLayoutEffect(() => {@@ -62,27 +61,14 @@ export function PeachRouter({ children }: { children: ReactNode }) {return peachHistory.listen((next) => { flushSync(() => setNavigation(next)) });}, []);return (- <NavigationSeq.Provider value={navigation.seq}>- <OpenEpoch.Provider value={navigation.openEpoch}>- <Router location={navigation.location} navigationType={navigation.action} navigator={peachHistory}>- {children}- </Router>- </OpenEpoch.Provider>- </NavigationSeq.Provider>+ <OpenEpoch.Provider value={navigation.openEpoch}>+ <Router location={navigation.location} navigationType={navigation.action} navigator={peachHistory}>+ {children}+ </Router>+ </OpenEpoch.Provider>);}-/** 派发点:每次历史变化报给 `routeSeen`,由它判断要不要让壳打开那一屏。- *- * 报在提交阶段之后的微任务里,不在 layout effect 里当场报:壳打开那一屏时,侧栏等常驻面的句柄内部用- * `flushSync` 当场画完;在 React 的提交阶段里调 `flushSync` 不会同步刷新这同一棵根,句柄返回时就还没画上。- * 微任务仍在这一次导航的同一轮里跑完,早于下一帧绘制。 */-function RouteDispatch() {- const seq = useContext(NavigationSeq);- useLayoutEffect(() => { queueMicrotask(() => routeSeen(seq)) }, [seq]);- return null;-}-/* 跟着地址重渲染的只有这一格:它把当前的 `navigate` 交给管理区宿主,宿主与页面不随导航重渲染。 */function NavigateInto({ target }: { target: RefObject<NavigateFunction | null> }) {const navigate = useNavigate();@@ -90,8 +76,8 @@ function NavigateInto({ target }: { target: RefObject<NavigateFunction | null> }return null;}-/** 管理区页面里的跳转:落在管理区那几页上的交给 React Router,别的路径交 `actions.navigate`(壳写好标题与- * 侧栏)。两条路都不认领,各派发一次、领一个开次代次,打开次数与后退前进相同。 */+/** 管理区页面里的跳转:落在管理区那几页上的交给 React Router,别的路径交 `actions.navigate`。两条路都不认领,+ * 各领一个开次代次,打开次数与后退前进相同。 */export function managedGo(path: string, actions: ShellActions, navigate: NavigateFunction): void {const target = new URL(path, window.location.href);if (!isManagedPath(target.pathname)) { actions.navigate(path); return }@@ -155,11 +141,13 @@ const ManagedPortal = memo(function ManagedPortal(});/* 页面组的 `location` 一直给(没有背景就给当前地址):给与不给之间 `<Routes>` 会多包一层 `LocationContext`,- * 来回切换就会把 `path="*"` 的元素拆掉重挂。- * 两组按页面分段,段与段之间隔开几行:各组迁进来时只改自己那一段。 */+ * 来回切换就会把页面元素拆掉重挂。背景读的是当前条目(`navigationBackground`),启动那一条当作没有。+ * 两组按页面分段,段与段之间隔开几行。 */function RouteGroups({ children }: { children?: ReactNode }) {const location = useLocation();- const background = backgroundOf(location.state);+ // 同一条目重放时地址不变、`useLocation` 不触发重渲染,代次照样变:启动那一条重放之后要开始读背景。+ useOpenEpoch();+ const background = navigationBackground();return (<><Routes location={background ?? location}>@@ -190,7 +178,19 @@ function RouteGroups({ children }: { children?: ReactNode }) {- {/* ── 沉浸 ── `/immerse` 落在下面的 `path="*"`。 */}+ {/* ── 沉浸 ── */}+ {Object.entries(IMMERSE_ROUTES).map(([path, route]) => <Route key={path} path={path} element={route.element} />)}++++ {/* ── 没有背景的覆盖地址 ── 作品与队列挂目录元素,补画网格;关注详情只让出 `#stats`。 */}+ {OVERLAY_PATHS.map((path) => (+ <Route key={path} path={path} element={path === '/follow/item/:id' ? <FollowDetailGround /> : CATALOG_ROUTES['/'].element} />+ ))}++++ {/* 认不出的地址。`children` 只给测试用。 */}<Route path="*" element={children} /></Routes>@@ -198,7 +198,7 @@ function RouteGroups({ children }: { children?: ReactNode }) {{/* ── 覆盖 ── */}<Routes>- {OVERLAY_PATHS.map((path) => <Route key={path} path={path} element={null} />)}+ {OVERLAY_PATHS.map((path) => <Route key={path} path={path} element={<OverlayMatch path={path} />} />)}<Route path="*" element={null} /></Routes></>@@ -211,8 +211,8 @@ export function RouterRoot({ children, actions = null }: { children?: ReactNode;<Providers><ShellActionsContext.Provider value={actions}><PeachRouter>- <RouteDispatch /><ManagedSurface />+ <QueueRequests /><RouteGroups>{children}</RouteGroups></PeachRouter></ShellActionsContext.Provider>diff --git a/frontend/src/react/router/shell-actions.ts b/frontend/src/react/router/shell-actions.tsindex 35c273057..4cc09256b 100644--- a/frontend/src/react/router/shell-actions.ts+++ b/frontend/src/react/router/shell-actions.ts@@ -5,6 +5,8 @@* 从 `@peach/legacy/*` 直接 import;每次打开才算得出的值(只读状态、地址上的分类与页签、引导标记)* 跟着那一次打开走,不在这里。 */+import type { OverlayTarget } from '@peach/history';+import type { LibraryProcessingProps } from '../bundle';import type { CatalogFilterProps } from '../catalog-filter/catalog-filter';import type { CatalogGridProps, MediaCardActions, MediaCardHelpers } from '../catalog-grid/types';@@ -25,7 +27,7 @@ export interface ShellActions {openTag(key: string): void;/** 口味页点一条名次:标签回目录筛选,人名进资料页。 */openTasteSignal(kind: string, name: string): void;- /** 换到一个路径:push 一条不认领的地址,像后退前进一样经派发打开那一页,领一个开次代次。 */+ /** 换到一个路径:push 一条不认领的地址,像后退前进一样领一个开次代次,由页面组按匹配打开那一页。 */navigate(path: string): void;/** 按管理区身份进一屏(路由表里 `section` 等于它的第一条;认不出的落到垃圾文件)。 */openManage(section: string): void;@@ -80,7 +82,11 @@ export interface ShellActions {clearSearch(): void;/** 打开沉浸模式,从 `id` 那一条开始;不给就从头。地址由调用方负责。 */openImmerse(id?: number): void;- /** 收起详情舞台(正在放的视频照旧进小窗),不写地址。 */+ /** 打开覆盖地址上的那一条(作品详情、队列里的一条或关注详情),地址已经在那里,不再写。 */+ openOverlay(target: OverlayTarget): void;+ /** 取走一次队列打开意图:等待队列定下实际条目,首屏确定后才写详情地址。 */+ openQueueRequest?(): void;+ /** 详情舞台开着就收起(正在放的视频照旧进小窗),不写地址。 */closeStage(): void;/** 目录网格卡片的助手与动作:壳里各一份、身份不变(卡片按引用比较),资料页作品区与目录共用。 */readonly grid: { helpers: MediaCardHelpers; actions: MediaCardActions };@@ -113,6 +119,9 @@ export interface FollowFeedShell {skeleton(): string;/** 整页打开交给页面的 props:筛选、取样种子与刷新代次、选择集、照片墙偏好,以及壳里那一份助手与动作。 */props(): FollowFeedProps;+ /** 关注详情下面那一层(深链、或后退前进落到关注详情上时列表没画着):舞台上开着的不是关注详情就先收起,再铺开+ * 管理区那一侧;列表还画在 `#stats` 里就原样留着,没画着就清空 `#stats`,列表等关掉详情才打开。 */+ ground(): void;}/** 目录元素回到壳的那几步。筛选由元素按地址写进 `@peach/shell` 的 `state`,之后的事归壳。 */@@ -125,6 +134,9 @@ export interface CatalogShell {open(path: string, options?: { entering?: boolean; retitle?: boolean }): void;/** 筛选与地址已经由壳写好:按它们重取目录。 */load(): void;+ /** 没有背景的作品详情与队列地址(深链、刷新)下面补画目录网格:网格没被占着、又是启动那一条或还铺着目录骨架时,+ * 按当前地址取一次(不是首页口径,不写筛选)。 */+ fill(): void;/** 离开目录:收起 `#grid` 那一页、首页新作行与处理横幅。 */release(): void;}diff --git a/frontend/src/shell/index.ts b/frontend/src/shell/index.tsindex 322e2f661..57f1ad6cb 100644--- a/frontend/src/shell/index.ts+++ b/frontend/src/shell/index.ts@@ -12,7 +12,7 @@** 每次写入之后通知订阅者,版本号单调递增,React 读者按 `useSyncExternalStore(subscribeShell, shellVersion)`* 接。服务端事实(来源在线状态、目录总数、聚合、实体形态、回收站计数)不在这里,归 TanStack Query;- * 壳路由派发判过期的代次计数器也不在这里。 */+ * 壳判过期的代次计数器也不在这里。 *//** 目录筛选口径:键与地址栏上的查询参数同名(`loc`、`creator`、`tag`、`state`、`sort`、`seed`…)。 */export type CatalogFilters = Record<string, string>;@@ -78,10 +78,12 @@ export let runtimeConfigurable: boolean | null = null;/** 这一次是不是从设置完成页(或教程卡)进来的:口味页打开时取走,取一次就清。 */export let cameFromSetup = false;-/** 壳要路由树按地址打开页面的次数。启动派发那一次记 1:在那之前来源、设置与形状名单还没读完,路由树里按匹配+/** 壳要路由树按地址打开页面的次数。壳开始路由那一次记 1:在那之前来源、设置与形状名单还没读完,路由树里按匹配* 挂上的页面元素只挂着、不打开。之后壳每要求一次「按当前地址把这一页从头重开」(批量写回之后、设置变了要重取、* 点开的正是画着的那一位)就加一。后退前进与跨页由开次代次(`@peach/history` 的 `openEpoch`)管,不经这里。 */export let pageOpens = 0;+/** 队列打开意图的代次:真实条目尚未取齐,地址由详情首屏确定。 */+export let queueOpens = 0;/** 资料页按第一页作品推出来的 JAV 语境(壳的 `javActive` 读):页面推上来,资料页每打开一次先清掉。 */export let entityJavLayout = false;/** 关注页这一次进入的取样种子:创作者、题材、标签三排露出哪些由它定,列表按它取样。重新进入与「换一批」时重掷。 */@@ -112,6 +114,7 @@ export interface ShellFields {followDetailReturnPath: string;configurationRequestedSection: string;pageOpens: number;+ queueOpens: number;entityJavLayout: boolean;followDiscoverySeed: number;followRevision: number;@@ -145,6 +148,7 @@ export function writeShell(patch: Partial<ShellFields>): void {if (has('followDetailReturnPath')) followDetailReturnPath = patch.followDetailReturnPath!;if (has('configurationRequestedSection')) configurationRequestedSection = patch.configurationRequestedSection!;if (has('pageOpens')) pageOpens = patch.pageOpens!;+ if (has('queueOpens')) queueOpens = patch.queueOpens!;if (has('entityJavLayout')) entityJavLayout = patch.entityJavLayout!;if (has('followDiscoverySeed')) followDiscoverySeed = patch.followDiscoverySeed!;if (has('followRevision')) followRevision = patch.followRevision!;diff --git a/frontend/test/history/history.test.ts b/frontend/test/history/history.test.tsindex ab3f9fa30..623c5f255 100644--- a/frontend/test/history/history.test.ts+++ b/frontend/test/history/history.test.ts@@ -64,13 +64,13 @@ it('每一次变化领一个递增序号,后退前进也算', () => {expect(seen[1]!.location.pathname).toBe('/');});-it('开次代次只在没人认领的变化上递增:壳认领的写地址不领,后退前进、路由树 push 与不认领的 shellNavigate 各领一个', () => {+it('开次代次只在没人认领的变化上递增:壳认领的写地址不领,后退前进、路由树 push 与 replace 各领一个', () => {const start = peachHistory.navigation.openEpoch;shellNavigate('/stats');shellNavigate('/stats?tab=1', { replace: true });pop('/');peachHistory.push('/tags');- shellNavigate('/follow', { claim: false });+ peachHistory.replace('/follow');expect(seen.map((n) => n.openEpoch - start)).toEqual([0, 0, 1, 2, 3]);});diff --git a/frontend/test/history/overlay.test.ts b/frontend/test/history/overlay.test.tsindex 1d5833d8b..58b1530f7 100644--- a/frontend/test/history/overlay.test.ts+++ b/frontend/test/history/overlay.test.ts@@ -2,7 +2,7 @@* 详情之间换条沿用上一条的背景,关掉详情与别的地址都不带。这里照壳的调用顺序走一遍:* `holdOverlayBackground()` → `shellNavigate(详情地址, {state: overlayState(种类)})`。* 后退前进落到详情条目上时壳先清、再 `adoptOverlayState(usr)`,打开详情那一处 `takeOverlayReturn()` 取来处;- * 启动那一次壳不调 `adoptOverlayState`,派发来由见 `test/react/router.test.tsx`。 */+ * 启动那一次不调 `adoptOverlayState`,覆盖元素什么时候接背景见 `test/react/pages/overlay.test.tsx`。 */import { beforeEach, expect, it } from 'vitest';import * as islands from '../../src/islands';diff --git a/frontend/test/react/batch-dock.test.tsx b/frontend/test/react/batch-dock.test.tsxindex f0544d216..7723d8ac9 100644--- a/frontend/test/react/batch-dock.test.tsx+++ b/frontend/test/react/batch-dock.test.tsx@@ -67,7 +67,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/frontend/test/react/browse-routes.test.tsx b/frontend/test/react/browse-routes.test.tsxindex a5c6084be..d2dd52140 100644--- a/frontend/test/react/browse-routes.test.tsx+++ b/frontend/test/react/browse-routes.test.tsx@@ -49,7 +49,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/frontend/test/react/catalog-routes.test.tsx b/frontend/test/react/catalog-routes.test.tsxindex bef9befb3..794faaa9a 100644--- a/frontend/test/react/catalog-routes.test.tsx+++ b/frontend/test/react/catalog-routes.test.tsx@@ -47,7 +47,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/frontend/test/react/entity-routes.test.tsx b/frontend/test/react/entity-routes.test.tsxindex 82336d36d..ee7c338cd 100644--- a/frontend/test/react/entity-routes.test.tsx+++ b/frontend/test/react/entity-routes.test.tsx@@ -51,7 +51,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: () => true,- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/frontend/test/react/immerse.test.tsx b/frontend/test/react/immerse.test.tsxindex 5b0d085f3..cd634d04f 100644--- a/frontend/test/react/immerse.test.tsx+++ b/frontend/test/react/immerse.test.tsx@@ -173,7 +173,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/frontend/test/react/manage-header.test.tsx b/frontend/test/react/manage-header.test.tsxindex 8c6c8033b..7e83f9d7e 100644--- a/frontend/test/react/manage-header.test.tsx+++ b/frontend/test/react/manage-header.test.tsx@@ -74,7 +74,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/frontend/test/react/managed-routes.test.tsx b/frontend/test/react/managed-routes.test.tsxindex 04a08d0d6..d7c8851be 100644--- a/frontend/test/react/managed-routes.test.tsx+++ b/frontend/test/react/managed-routes.test.tsx@@ -1,9 +1,9 @@/* 由路由画的那几页(`src/history/managed.ts` 与 `src/react/router/`;管理区画进 `#stats`,索引页画进- * `#index`):壳的骨架留到首屏取齐,换成整页落在同一个任务里;冷启动不论 Router 先挂还是壳先开始路由- * 都只派发一次;每次打开都重取,壳的开关就地合进去不重挂;两个容器互不相收;详情舞台压在上面时页面- * 留着,壳下一次认领表面才收;管理区几页之间的跳转走 React Router,别的交壳。+ * `#index`):壳的骨架留到首屏取齐,换成整页落在同一个任务里;冷启动不论 Router 先挂还是先打开都只取一次;+ * 每次打开都重取,壳的开关就地合进去不重挂;两个容器互不相收;详情舞台压在上面时页面留着,壳下一次认领+ * 表面才收;管理区几页之间的跳转走 React Router,别的交壳。*- * 历史对象、派发状态与各容器的登记都是模块级的,和页面上只有一份一致,所以每条用例重新装载+ * 历史对象与各容器的登记都是模块级的,和页面上只有一份一致,所以每条用例重新装载* `src/history` 与 `src/react/router`。 */import { act, type ReactElement } from 'react';import { createRoot } from 'react-dom/client';@@ -52,7 +52,7 @@ function shellActions(): ShellActions {routeIndex: vi.fn(), savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(),personAvatar: vi.fn(() => ({ html: '', face: '' })), authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(),openFollowAuthor: vi.fn(), openFollowTag: vi.fn(), openPlaylist: vi.fn(), canFlip: () => true,- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}@@ -127,7 +127,7 @@ async function until(ok: () => boolean, what: string): Promise<void> {throw new Error(`一直没等到:${what}`);}-/* 这里直接调打开管线、派发是替身:要开始路由的用例把地址落在首页,管理区的页面元素不挂(元素怎么打开见+/* 这里直接调打开管线:用例把地址落在首页或不交壳的动作,管理区的页面元素不打开(元素怎么打开见`pages/managed.test.tsx`)。 */const open = (r: Loaded, stats: Element, isCurrent = () => true) =>r.openManagedRoute('/activity', {}, { container: stats, isCurrent });@@ -142,19 +142,18 @@ it('冷启动深链,Router 先挂上:壳画的骨架留到首屏取齐,换const fetch = tasksFetch();fetch.install();let opened: Promise<boolean> | undefined;- const dispatch = vi.fn(() => { opened = open(r, stats) });- await act(async () => { await r.startRouting(dispatch) });+ await act(async () => { opened = open(r, stats) });await until(() => fetch.taskCalls() > 0, '首屏取数发出去');expect(stats.firstElementChild, '取齐之前骨架原样留着').toBe(skeleton);const batches = watch(stats, skeleton);fetch.resolve();await act(async () => { expect(await opened).toBe(true) });- expect(dispatch).toHaveBeenCalledTimes(1);+ expect(fetch.taskCalls()).toBe(1);expect(batches[0], '骨架撤下的那一批变化里整页已经画好,中间没有空白的一帧').toEqual({ skeleton: false, painted: true });expect(stats.querySelector(':scope > .peach-react')?.textContent).toContain('追更检查');});-it('冷启动深链,壳先开始路由、Router 后挂上:包到了才取数,挂上时不再派发,骨架同样留到换成整页', async () => {+it('冷启动深链,壳先打开、Router 后挂上:包到了才取数,骨架同样留到换成整页', async () => {const r = await load('/');const { stats, skeleton } = surface();let arrive: (prefetch: typeof r.prefetchManagedRoute) => void = () => {};@@ -162,10 +161,8 @@ it('冷启动深链,壳先开始路由、Router 后挂上:包到了才取数const fetch = tasksFetch();fetch.install();let opened: Promise<boolean> | undefined;- const dispatch = vi.fn(() => { opened = open(r, stats) });- await act(async () => { await r.startRouting(dispatch) });+ await act(async () => { opened = open(r, stats) });await mount(r);- expect(dispatch).toHaveBeenCalledTimes(1);expect(fetch.fetched).not.toHaveBeenCalled();expect(stats.firstElementChild).toBe(skeleton);await act(async () => { arrive(r.prefetchManagedRoute) });@@ -174,7 +171,7 @@ it('冷启动深链,壳先开始路由、Router 后挂上:包到了才取数const batches = watch(stats, skeleton);fetch.resolve();await act(async () => { expect(await opened).toBe(true) });- expect(dispatch).toHaveBeenCalledTimes(1);+ expect(fetch.taskCalls()).toBe(1);expect(batches[0]).toEqual({ skeleton: false, painted: true });});@@ -246,8 +243,6 @@ it('详情舞台压在上面时页面留着,地址回来也不重挂;壳下await mount(r);r.connectManagedRoutes(Promise.resolve(r.prefetchManagedRoute));tasksFetch(tasks(), { deferred: false }).install();- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });await act(async () => { await open(r, stats) });const page = painted(stats);expect(page).not.toBeNull();@@ -257,7 +252,6 @@ it('详情舞台压在上面时页面留着,地址回来也不重挂;壳下// 关掉详情:壳把地址写回列表那一页。await act(async () => { r.shellNavigate('/') });expect(painted(stats)).toBe(page);- expect(dispatch).toHaveBeenCalledTimes(1);act(() => { r.releaseManagedRoute(stats) });expect(stats.children).toHaveLength(0);});@@ -341,16 +335,14 @@ it('这几页之间的跳转交给 React Router,别的路径交壳', async ()expect(vi.mocked(actions.navigate).mock.calls).toEqual([['/'], ['/trash']]);});-it('页面里的跳转落到壳上:只派发一次、历史只多一条', async () => {+it('页面里的跳转:只领一个开次代次、历史只多一条', async () => {const r = await load('/scraping');await mount(r);- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });- dispatch.mockClear();+ const epoch = r.peachHistory.navigation.openEpoch;const before = window.history.length;const navigate = ((to: string) => { r.peachHistory.push(to) }) as unknown as NavigateFunction;await act(async () => { r.managedGo('/activity', shellActions(), navigate) });- expect([dispatch.mock.calls.length, location.pathname, window.history.length - before]).toEqual([1, '/activity', 1]);+ expect([r.peachHistory.navigation.openEpoch - epoch, location.pathname, window.history.length - before]).toEqual([1, '/activity', 1]);});/** 一页的元素与它拿到的 props,不画。 */@@ -513,14 +505,13 @@ it('冷启动深链索引页:壳画的骨架留到首屏取齐,换成整页const fetch = indexFetch();fetch.install();let opened: Promise<boolean> | undefined;- const dispatch = vi.fn(() => { opened = r.openManagedRoute('/tags', tagsOpen(), { container: index, isCurrent: () => true }) });- await act(async () => { await r.startRouting(dispatch) });+ await act(async () => { opened = r.openManagedRoute('/tags', tagsOpen(), { container: index, isCurrent: () => true }) });await until(() => fetch.indexCalls() > 0, '首屏取数发出去');expect(index.firstElementChild, '取齐之前骨架原样留着').toBe(skeleton);const batches = watch(index, skeleton, '痴女');fetch.resolve();await act(async () => { expect(await opened).toBe(true) });- expect(dispatch).toHaveBeenCalledTimes(1);+ expect(fetch.indexCalls()).toBe(1);expect(batches[0], '骨架撤下的那一批变化里整页已经画好').toEqual({ skeleton: false, painted: true });expect(index.querySelector(':scope > .peach-react [data-index-search]')).not.toBeNull();});diff --git a/frontend/test/react/pages/catalog.test.tsx b/frontend/test/react/pages/catalog.test.tsxindex 9888c7a39..9cd05f587 100644--- a/frontend/test/react/pages/catalog.test.tsx+++ b/frontend/test/react/pages/catalog.test.tsx@@ -2,7 +2,7 @@* 次数(`@peach/shell` 的 `pageOpens`)与覆盖层决定整页打开还是只重取;整页打开时照地址重建目录筛选,交壳收尾。** 网格怎么取数、怎么画由 `catalog-routes.test.tsx` 与各页的用例管;这里看的是元素什么时候开、开几次、写进- * `state` 的是哪一套筛选、交给壳什么。历史对象、派发状态与壳状态都是模块级的,每条用例重新装载。 */+ * `state` 的是哪一套筛选、交给壳什么。历史对象与壳状态都是模块级的,每条用例重新装载。 */import { act } from 'react';import { createRoot } from 'react-dom/client';import { afterEach, beforeAll, expect, it, vi } from 'vitest';@@ -46,8 +46,7 @@ function shellActions() {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: () => true,- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(),- closeStage: vi.fn(() => { log.push('closeStage') }),+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(),grid: { helpers: {}, actions: {} } as ShellActions['grid'],configurable: () => true,surfaceShown: vi.fn(),@@ -58,6 +57,7 @@ function shellActions() {}),load: vi.fn(() => { log.push('load') }),release: vi.fn(() => { log.push('release') }),+ fill: vi.fn(() => { log.push('fill') }),},};return { actions, log };@@ -75,9 +75,7 @@ async function boot(r: Loaded, actions: ShellActions) {await act(async () => { root.render(<r.RouterRoot actions={actions} />) });unmounts.push(() => root.unmount());await settle();- await act(async () => {- await r.startRouting((origin) => { if (origin === 'boot') r.shell.writeShell({ pageOpens: 1 }) });- });+ await act(async () => { r.shell.writeShell({ pageOpens: 1 }) });await settle();}@@ -92,11 +90,11 @@ async function pop(path: string, state: unknown = null) {const filters = (r: Loaded) => r.shell.state ?? {};-it('启动:壳开始路由之前只挂着;启动那一下照地址写筛选、收舞台、整页打开一次', async () => {+it('启动:壳开始路由之前只挂着;启动那一下照地址写筛选、整页打开一次', async () => {const r = await load('/unseen?tag=a,%E7%9F%AD%E7%89%87-2%E5%88%86%E5%86%85&owner=none&loc=local');const { actions, log } = shellActions();await boot(r, actions);- expect(log).toEqual(['closeStage', 'open /unseen']);+ expect(log).toEqual(['open /unseen']);expect(filters(r)).toMatchObject({ state: 'fresh', tag: 'a', owner: 'none', loc: 'local' });expect(filters(r).seed, '地址上没写种子就掷一粒').toMatch(/^\d+$/);});@@ -106,10 +104,10 @@ it('从回收站后退到首页重掷取样种子,并让壳作废顶部三层r.shell.writeShell({ state: { seed: '111', sort: 'seed', dir: '' } });const { actions, log } = shellActions();await boot(r, actions);- expect(log).toEqual(['closeStage', 'open /trash']);+ expect(log).toEqual(['open /trash']);expect(filters(r)).toMatchObject({ state: 'trash', seed: '111' });await pop('/');- expect(log.slice(2)).toEqual(['closeStage', 'open / entering']);+ expect(log.slice(1)).toEqual(['open / entering']);expect(filters(r).state).toBe('');expect(filters(r).seed).toMatch(/^\d+$/);expect(filters(r).seed).not.toBe('111');@@ -122,7 +120,7 @@ it('首页换一枚标签的后退前进沿用这一粒种子', async () => {await boot(r, actions);expect(filters(r)).toMatchObject({ tag: 'a', seed: '222' });await pop('/?tag=b');- expect(log.slice(2)).toEqual(['closeStage', 'open /']);+ expect(log.slice(1)).toEqual(['open /']);expect(filters(r)).toMatchObject({ tag: 'b', seed: '222' });});@@ -143,7 +141,7 @@ it('壳认领写地址只重取,不重建筛选;同一个地址再写一次await settle();await act(async () => { r.shellNavigate('/?tag=x', { replace: true }) });await settle();- expect(log.slice(2)).toEqual(['load', 'load']);+ expect(log.slice(1)).toEqual(['load', 'load']);expect(filters(r).tag).toBe('x');});@@ -156,7 +154,7 @@ it('首页、筛选态与回收站之间换页不重挂;壳认领进回收站r.shell.writeShell({ pageOpens: r.shell.pageOpens + 1 });});await settle();- expect(log.slice(2)).toEqual(['closeStage', 'open /trash']);+ expect(log.slice(1)).toEqual(['open /trash']);expect(actions.catalog?.release).not.toHaveBeenCalled();});@@ -167,20 +165,50 @@ it('详情压着时什么都不做;关掉回到压着的那一份地址、筛const overlay = { backgroundLocation: { pathname: '/', search: '?tag=a' }, overlay: 'item' };await act(async () => { r.shellNavigate('/item/7', { state: overlay }) });await settle();- await act(async () => { r.shellNavigate('/item/8', { claim: false, state: overlay }) });+ await act(async () => { r.peachHistory.push('/item/8', overlay) });await settle();await act(async () => { r.shellNavigate('/?tag=a') });await settle();- expect(log.slice(2), '关掉回到原处').toEqual([]);+ expect(log.slice(1), '关掉回到原处').toEqual([]);await act(async () => { r.shellNavigate('/item/7', { state: overlay }) });await settle();r.shell.writeShell({ state: { ...filters(r), seed: '9' } });await act(async () => { r.shellNavigate('/?tag=a') });await settle();- expect(log.slice(2), '压着的时候筛选换了').toEqual(['load']);+ expect(log.slice(1), '压着的时候筛选换了').toEqual(['load']);expect(actions.catalog?.release).not.toHaveBeenCalled();});+it('没有背景的作品地址(深链):补画一次目录网格,不整页打开;关掉时壳要求重开才整页打开', async () => {+ const r = await load('/item/7');+ const { actions, log } = shellActions();+ await boot(r, actions);+ expect(log).toEqual(['fill']);+ await act(async () => {+ r.shellNavigate('/');+ r.shell.writeShell({ pageOpens: r.shell.pageOpens + 1 });+ });+ await settle();+ expect(log).toEqual(['fill', 'open /']);+});++it('后退落到压在首页上的详情才挂上(中间去过别的页):压着时不动,关掉回首页整页打开', async () => {+ const r = await load('/');+ const { actions, log } = shellActions();+ await boot(r, actions);+ const overlay = { backgroundLocation: { pathname: '/', search: '' }, overlay: 'item' };+ await act(async () => { r.shellNavigate('/item/7', { state: overlay }) });+ await settle();+ await act(async () => { r.peachHistory.push('/stats') });+ await settle();+ expect(log.slice(1)).toEqual(['release']);+ await pop('/item/7', { usr: overlay, key: 'x', idx: 1 });+ expect(log.slice(2), '压着的时候不开').toEqual([]);+ await act(async () => { r.shellNavigate('/') });+ await settle();+ expect(log.slice(2)).toEqual(['open /']);+});+it('首页上的 `?state=ads` 原地改写成垃圾文件的地址,由垃圾文件那一页整页打开并补标题', async () => {const r = await load('/?state=ads&type=video&view=dismissed');const { actions, log } = shellActions();@@ -188,7 +216,7 @@ it('首页上的 `?state=ads` 原地改写成垃圾文件的地址,由垃圾await boot(r, actions);expect(window.location.pathname + window.location.search).toBe('/junk-files?type=video&view=dismissed');expect(window.history.length, '改写不加条目').toBe(length);- expect(log).toEqual(['closeStage', 'open /junk-files retitle']);+ expect(log).toEqual(['open /junk-files retitle']);expect(filters(r).state).toBe('ads');});diff --git a/frontend/test/react/pages/follow.test.tsx b/frontend/test/react/pages/follow.test.tsxindex d9e59bb90..ce9ea3106 100644--- a/frontend/test/react/pages/follow.test.tsx+++ b/frontend/test/react/pages/follow.test.tsx@@ -1,9 +1,9 @@/* 关注页与播放列表页的路由元素(`src/react/router/pages/follow.tsx`):页面组匹配到这两条时挂上,按开次代次、* 壳的重开次数(`@peach/shell` 的 `pageOpens`)与覆盖层决定什么时候按地址打开那一页,画进 `#stats`。*- * 关注页不按代次挂 key:每次打开先收舞台、再交壳按地址读筛选(`follow.refresh`),列表还画着就由壳就地推,+ * 关注页不按代次挂 key:每次打开先交壳按地址读筛选(`follow.refresh`),列表还画着就由壳就地推,* 没画着才整页打开。这里的壳替身照真壳的判据推:`#stats` 里画着关注页就把地址上的种子与一个新代次推过去。- * 页面自己怎么取数、怎么画由 `browse-routes.test.tsx` 与各页的用例管。历史对象、派发状态与壳状态都是模块级的,+ * 页面自己怎么取数、怎么画由 `browse-routes.test.tsx` 与各页的用例管。历史对象与壳状态都是模块级的,* 每条用例重新装载。 */import { act } from 'react';import { createRoot } from 'react-dom/client';@@ -69,8 +69,7 @@ function shellActions(r: Loaded) {authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: () => true,surfaceChanged: vi.fn((kind: string, path: string) => { log.push(`surface ${kind} ${path}`) }),- clearSearch: vi.fn(), openImmerse: vi.fn(),- closeStage: vi.fn(() => { log.push('closeStage') }),+ clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(),grid: { helpers: {}, actions: {} } as ShellActions['grid'],follow: {refresh: vi.fn(() => {@@ -82,6 +81,7 @@ function shellActions(r: Loaded) {}),skeleton: vi.fn(() => FOLLOW_SKELETON),props: vi.fn(props),+ ground: vi.fn(() => { log.push('ground') }),},};return { actions, log };@@ -146,9 +146,7 @@ async function boot(r: Loaded, actions: ShellActions) {await act(async () => { root.render(<r.RouterRoot actions={actions} />) });unmounts.push(() => root.unmount());r.connectManagedRoutes(Promise.resolve(r.prefetchManagedRoute));- await act(async () => {- await r.startRouting((origin) => { if (origin === 'boot') r.shell.writeShell({ pageOpens: 1 }) });- });+ await act(async () => { r.shell.writeShell({ pageOpens: 1 }) });await settle();}@@ -173,14 +171,14 @@ const page = (stats: Element) => stats.querySelector(':scope > .peach-react > *'const opens = (actions: ShellActions) => vi.mocked(actions.surfaceChanged).mock.calls.length;const FOLLOW_ITEM_STATE = { backgroundLocation: { pathname: '/follow', search: '' }, overlay: 'follow' };-it('关注元素:壳开始路由那一下按地址整页打开,先收舞台、交壳读筛选,再报换面、铺骨架、取齐首屏', async () => {+it('关注元素:壳开始路由那一下按地址整页打开,先交壳读筛选,再报换面、铺骨架、取齐首屏', async () => {const r = await load('/follow');const stats = statsSurface();const calls = serve();const { actions, log } = shellActions(r);await boot(r, actions);await until(() => page(stats) !== null, '整页画上');- expect(log).toEqual(['closeStage', 'refresh', 'surface follow /follow']);+ expect(log).toEqual(['refresh', 'surface follow /follow']);expect(actions.follow!.skeleton).toHaveBeenCalledTimes(1);expect([calls('/api/follow'), calls('/api/follow/credentials')]).toEqual([1, 1]);expect(r.managedEntry(stats)).toMatchObject({ path: '/follow', props: { revision: 0 } });@@ -244,32 +242,33 @@ it('关注元素:进详情、关掉回列表都由壳认领写地址,列表expect(calls('/api/follow')).toBe(1);});-it('关注元素:深链直接进关注详情不挂列表;关掉详情(壳认领写地址、要求重开)时才整页打开', async () => {+it('关注元素:深链直接进关注详情不挂列表,只交壳让出 `#stats`;关掉详情(壳认领写地址、要求重开)时才整页打开', async () => {const r = await load('/follow/item/2');const stats = statsSurface('');const calls = serve();const { actions, log } = shellActions(r);await boot(r, actions);- expect(log, '深链详情下面不挂列表').toEqual([]);+ expect(log, '深链详情下面不挂列表').toEqual(['ground']);expect(calls('/api/follow')).toBe(0);await openRouted(r, '/follow');await until(() => page(stats) !== null, '关掉详情后整页画上');- expect(log).toEqual(['closeStage', 'refresh', 'surface follow /follow']);+ expect(log).toEqual(['ground', 'refresh', 'surface follow /follow']);});-it('关注元素:后退前进落在压着列表的详情上时不动;之后认领写回列表地址也不动,壳要求重开才打开', async () => {+it('关注元素:后退前进落在压着列表的详情上、列表没画着时交壳让出 `#stats`;关掉回列表(认领写地址)整页打开一次', async () => {const r = await load('/immerse');- statsSurface('');+ const stats = statsSurface('');serve();const { actions, log } = shellActions(r);await boot(r, actions);await pop(r, '/follow/item/2', { usr: FOLLOW_ITEM_STATE, key: 'x', idx: 1 });- await act(async () => { r.shellNavigate('/follow') });- await settle();- expect(log, '被详情压着挂上、认领写地址都不打开').toEqual([]);- await act(async () => { r.shell.writeShell({ pageOpens: r.shell.pageOpens + 1 }) });- await settle();- expect(log).toEqual(['closeStage', 'refresh', 'surface follow /follow']);+ expect(log, '被详情压着挂上不打开').toEqual(['ground']);+ await act(async () => {+ r.shellNavigate('/follow');+ r.shell.writeShell({ pageOpens: r.shell.pageOpens + 1 });+ });+ await until(() => page(stats) !== null, '关掉详情后整页画上');+ expect(log, '认领写地址与要求重开合成一次').toEqual(['ground', 'refresh', 'surface follow /follow']);});it('播放列表元素:按地址整页打开;停在这一页要求重读时就地推新代次重取,壳要求重开时整页重开', async () => {@@ -279,7 +278,7 @@ it('播放列表元素:按地址整页打开;停在这一页要求重读时const { actions, log } = shellActions(r);await boot(r, actions);await until(() => page(stats) !== null, '整页画上');- expect(log).toEqual(['closeStage', 'surface playlists /playlists']);+ expect(log).toEqual(['surface playlists /playlists']);expect(stats.querySelector('[data-skeleton]'), '骨架取齐之后撤下').toBeNull();const painted = page(stats);await act(async () => { r.shell.writeShell({ playlistsRevision: r.shell.playlistsRevision + 1 }) });diff --git a/frontend/test/react/pages/index-entity.test.tsx b/frontend/test/react/pages/index-entity.test.tsxindex 0870a5607..69baa1fbd 100644--- a/frontend/test/react/pages/index-entity.test.tsx+++ b/frontend/test/react/pages/index-entity.test.tsx@@ -1,9 +1,9 @@/* 索引页与资料页的路由元素(`src/react/router/pages/index-entity.tsx`):页面组匹配到这两组时挂上,从地址读出* 这一页,按开次代次、壳的重开次数(`@peach/shell` 的 `pageOpens`)与覆盖层决定什么时候整页打开;资料页同一位- * 领了新代次时只就地推新筛选。打开先报换面、再收舞台。+ * 领了新代次时只就地推新筛选。打开先报换面。** 页面自己怎么取数、怎么画由 `managed-routes.test.tsx`、`entity-routes.test.tsx` 与各页的用例管;这里看的是- * 元素什么时候开、开几次、交给壳什么。历史对象、派发状态与壳状态都是模块级的,每条用例重新装载。 */+ * 元素什么时候开、开几次、交给壳什么。历史对象与壳状态都是模块级的,每条用例重新装载。 */import { act } from 'react';import { createRoot } from 'react-dom/client';import { afterEach, beforeAll, expect, it, vi } from 'vitest';@@ -48,8 +48,7 @@ function shellActions(refreshed = { ok: true }) {authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: () => true,surfaceChanged: vi.fn((kind: string, path: string) => { log.push(`surface ${kind} ${path}`) }),- clearSearch: vi.fn(), openImmerse: vi.fn(),- closeStage: vi.fn(() => { log.push('closeStage') }),+ clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(),grid: { helpers: {}, actions: {} } as ShellActions['grid'],configurable: () => true,surfaceShown: vi.fn((kind: string) => { log.push(`shown ${kind}`) }),@@ -88,9 +87,7 @@ async function boot(r: Loaded, actions: ShellActions) {unmounts.push(() => root.unmount());await settle();const before = vi.mocked(actions.surfaceChanged).mock.calls.length;- await act(async () => {- await r.startRouting((origin) => { if (origin === 'boot') r.shell.writeShell({ pageOpens: 1 }) });- });+ await act(async () => { r.shell.writeShell({ pageOpens: 1 }) });await settle();return before;}@@ -108,13 +105,13 @@ it('地址上的这一位:先整段解码再按段切,名字吃掉剩下全expect(r.entityTarget('/performers/%E0')).toBeNull();});-it('索引元素:壳开始路由之前只挂着;启动那一下按地址打开一次,先报换面、再收舞台、铺骨架', async () => {+it('索引元素:壳开始路由之前只挂着;启动那一下按地址打开一次,先报换面、再铺骨架', async () => {const r = await load('/performers?q=ab');const index = indexSurface();const { actions, log } = shellActions();const before = await boot(r, actions);expect(before, '壳开始路由之前不打开').toBe(0);- expect(log).toEqual(['surface index /performers', 'closeStage']);+ expect(log).toEqual(['surface index /performers']);expect(index.querySelector('[data-skeleton]'), '打开时铺这一页的骨架').not.toBeNull();expect(index.querySelector<HTMLInputElement>('input[type="search"]')?.value, '骨架里的过滤框带着地址上的过滤词').toBe('ab');});@@ -128,7 +125,7 @@ it('索引元素:认领的写地址不重开;不认领的跳转、后退前await act(async () => { r.shellNavigate('/performers?q=abc', { replace: true }) });await settle();expect(opens(actions), '页内写过滤词由壳认领').toBe(1);- await act(async () => { r.shellNavigate('/performers?scope=online', { claim: false }) });+ await act(async () => { r.peachHistory.push('/performers?scope=online') });await settle();expect(opens(actions), '不认领的跳转领新代次').toBe(2);await act(async () => {@@ -161,39 +158,61 @@ it('索引元素:被详情压着时领了新代次也不重开,下面那一const { actions } = shellActions();await boot(r, actions);await act(async () => {- r.shellNavigate('/item/7', { claim: false, state: { backgroundLocation: { pathname: '/performers', search: '' }, overlay: 'item' } });+ r.peachHistory.push('/item/7', { backgroundLocation: { pathname: '/performers', search: '' }, overlay: 'item' });});await settle();expect(opens(actions)).toBe(1);});+it('索引元素:后退落到压在索引上的详情才挂上(中间去过别的页)时不开;关掉回来这一页没露着就整页打开一次', async () => {+ const r = await load('/performers');+ const index = indexSurface();+ const { actions } = shellActions();+ await boot(r, actions);+ const overlay = { backgroundLocation: { pathname: '/performers', search: '' }, overlay: 'item' };+ await act(async () => { r.shellNavigate('/item/7', { state: overlay }) });+ await settle();+ await act(async () => { r.peachHistory.push('/stats') });+ await settle();+ index.hidden = true;+ await act(async () => {+ window.history.replaceState({ usr: overlay, key: 'x', idx: 1 }, '', '/item/7');+ window.dispatchEvent(new PopStateEvent('popstate', { state: window.history.state }));+ });+ await settle();+ expect(opens(actions), '被详情压着挂上不开').toBe(1);+ await act(async () => { r.shellNavigate('/performers') });+ await settle();+ expect(opens(actions), '关掉回来整页打开').toBe(2);+});+it('资料元素:同一位领了新代次只就地推,推不进才整页开;换一位与壳要求重开都整页开', async () => {const refreshed = { ok: true };const r = await load('/performers/A');indexSurface();const { actions, log } = shellActions(refreshed);await boot(r, actions);- expect(log).toEqual(['surface entity /performers/A', 'closeStage', 'loading performer A', 'props performer A ']);+ expect(log).toEqual(['surface entity /performers/A', 'loading performer A', 'props performer A ']);log.length = 0;- await act(async () => { r.shellNavigate('/performers/A?tag=x', { claim: false }) });+ await act(async () => { r.peachHistory.push('/performers/A?tag=x') });await settle();expect(log, '推进画着的那一页就够了').toEqual(['refresh performer A ?tag=x']);log.length = 0;refreshed.ok = false;- await act(async () => { r.shellNavigate('/performers/A?tag=y', { claim: false }) });+ await act(async () => { r.peachHistory.push('/performers/A?tag=y') });await settle();- expect(log, '那一页没画着就整页开').toEqual(['refresh performer A ?tag=y', 'surface entity /performers/A', 'closeStage',+ expect(log, '那一页没画着就整页开').toEqual(['refresh performer A ?tag=y', 'surface entity /performers/A','loading performer A', 'props performer A ?tag=y']);log.length = 0;refreshed.ok = true;await act(async () => { r.shellNavigate('/performers/B', { replace: true }) });await settle();- expect(log, '换一位按新名字重挂').toEqual(['surface entity /performers/B', 'closeStage', 'loading performer B',+ expect(log, '换一位按新名字重挂').toEqual(['surface entity /performers/B', 'loading performer B','props performer B ']);log.length = 0;await act(async () => { reopen(r) });await settle();- expect(log, '壳要求重开时不就地推').toEqual(['surface entity /performers/B', 'closeStage', 'loading performer B',+ expect(log, '壳要求重开时不就地推').toEqual(['surface entity /performers/B', 'loading performer B','props performer B ']);expect(r.shell.entityJavLayout, '每次整页打开都从非 JAV 语境起').toBe(false);});diff --git a/frontend/test/react/pages/managed.test.tsx b/frontend/test/react/pages/managed.test.tsxindex ffbb530cd..7e18bfd5d 100644--- a/frontend/test/react/pages/managed.test.tsx+++ b/frontend/test/react/pages/managed.test.tsx@@ -1,8 +1,8 @@-/* 管理区的页面元素(`src/react/router/pages/managed.tsx`):页面组按匹配挂上它就打开那一页。先收舞台、报换页,- * 再铺骨架(与壳冷启动铺的同键就不重画)、取首屏;派发一次就是打开一次,认领的写地址与详情压上来都不重开;+/* 管理区的页面元素(`src/react/router/pages/managed.tsx`):页面组按匹配挂上它就打开那一页。先报换页,+ * 再铺骨架(与壳冷启动铺的同键就不重画)、取首屏;没人认领的历史变化一次就是打开一次,认领的写地址与详情压上来都不重开;* 卸载时这一页还露在 `#stats` 上才收;`/resource-sync` 与配置页的 `#libraryProcessing` 改写地址、不加历史条目。*- * 历史对象、派发状态与壳的内存状态都是模块级的,每条用例重新装载。 */+ * 历史对象与壳的内存状态都是模块级的,每条用例重新装载。 */import { act } from 'react';import { createRoot } from 'react-dom/client';import { afterEach, beforeAll, expect, it, vi } from 'vitest';@@ -46,19 +46,18 @@ function shellActions(): ShellActions {routeIndex: vi.fn(), savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(),personAvatar: vi.fn(() => ({ html: '', face: '' })), authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(),openFollowAuthor: vi.fn(), openFollowTag: vi.fn(), openPlaylist: vi.fn(), canFlip: () => true,- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}-/** 挂上路由树、接上页面包,再让壳开始路由(派发是替身)。 */+/** 挂上路由树、接上页面包,再像壳那样开始路由:`pageOpens` 写成 1。 */async function boot(r: Loaded, actions = shellActions()) {const root = createRoot(document.createElement('div'));await act(async () => { root.render(<r.RouterRoot actions={actions} />) });unmounts.push(() => root.unmount());r.connectManagedRoutes(Promise.resolve(r.prefetchManagedRoute));- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });- return { actions, dispatch };+ await act(async () => { r.shell.writeShell({ pageOpens: 1 }) });+ return { actions };}/** 管理区正文的容器,铺着壳冷启动时那一张骨架。 */@@ -118,30 +117,28 @@ const settle = () => act(async () => { await new Promise((resolve) => { setTimeo/** 页面画出来的那一块(宿主里的第一个元素):重挂之后就换成另一个。 */const painted = (stats: Element) => stats.querySelector(':scope > .peach-react > *');-it('挂上就打开:先收舞台、再报换页,骨架与冷启动那张同键不重画,首屏取齐才换成整页', async () => {+it('挂上就打开:先报换页,骨架与冷启动那张同键不重画,首屏取齐才换成整页', async () => {const r = await load('/activity');const { stats, skeleton } = surface(r, '/activity');const order: string[] = [];const actions = shellActions();- vi.mocked(actions.closeStage).mockImplementation(() => { order.push('closeStage') });vi.mocked(actions.surfaceChanged).mockImplementation((kind, path) => { order.push(`${kind} ${path}`) });const api = serve({ '/api/tasks': tasks(), '/api/downloads': { available: true, providers: [], tasks: [] } }, ['/api/tasks']);api.fetched.mockImplementationOnce(((original) => (input: string, init?: RequestInit) => {order.push(`fetch ${input.split('?')[0]}`);return original(input, init);})(api.fetched.getMockImplementation()!));- const { dispatch } = await boot(r, actions);+ await boot(r, actions);await until(() => api.calls('/api/tasks') > 0, '首屏取数发出去');- expect(order).toEqual(['closeStage', 'management /activity', 'fetch /api/tasks']);+ expect(order).toEqual(['management /activity', 'fetch /api/tasks']);expect(stats.firstElementChild, '同一张骨架原样留着').toBe(skeleton);api.resolve();await until(() => painted(stats) !== null, '整页画上');expect(stats.firstElementChild).not.toBe(skeleton);expect(stats.textContent).toContain('追更检查');- expect(dispatch).toHaveBeenCalledTimes(1);});-it('派发一次就是打开一次:认领的写地址不重开,同一路径经派发再开就重取、重挂', async () => {+it('没人认领的写地址一次就是打开一次:认领的写地址不重开,同一路径不认领再写就重取、重挂', async () => {const r = await load('/activity');const { stats } = surface(r, '/activity');const api = serve({ '/api/tasks': tasks(), '/api/downloads': { available: true, providers: [], tasks: [] } });@@ -153,7 +150,7 @@ it('派发一次就是打开一次:认领的写地址不重开,同一路径await settle();expect([api.calls('/api/tasks'), painted(stats)]).toEqual([1, page]);const length = window.history.length;- await act(async () => { r.shellNavigate('/activity', { claim: false }) });+ await act(async () => { r.peachHistory.push('/activity') });await until(() => painted(stats) !== null && painted(stats) !== page, '重挂之后再画上');expect(api.calls('/api/tasks')).toBe(2);expect(r.managedEntry(stats)?.revision).not.toBe(revision);@@ -176,6 +173,28 @@ it('详情压在上面时页面不拆也不重开,关掉详情回到这一页expect([painted(stats), api.calls('/api/tasks')]).toEqual([page, 1]);});+it('后退落到压在这一页上的详情才挂上(中间去过别的页)时不开;关掉详情回来按地址打开一次', async () => {+ const r = await load('/activity');+ const { stats } = surface(r, '/activity');+ const api = serve({ '/api/tasks': tasks(), '/api/downloads': { available: true, providers: [], tasks: [] } });+ await boot(r);+ await until(() => painted(stats) !== null, '画上');+ const overlay = { backgroundLocation: { pathname: '/activity', search: '' }, overlay: 'item' };+ await act(async () => { r.shellNavigate('/item/7', { state: overlay }) });+ await settle();+ await act(async () => { r.shellNavigate('/'); stats.replaceChildren() });+ await settle();+ await act(async () => {+ window.history.replaceState({ usr: overlay, key: 'x', idx: 1 }, '', '/item/7');+ window.dispatchEvent(new PopStateEvent('popstate', { state: window.history.state }));+ });+ await settle();+ expect([painted(stats), api.calls('/api/tasks')], '被详情压着挂上不开').toEqual([null, 1]);+ await act(async () => { r.shellNavigate('/activity') });+ await until(() => painted(stats) !== null, '关掉详情后画上');+ expect(api.calls('/api/tasks')).toBe(2);+});+it('走开时还露在 `#stats` 上就收起,收起排在提交之后、不报同步提交的告警;壳藏起了它就留着', async () => {const errors = vi.spyOn(console, 'error');const r = await load('/activity');@@ -188,7 +207,7 @@ it('走开时还露在 `#stats` 上就收起,收起排在提交之后、不报expect([stats.querySelector('.peach-react'), r.managedEntry(stats)]).toEqual([null, null]);expect(errors).not.toHaveBeenCalled();- await act(async () => { r.shellNavigate('/activity', { claim: false }) });+ await act(async () => { r.peachHistory.push('/activity') });await until(() => painted(stats) !== null, '再开一次画上');const page = painted(stats);// 资料页压过来:壳在同一个任务里藏起 `#stats`,页面藏着照常活,等下一次认领表面才收。diff --git a/frontend/test/react/pages/overlay.test.tsx b/frontend/test/react/pages/overlay.test.tsxnew file mode 100644index 000000000..aa1c33f36--- /dev/null+++ b/frontend/test/react/pages/overlay.test.tsx@@ -0,0 +1,257 @@+/* 详情覆盖的路由元素(`src/react/router/pages/overlay.tsx`):覆盖组按真实地址匹配六条覆盖路径,没人认领的历史变化+ * 落上来就接上条目记的背景、交壳打开那一条(`ShellActions.openOverlay`),认领写地址的打开请求也交元素;去处不是覆盖地址时收起舞台。+ * 页面组那一侧按背景匹配,背景页不重挂;启动那一条不读背景,作品与队列补画目录网格,关注详情只让出 `#stats`。+ *+ * 壳怎么取数、怎么画详情由舞台岛与 e2e 管;这里看的是什么时候开、开哪一条、背景接没接上。历史对象与壳状态都是+ * 模块级的,每条用例重新装载。 */+import { act, useEffect } from 'react';+import { flushSync } from 'react-dom';+import { createRoot } from 'react-dom/client';+import { useLocation } from 'react-router';+import { afterEach, beforeAll, expect, it, vi } from 'vitest';++import type { OverlayTarget } from '../../../src/history';+import type { ShellActions } from '../../../src/react/router/shell-actions';++const REACT_IMPORT_TIMEOUT_MS = 30_000;++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++beforeAll(async () => { await import('../../../src/react/router/router') }, REACT_IMPORT_TIMEOUT_MS);++/* `entry` 是装载时那一条历史条目(`{ usr, key, idx }`,刷新后条目照旧带着)。 */+async function load(path: string, entry: unknown = null) {+ vi.resetModules();+ window.history.replaceState(entry, '', path);+ const [history, router, shell] = await Promise.all([+ import('../../../src/history'), import('../../../src/react/router/router'), import('../../../src/shell'),+ ]);+ return { ...history, ...router, shell };+}+type Loaded = Awaited<ReturnType<typeof load>>;++const unmounts: Array<() => void> = [];+afterEach(async () => {+ for (const unmount of unmounts.splice(0)) await act(async () => { unmount() });+ document.body.innerHTML = '';+ vi.restoreAllMocks();+});++/** 壳交进来的那一组:打开记下目标与那一刻取到的来处,其余是空桩。 */+function shellActions(r: Loaded) {+ const opened: Array<{ target: OverlayTarget; from: string | null }> = [];+ let bootOpened = false;+ const actions = {+ openOverlay: vi.fn((target: OverlayTarget) => {+ if ((!r.bootEntry() || bootOpened) && r.peachHistory.navigation.claimed) return;+ bootOpened ||= r.bootEntry();+ opened.push({ target, from: r.takeOverlayReturn() });+ }),+ closeStage: vi.fn(), openImmerse: vi.fn(), surfaceChanged: vi.fn(),+ catalog: { defaultLoc: () => 'local', open: vi.fn(), load: vi.fn(), release: vi.fn(), fill: vi.fn() },+ follow: { refresh: vi.fn(() => false), skeleton: vi.fn(() => ''), props: vi.fn(), ground: vi.fn() },+ } as unknown as ShellActions;+ return { actions, opened };+}++/** 页面组认不出的地址那一格的探针:记挂载、卸载与它看到的地址。 */+function probe() {+ const seen = { mounted: 0, unmounted: 0, paths: [] as string[] };+ function Probe() {+ seen.paths.push(useLocation().pathname);+ useEffect(() => { seen.mounted += 1; return () => { seen.unmounted += 1 } }, []);+ return null;+ }+ return { seen, Probe };+}++async function settle() {+ for (let step = 0; step < 3; step += 1) {+ await act(async () => { await new Promise((resolve) => { setTimeout(resolve, 0) }) });+ }+}++async function mount(r: Loaded, actions: ShellActions, children?: React.ReactNode) {+ const root = createRoot(document.createElement('div'));+ await act(async () => { root.render(<r.RouterRoot actions={actions}>{children}</r.RouterRoot>) });+ unmounts.push(() => root.unmount());+ await settle();+}++/** 像壳那样开始路由:`pageOpens` 写成 1。 */+async function start(r: Loaded) {+ await act(async () => { r.shell.writeShell({ pageOpens: 1 }) });+ await settle();+}++/** 浏览器的后退前进:换好地址与条目再报 `popstate`;不给地址就是同一条目重放。 */+async function pop(path?: string, entry?: unknown) {+ await act(async () => {+ if (path) window.history.replaceState(entry === undefined ? window.history.state : entry, '', path);+ window.dispatchEvent(new PopStateEvent('popstate', { state: window.history.state }));+ });+ await settle();+}++const over = (pathname: string, overlay: 'item' | 'follow' = 'item', search = '') =>+ ({ backgroundLocation: { pathname, search }, overlay });+const entry = (state: unknown, key = 'x') => ({ usr: state, key, idx: 1 });++it('后退前进落到覆盖地址上接上背景并打开;没有请求的认领条目只同步地址;关掉时背景页不重挂', async () => {+ const r = await load('/nowhere');+ const { actions, opened } = shellActions(r);+ const { seen, Probe } = probe();+ await mount(r, actions, <Probe />);+ await start(r);+ await act(async () => { r.shellNavigate('/item/7', { state: over('/nowhere') }) });+ await settle();+ expect(opened, '认领条目没有打开请求时不会重开舞台').toEqual([]);+ await pop('/item/8', entry(over('/nowhere', 'item', '?q=1'), 'a'));+ await pop('/mix/3/4', entry(over('/nowhere'), 'b'));+ await pop('/follow/item/5', entry(over('/nowhere', 'follow'), 'c'));+ await pop('/playlists/2/9', entry(over('/nowhere'), 'd'));+ expect(opened).toEqual([+ { target: { kind: 'item', id: 8 }, from: '/nowhere?q=1' },+ { target: { kind: 'queue', queue: 'mix', key: 3, item: 4 }, from: '/nowhere' },+ { target: { kind: 'follow', id: 5 }, from: '/nowhere' },+ { target: { kind: 'queue', queue: 'playlist', key: 2, item: 9 }, from: '/nowhere' },+ ]);+ expect(actions.closeStage, '覆盖之间换来换去不收舞台').not.toHaveBeenCalled();+ await act(async () => { r.shellNavigate('/nowhere') });+ await settle();+ expect(actions.closeStage).toHaveBeenCalledTimes(1);+ expect([seen.mounted, seen.unmounted], '背景页从头到尾是同一个实例').toEqual([1, 0]);+ expect(new Set(seen.paths)).toEqual(new Set(['/nowhere']));+});++it('`history.state` 为空的同一条目重放:领一个新代次,重开同一条,不接背景', async () => {+ const r = await load('/nowhere');+ const { actions, opened } = shellActions(r);+ await mount(r, actions);+ await start(r);+ await act(async () => { r.shellNavigate('/item/7', { state: over('/nowhere') }) });+ await settle();+ await pop('/item/7', null);+ await pop();+ expect(opened).toEqual([+ { target: { kind: 'item', id: 7 }, from: null },+ { target: { kind: 'item', id: 7 }, from: null },+ ]);+});++it('点卡的认领导航交覆盖元素打开:同一路径再开一次也重新交付,背景页保留原节点', async () => {+ const r = await load('/nowhere');+ const { actions } = shellActions(r);+ const { seen, Probe } = probe();+ await mount(r, actions, <Probe />);+ await start(r);+ const presented: OverlayTarget[] = [];+ vi.mocked(actions.openOverlay).mockImplementation((target) => { presented.push(target) });+ await act(async () => { r.shellNavigate('/item/7', { state: over('/nowhere') }) });+ await settle();+ await act(async () => { r.shellNavigate('/item/7', { state: over('/nowhere') }) });+ await settle();+ expect(presented).toEqual([{ kind: 'item', id: 7 }, { kind: 'item', id: 7 }]);+ expect([seen.mounted, seen.unmounted]).toEqual([1, 0]);+});++it('深链 `/item/:id`:壳开始路由之前只挂着,那一刻打开那一条、补画目录网格;启动那一条不读背景', async () => {+ const r = await load('/item/7', entry(over('/stats')));+ const { actions, opened } = shellActions(r);+ await mount(r, actions);+ expect(opened, '壳开始路由之前不开').toEqual([]);+ await start(r);+ expect(opened).toEqual([{ target: { kind: 'item', id: 7 }, from: null }]);+ expect(actions.catalog!.fill).toHaveBeenCalledTimes(1);+ expect(actions.follow!.ground).not.toHaveBeenCalled();+ expect(actions.surfaceChanged, '条目里记的背景页不打开').not.toHaveBeenCalled();+ await act(async () => { r.shellNavigate('/item/7?t=12', { replace: true }) });+ await settle();+ expect(opened).toHaveLength(1);+});++it('深链 `/follow/item/:id`:打开那一条,只让出 `#stats`、不挂列表也不补画目录', async () => {+ const r = await load('/follow/item/5');+ const { actions, opened } = shellActions(r);+ await mount(r, actions);+ await start(r);+ expect(opened).toEqual([{ target: { kind: 'follow', id: 5 }, from: null }]);+ expect(actions.follow!.ground).toHaveBeenCalledTimes(1);+ expect(actions.follow!.refresh).not.toHaveBeenCalled();+ expect(actions.catalog!.fill).not.toHaveBeenCalled();+});++it('路由根晚于壳开始路由才挂上:挂上就打开启动那一条,只开一次', async () => {+ const r = await load('/parts/3/4');+ const { actions, opened } = shellActions(r);+ r.shell.writeShell({ pageOpens: 1 });+ await mount(r, actions);+ await settle();+ expect(opened).toEqual([{ target: { kind: 'queue', queue: 'parts', key: 3, item: 4 }, from: null }]);+});++it('参数只认数字:`/item/abc` 什么都不开,下面也不补画', async () => {+ const r = await load('/item/abc');+ const { actions, opened } = shellActions(r);+ await mount(r, actions);+ await start(r);+ expect(opened).toEqual([]);+ expect(actions.catalog!.fill).not.toHaveBeenCalled();+ expect(r.overlayTarget('/editions/1/2')).toEqual({ kind: 'queue', queue: 'editions', key: 1, item: 2 });+ expect(r.overlayTarget('/item/7/x')).toBeNull();+ expect(r.overlayTarget('/playlists/1/b')).toBeNull();+ expect(r.overlayTarget('/item/')).toBeNull();+});++it('打开跑在提交阶段之外:壳在里面用 flushSync 画别的岛,当场画上、不报告警', async () => {+ const errors = vi.spyOn(console, 'error');+ const r = await load('/nowhere');+ const { actions } = shellActions(r);+ const host = document.createElement('div');+ const other = createRoot(host);+ unmounts.push(() => other.unmount());+ const painted: string[] = [];+ vi.mocked(actions.openOverlay).mockImplementation(() => {+ flushSync(() => other.render(<i>{location.pathname}</i>));+ painted.push(host.textContent ?? '');+ });+ await mount(r, actions);+ await start(r);+ await pop('/item/9', entry(over('/nowhere')));+ expect(painted).toEqual(['/item/9']);+ expect(errors).not.toHaveBeenCalled();+});++it('队列意图由路由树接手:壳未就绪时等待,取齐前地址与历史深度保持', async () => {+ const r = await load('/nowhere');+ const { actions } = shellActions(r);+ actions.openQueueRequest = vi.fn();+ await mount(r, actions);+ const depth = history.length;+ await act(async () => { r.shell.writeShell({ queueOpens: 1 }) });+ await settle();+ expect(actions.openQueueRequest).not.toHaveBeenCalled();+ await start(r);+ expect(actions.openQueueRequest).toHaveBeenCalledTimes(1);+ expect([location.pathname, history.length]).toEqual(['/nowhere', depth]);+ await act(async () => { r.shell.writeShell({ queueOpens: 2 }) });+ await settle();+ expect(actions.openQueueRequest).toHaveBeenCalledTimes(2);+});++it('沉浸从顶栏的认领导航打开,换条replace不重开,后退离开地址时保留关闭键的行为', async () => {+ const r = await load('/nowhere');+ const { actions } = shellActions(r);+ await mount(r, actions);+ await start(r);+ await act(async () => { r.shellNavigate('/immerse') });+ await settle();+ expect(actions.openImmerse).toHaveBeenCalledTimes(1);+ const depth = history.length;+ await act(async () => { r.shellNavigate('/immerse?id=8', { replace: true }) });+ await settle();+ expect(actions.openImmerse).toHaveBeenCalledTimes(1);+ expect(history.length).toBe(depth);+ await pop('/nowhere', null);+ expect(actions.closeStage).not.toHaveBeenCalled();+});diff --git a/frontend/test/react/router-sync.test.tsx b/frontend/test/react/router-sync.test.tsxindex a16940964..9b4ad8304 100644--- a/frontend/test/react/router-sync.test.tsx+++ b/frontend/test/react/router-sync.test.tsx@@ -1,7 +1,7 @@/* 路由基座(`src/react/router/router.tsx` 与 `src/history/`):路由根在历史变化的同一调用里同步提交;没人认领的* 历史变化各领一个开次代次,按代次挂 key 的元素随之重挂,认领的写地址不重挂;路由元数据覆盖管理区、索引与资料那几页。*- * 历史对象与派发状态都是模块级的,每条用例重新装载 `src/history` 与 `src/react/router`(同 `router.test.tsx`)。 */+ * 历史对象是模块级的,每条用例重新装载 `src/history` 与 `src/react/router`(同 `router.test.tsx`)。 */import { act, useEffect } from 'react';import { createRoot } from 'react-dom/client';import { useLocation } from 'react-router';@@ -56,52 +56,55 @@ function probe(r: Loaded) {}it('shellNavigate 返回时页面组的匹配已经提交:离开的那一页当场卸掉,回来的那一页当场挂上', async () => {- const r = await load('/immerse');+ const r = await load('/nowhere');const { seen, Probe } = probe(r);await mount(r, <Probe />);- await act(async () => { await r.startRouting(() => {}) });const after: number[][] = [];await act(async () => {r.shellNavigate('/stats');after.push([seen.mounted, seen.unmounted]);- pop('/immerse');+ pop('/nowhere');after.push([seen.mounted, seen.unmounted]);- r.shellNavigate('/item/7');+ r.shellNavigate('/no/such');after.push([seen.mounted, seen.unmounted]);});expect(after).toEqual([[1, 1], [2, 1], [2, 1]]);- expect(seen.paths.at(-1)).toBe('/item/7');+ expect(seen.paths.at(-1)).toBe('/no/such');});it('没人认领的历史变化各领一个开次代次、按代次挂的元素当场重挂;认领的写地址不领', async () => {- const r = await load('/immerse');+ const r = await load('/nowhere');const { seen, Probe } = probe(r);await mount(r, <Probe />);- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });- dispatch.mockClear();const keyed: number[] = [];+ const claimed: boolean[] = [];await act(async () => {- r.shellNavigate('/immerse?id=2', { replace: true });+ r.shellNavigate('/nowhere?id=2', { replace: true });keyed.push(seen.keyed);- r.shellNavigate('/immerse?id=3');+ claimed.push(r.peachHistory.navigation.claimed);+ r.shellNavigate('/nowhere?id=3');keyed.push(seen.keyed);- r.peachHistory.push('/immerse?id=4');+ claimed.push(r.peachHistory.navigation.claimed);+ r.peachHistory.push('/nowhere?id=4');keyed.push(seen.keyed);+ claimed.push(r.peachHistory.navigation.claimed);pop();keyed.push(seen.keyed);- r.shellNavigate('/immerse?id=5', { claim: false });+ claimed.push(r.peachHistory.navigation.claimed);+ r.peachHistory.replace('/nowhere?id=5');keyed.push(seen.keyed);+ claimed.push(r.peachHistory.navigation.claimed);});expect(keyed).toEqual([1, 1, 2, 3, 4]);- expect(dispatch).toHaveBeenCalledTimes(3);+ expect(claimed).toEqual([true, true, false, false, false]);expect(seen.mounted).toBe(1);expect(new Set(seen.epochs).size).toBe(4);});-it('路由元数据登记的就是管理区、播放列表与关注、索引、资料与目录那几页,加上改写过去的旧直达地址', async () => {+it('路由元数据登记的就是管理区、播放列表与关注、索引、资料与目录那几页,加上改写过去的旧直达地址、沉浸与覆盖的六条', async () => {const r = await load();expect(new Set(Object.keys(r.ROUTE_META))).toEqual(new Set([...Object.keys(r.MANAGED_ROUTES), ...Object.keys(r.REDIRECT_ROUTES), ...Object.keys(r.BROWSE_ROUTES),- ...Object.keys(r.INDEX_ROUTES), ...Object.keys(r.ENTITY_ROUTES), ...r.CATALOG_PATHS]));+ ...Object.keys(r.INDEX_ROUTES), ...Object.keys(r.ENTITY_ROUTES), ...r.CATALOG_PATHS,+ ...Object.keys(r.IMMERSE_ROUTES), ...r.OVERLAY_PATHS]));});diff --git a/frontend/test/react/router.test.tsx b/frontend/test/react/router.test.tsxindex 619c405a0..ad8328b60 100644--- a/frontend/test/react/router.test.tsx+++ b/frontend/test/react/router.test.tsx@@ -1,11 +1,11 @@-/* 客户端导航(`src/react/router/`):只有后退前进、React 子树里的 `navigate` 和启动会让壳打开那一屏;- * 壳自己写地址不派发;启动不论 Router 先挂还是后挂都只派发一次;`path="*"` 的元素在非管理区地址之间从头到尾- * 是同一个实例。管理区那几页的宿主见 `managed-routes.test.tsx`。+/* 客户端导航(`src/react/router/`):两组 `<Routes>` 怎么匹配。页面组按条目记的背景匹配(启动那一条不读),+ * 覆盖组按真实地址匹配;`path="*"` 是认不出的地址,那一格在认不出的地址之间从头到尾是同一个实例。没人认领的+ * 历史变化(后退前进、React 子树里的 `navigate`)各领一个开次代次,壳认领写的不领。各页什么时候打开见+ * `pages/` 各自的用例,详情覆盖见 `pages/overlay.test.tsx`,管理区那几页的宿主见 `managed-routes.test.tsx`。*- * 历史对象与派发状态都是模块级的,和页面上只有一份一致,所以每条用例重新装载 `src/history` 与- * `src/react/router`。React 与 React Router 在 node_modules 里,不随之重载,组件照常写 JSX。 */+ * 历史对象是模块级的,和页面上只有一份一致,所以每条用例重新装载 `src/history` 与 `src/react/router`。+ * React 与 React Router 在 node_modules 里,不随之重载,组件照常写 JSX。 */import { act, useEffect, type ReactNode } from 'react';-import { flushSync } from 'react-dom';import { createRoot } from 'react-dom/client';import { useLocation, useNavigate } from 'react-router';import { afterEach, beforeAll, expect, it, vi } from 'vitest';@@ -17,10 +17,10 @@ const REACT_IMPORT_TIMEOUT_MS = 30_000;beforeAll(async () => { await import('../../src/react/router/router') }, REACT_IMPORT_TIMEOUT_MS);-/* `path` 是装载时的地址。`path="*"` 那一格只在不归路由树画的地址上(详情、沉浸)才画出来。 */-async function load(path = '/') {+/* `path` 与 `entry` 是装载时的地址与那一条历史条目(`{ usr, key, idx }`,刷新后条目照旧带着)。 */+async function load(path = '/nowhere', entry: unknown = null) {vi.resetModules();- window.history.replaceState(null, '', path);+ window.history.replaceState(entry, '', path);const [history, router] = await Promise.all([import('../../src/history'), import('../../src/react/router/router')]);return { ...history, ...router };}@@ -43,78 +43,6 @@ function pop(path?: string) {window.dispatchEvent(new PopStateEvent('popstate', { state: window.history.state }));}-it('Router 先挂上、壳随后开始路由:启动只派发一次', async () => {- const r = await load();- await mount(r);- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });- expect(dispatch).toHaveBeenCalledTimes(1);-});--it('壳先开始路由、Router 后挂上:挂上时不再派发', async () => {- const r = await load();- const dispatch = vi.fn();- r.shellNavigate('/stats');- await act(async () => { await r.startRouting(dispatch) });- await mount(r);- expect(dispatch).toHaveBeenCalledTimes(1);-});--it('启动后、Router 挂上前有一次后退:挂上时补派这一次', async () => {- const r = await load();- const dispatch = vi.fn();- r.shellNavigate('/stats');- await act(async () => { await r.startRouting(dispatch) });- await act(async () => { pop('/') });- expect(dispatch).toHaveBeenCalledTimes(1);- await mount(r);- expect(dispatch).toHaveBeenCalledTimes(2);-});--it('壳写地址不派发;后退前进各派发一次,地址没变的 popstate 也算', async () => {- const r = await load();- await mount(r);- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });- dispatch.mockClear();- await act(async () => { r.shellNavigate('/stats') });- await act(async () => { r.shellNavigate('/taste', { replace: true }) });- expect(dispatch).not.toHaveBeenCalled();- await act(async () => { pop('/') });- expect(dispatch).toHaveBeenCalledTimes(1);- await act(async () => { pop() });- expect(dispatch).toHaveBeenCalledTimes(2);- await act(async () => { r.shellNavigate('/tags') });- expect(dispatch).toHaveBeenCalledTimes(2);-});--it('派发带来由:启动那一次是 boot(落在详情地址上也是),之后的后退前进与 React 子树写的是 history', async () => {- const r = await load('/item/7');- let navigate: ReturnType<typeof useNavigate> | null = null;- function Probe() { navigate = useNavigate(); return null }- await mount(r, <Probe />);- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });- await act(async () => { r.shellNavigate('/trash') });- await act(async () => { pop('/item/7') });- await act(async () => { void navigate!('/performers') });- expect(dispatch.mock.calls).toEqual([['boot'], ['history'], ['history']]);-});--it('React 子树里的 navigate 让壳打开那一屏', async () => {- const r = await load('/immerse');- let navigate: ReturnType<typeof useNavigate> | null = null;- function Probe() { navigate = useNavigate(); return null }- await mount(r, <Probe />);- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });- dispatch.mockClear();- await act(async () => { void navigate!('/performers') });- expect([dispatch.mock.calls.length, location.pathname]).toEqual([1, '/performers']);- await act(async () => { void navigate!('/tags', { replace: true }) });- expect([dispatch.mock.calls.length, location.pathname]).toEqual([2, '/tags']);-});-/* 详情与队列条目的 `usr`:压在哪一页上,和壳写的形状一致。 */const over = (pathname: string, overlay: 'item' | 'follow' = 'item', search = '') =>({ backgroundLocation: { pathname, search }, overlay });@@ -130,31 +58,40 @@ function probe() {return { seen, Probe };}-it('详情压着下面那一页时,页面组 path="*" 的元素不重挂,看到的是背景那一页', async () => {- const r = await load('/immerse');+it('认不出的地址之间换来换去,页面组 path="*" 那一格是同一个实例', async () => {+ const r = await load('/nowhere');+ const { seen, Probe } = probe();+ await mount(r, <Probe />);+ await act(async () => { r.shellNavigate('/also/nowhere') });+ await act(async () => { pop('/x/y') });+ await act(async () => { pop() });+ expect([seen.mounted, seen.unmounted]).toEqual([1, 0]);+ expect(seen.paths.at(-1)).toBe('/x/y');+});++it('详情压着下面那一页时,页面组的元素不重挂,看到的是背景那一页', async () => {+ const r = await load('/nowhere');const { seen, Probe } = probe();await mount(r, <Probe />);- await act(async () => { await r.startRouting(() => {}) });const steps: Array<[string, ReturnType<typeof over>]> = [- ['/follow/item/3', over('/immerse', 'follow')], ['/item/7', over('/immerse')], ['/parts/1/2', over('/immerse')]];+ ['/follow/item/3', over('/nowhere', 'follow')], ['/item/7', over('/nowhere')], ['/parts/1/2', over('/nowhere')]];for (const [path, state] of steps) await act(async () => { r.shellNavigate(path, { state }) });await act(async () => { pop('/follow/item/3') });- await act(async () => { r.peachHistory.push('/mix/4/5') });+ await act(async () => { r.peachHistory.push('/mix/4/5', over('/nowhere')) });expect([seen.mounted, seen.unmounted]).toEqual([1, 0]);- expect(seen.paths.at(-1)).toBe('/mix/4/5');- expect(new Set(seen.paths)).toEqual(new Set(['/immerse', '/mix/4/5']));+ expect(new Set(seen.paths)).toEqual(new Set(['/nowhere']));});-it('页面组按背景匹配:背景是管理区那一页就匹配那一条,两组都不报没有路由', async () => {+it('页面组按背景匹配:背景是管理区那一页就匹配那一条;没有背景的覆盖地址挂自己那一格;两组都不报没有路由', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});try {- const r = await load('/immerse');+ const r = await load('/nowhere');const { seen, Probe } = probe();await mount(r, <Probe />);- await act(async () => { await r.startRouting(() => {}) });await act(async () => { r.shellNavigate('/item/7', { state: over('/stats', 'item', '?range=30') }) });expect([seen.mounted, seen.unmounted]).toEqual([1, 1]);await act(async () => { r.shellNavigate('/item/8') });+ expect(seen.mounted, '没有背景的作品地址不落到认不出的那一格').toBe(1);await act(async () => { r.shellNavigate('/no/such/page') });expect(seen.mounted).toBe(2);const unmatched = warn.mock.calls.map((call) => String(call[0])).filter((text) => text.includes('No routes matched'));@@ -164,45 +101,46 @@ it('页面组按背景匹配:背景是管理区那一页就匹配那一条,}});-it('带背景的条目后退前进照样派发一次,背景随条目回来', async () => {- const r = await load('/stats');- await mount(r);- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });- dispatch.mockClear();- await act(async () => { r.shellNavigate('/item/7', { state: over('/stats') }) });- await act(async () => { r.shellNavigate('/item/8', { state: over('/stats') }) });- expect(dispatch).not.toHaveBeenCalled();- await act(async () => { pop('/item/7') });- expect(dispatch).toHaveBeenCalledTimes(1);- expect(r.peachHistory.navigation.location.state).toEqual(over('/stats'));+it('启动那一条不读背景:刷新落在带背景的详情条目上时当作没有背景;后退前进回到这一条才读', async () => {+ const r = await load('/item/7', { usr: over('/nowhere'), key: 'boot', idx: 0 });+ const { seen, Probe } = probe();+ await mount(r, <Probe />);+ expect(r.navigationBackground()).toBeNull();+ expect(seen.mounted, '启动那一条照没有背景,作品地址挂自己那一格').toBe(0);await act(async () => { pop() });- expect(dispatch).toHaveBeenCalledTimes(2);+ expect(r.navigationBackground()).toEqual({ pathname: '/nowhere', search: '' });+ expect(seen.mounted, '后退前进回到这一条,按背景匹配').toBe(1);});-it('派发跑在 React 提交阶段之外:壳在里面用 flushSync 画别的岛,当场就画上', async () => {- const r = await load();- await mount(r);- const host = document.createElement('div');- const other = createRoot(host);- unmounts.push(() => other.unmount());- const painted: string[] = [];- const dispatch = () => {- flushSync(() => other.render(<i>{location.pathname}</i>));- painted.push(host.textContent ?? '');- };- await act(async () => { await r.startRouting(dispatch) });- await act(async () => { pop('/stats') });- expect(painted).toEqual(['/', '/stats']);+it('壳认领写的地址不领开次代次;后退前进与 React 子树里的 navigate 各领一个,地址没变的 popstate 也算', async () => {+ const r = await load('/nowhere');+ let navigate: ReturnType<typeof useNavigate> | null = null;+ function Probe() { navigate = useNavigate(); return null }+ await mount(r, <Probe />);+ const epoch = () => r.peachHistory.navigation.openEpoch;+ const start = epoch();+ await act(async () => { r.shellNavigate('/stats') });+ await act(async () => { r.shellNavigate('/taste', { replace: true }) });+ expect([epoch() - start, r.peachHistory.navigation.claimed]).toEqual([0, true]);+ await act(async () => { pop('/nowhere') });+ await act(async () => { pop() });+ expect(epoch() - start).toBe(2);+ await act(async () => { void navigate!('/performers') });+ expect([epoch() - start, r.peachHistory.navigation.claimed, location.pathname]).toEqual([3, false, '/performers']);});-it('configureRouter 只挂一棵:重复调用后一次后退仍只派发一次', async () => {- const r = await load();- const dispatch = vi.fn();- const actions = {} as Parameters<typeof r.configureRouter>[0];+it('configureRouter 只挂一棵:重复调用后一次后退落到详情上,覆盖元素只打开一次', async () => {+ const r = await load('/nowhere');+ const shell = await import('../../src/shell');+ const openOverlay = vi.fn();+ const actions = { openOverlay, closeStage: vi.fn() } as unknown as Parameters<typeof r.configureRouter>[0];await act(async () => { r.configureRouter(actions) });await act(async () => { r.configureRouter(actions) });- await act(async () => { await r.startRouting(dispatch) });- await act(async () => { pop('/stats') });- expect(dispatch).toHaveBeenCalledTimes(2);+ await act(async () => { shell.writeShell({ pageOpens: 1 }) });+ await act(async () => {+ window.history.replaceState({ usr: over('/nowhere'), key: 'x', idx: 1 }, '', '/item/7');+ pop();+ });+ await act(async () => { await new Promise((resolve) => { setTimeout(resolve, 0) }) });+ expect(openOverlay.mock.calls).toEqual([[{ kind: 'item', id: 7 }]]);});diff --git a/frontend/test/react/settings-panel.test.tsx b/frontend/test/react/settings-panel.test.tsxindex f75233241..1509d0f45 100644--- a/frontend/test/react/settings-panel.test.tsx+++ b/frontend/test/react/settings-panel.test.tsx@@ -90,7 +90,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/frontend/test/react/sidebar.test.tsx b/frontend/test/react/sidebar.test.tsxindex 37acbe047..942337f61 100644--- a/frontend/test/react/sidebar.test.tsx+++ b/frontend/test/react/sidebar.test.tsx@@ -76,7 +76,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/frontend/test/react/stage.test.tsx b/frontend/test/react/stage.test.tsxindex 24a4c6ecb..a2688f5c7 100644--- a/frontend/test/react/stage.test.tsx+++ b/frontend/test/react/stage.test.tsx@@ -128,7 +128,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/frontend/test/react/surface-boundary.test.tsx b/frontend/test/react/surface-boundary.test.tsxindex 2787fb994..be082e386 100644--- a/frontend/test/react/surface-boundary.test.tsx+++ b/frontend/test/react/surface-boundary.test.tsx@@ -1,10 +1,11 @@-/* 路由树一面一层错误边界:某一面渲染抛错只空出那一面并撤掉它的登记,别的面、派发点与 `<Routes>` 照旧;+/* 路由树一面一层错误边界:某一面渲染抛错只空出那一面并撤掉它的登记,别的面与 `<Routes>` 照旧;* 错误经根的 `onCaughtError` 交给 `reportError`,每次一条;壳下次打开能重开。** 首页新作行与垃圾队列的页面模块整个换掉,抛不抛、首屏取数成不成由 `pages` 当场决定:用例中途改它,就是* 「下一次打开换成好页面」。 */import { act } from 'react';import { createRoot } from 'react-dom/client';+import { useLocation } from 'react-router';import { afterEach, beforeAll, expect, it, vi } from 'vitest';import type { CatalogFilterProps } from '../../src/react/catalog-filter/catalog-filter';@@ -43,7 +44,7 @@ vi.mock('../../src/react/junk-queue/junk-queue-page', () => ({/** 装载时停在沉浸地址上:页面组 `path="*"` 只在不归路由树画的地址上画出 `children`。 */async function load() {vi.resetModules();- window.history.replaceState(null, '', '/immerse');+ window.history.replaceState(null, '', '/nowhere');const [history, router, routes] = await Promise.all([import('../../src/history'), import('../../src/react/router/router'), import('../../src/react/router/managed-routes'),]);@@ -70,16 +71,21 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}/** 壳启动时的顺序:先画路由树,再接上取数。根的选项与 `configureRouter` 是同一份;返回根所在的容器,* `children` 的标记节点画在那里面。 */+/* 页面组认不出的地址那一格:记着它看到的地址,后退前进之后还跟着变就说明 `<Routes>` 还活着。 */+function Marker() {+ return <i data-marker data-path={useLocation().pathname} />;+}+async function mount(r: Loaded): Promise<HTMLElement> {const el = document.createElement('div');const root = createRoot(el, r.ROUTER_ROOT_OPTIONS);- await act(async () => { root.render(<r.RouterRoot actions={shellActions()}><i data-marker /></r.RouterRoot>) });+ await act(async () => { root.render(<r.RouterRoot actions={shellActions()}><Marker /></r.RouterRoot>) });unmounts.push(() => root.unmount());await act(async () => { r.connectManagedRoutes(Promise.resolve(r.prefetchManagedRoute)) });return el;@@ -204,7 +210,7 @@ it('首屏取数失败不是渲染错误:照画、不上报', async () => {expect(reported).not.toHaveBeenCalled();});-it('一页抛错:四座附属面照画,后退前进照旧派发', async () => {+it('一页抛错:四座附属面照画,后退前进照旧跟着走', async () => {const reported = watchReports();pages.junkBroken = true;const r = await load();@@ -219,9 +225,6 @@ it('一页抛错:四座附属面照画,后退前进照旧派发', async () =await r.openManagedRoute('library-processing', { toast: vi.fn(), mode: 'notice' }, { container: notice, isCurrent: always });await r.openManagedRoute('search', searchProps(exposed), { container: menu, isCurrent: always });});- const dispatch = vi.fn();- await act(async () => { await r.startRouting(dispatch) });-const grid = container('grid');await act(async () => { await r.openManagedRoute('/junk-files', {}, { container: grid, isCurrent: always }) });@@ -237,6 +240,9 @@ it('一页抛错:四座附属面照画,后退前进照旧派发', async () =expect(exposed.api).not.toBeNull();expect(tree.querySelector('[data-marker]')).not.toBeNull();- await act(async () => { window.dispatchEvent(new PopStateEvent('popstate', { state: window.history.state })) });- expect(dispatch, '派发点还活着').toHaveBeenCalledTimes(2);+ await act(async () => {+ window.history.replaceState(window.history.state, '', '/elsewhere');+ window.dispatchEvent(new PopStateEvent('popstate', { state: window.history.state }));+ });+ expect(tree.querySelector('[data-marker]')?.getAttribute('data-path'), '路由根还跟着历史走').toBe('/elsewhere');});diff --git a/frontend/test/react/surface-routes.test.tsx b/frontend/test/react/surface-routes.test.tsxindex 9572d8d30..76705207f 100644--- a/frontend/test/react/surface-routes.test.tsx+++ b/frontend/test/react/surface-routes.test.tsx@@ -46,7 +46,7 @@ function shellActions(): ShellActions {savePeopleLayout: vi.fn(), exitSelectMode: vi.fn(), personAvatar: vi.fn(() => ({ html: '', face: '' })),authorAvatar: vi.fn(() => ''), showIndexTags: vi.fn(), openFollowAuthor: vi.fn(), openFollowTag: vi.fn(),openPlaylist: vi.fn(), canFlip: vi.fn(() => true),- surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],+ surfaceChanged: vi.fn(), clearSearch: vi.fn(), openImmerse: vi.fn(), openOverlay: vi.fn(), closeStage: vi.fn(), grid: {} as ShellActions['grid'],};}diff --git a/tests/test_copy_final_state.py b/tests/test_copy_final_state.pyindex 38568177e..72bb702e7 100644--- a/tests/test_copy_final_state.py+++ b/tests/test_copy_final_state.py@@ -65,7 +65,7 @@ class CopyFinalStateTests(unittest.TestCase):"""扫描面写死成 glob 就会漏掉新目录,所以直接核对它收到了哪些文件。"""picked = {path.relative_to(ROOT).as_posix() for path in checker.targets(ROOT)}for required in ("AGENTS.md", "README.md", "docs/HANDOFF.md",- "web/app.js", "web/index.html", "web/js/routes.js",+ "web/app.js", "web/index.html", "web/js/core.js","src/peach/web_entity.py","tests/test_web_ui.py",".claude/skills/peach-worktree/SKILL.md"):diff --git a/tests/test_legacy_shell_routes.py b/tests/test_legacy_shell_routes.pyindex c418d475f..c93d4b2d8 100644--- a/tests/test_legacy_shell_routes.py+++ b/tests/test_legacy_shell_routes.py@@ -4,10 +4,10 @@ ADR-0022 的迁移方向是逐屏搬出 app.js,可 2026-09-13 盘点时它已时多出四成——每一轮新功能都往旧壳里加一屏。行数拦不住这种增长(拦住的只是注释),拦得住的是「旧壳里登记了哪些页面」。-冻结的是页面全集,按归属分成三列:壳打开的(app.js `ROUTES` 的字面 match)、路由树用元素画的-(`managed-routes.tsx` 各张路由表里带 `element` 的条目;目录表按页面分键,带了元素就算 `CATALOG_PATHS`-那几条路径)、覆盖组按真实地址匹配的详情与队列(`OVERLAY_PATHS`)。一页搬进路由树就从 app.js 的 `ROUTES`-里删掉,三列互不相交、并起来仍是这张全集。+冻结的是页面全集,按归属分成三列:壳打开的(app.js 里 `ROUTES` 表的字面 match,这张表已经没有了,这一列+是空的)、路由树用元素画的(`managed-routes.tsx` 各张路由表里带 `element` 的条目;目录表按页面分键,带了元素+就算 `CATALOG_PATHS` 那几条路径)、覆盖组按真实地址匹配的详情与队列(`OVERLAY_PATHS`)。三列互不相交、+并起来仍是这张全集;壳那一列不许再长出来。"""import pathlibimport re@@ -22,8 +22,8 @@ ROUTE_TABLES = FRONTEND_SRC / "react" / "router" / "managed-routes.tsx"OVERLAY = FRONTEND_SRC / "history" / "overlay.ts"CORE = FRONTEND_SRC / "core" / "index.ts"-#: 以字面量写出的页面路径;`STATE_ROUTES` 那一组筛选态(三个筛选态与垃圾文件)不在此列,壳的 `ROUTES` 里-#: 展开的组数由下面的 `SPREADS` 钉住。资料页由路由树按模式(`TREE_PATTERNS`)登记,同样不在此列。+#: 以字面量写出的页面路径;`STATE_ROUTES` 那一组筛选态(三个筛选态与垃圾文件)不在此列。资料页由路由树按模式+#: (`TREE_PATTERNS`)登记,同样不在此列。FROZEN_ROUTES = frozenset({"/", "/trash", "/playlists", "/playlists/:playlist/:item", "/mix/:seed/:item","/parts/:seed/:item", "/editions/:seed/:item", "/item/:id", "/follow/item/:id",@@ -32,7 +32,6 @@ FROZEN_ROUTES = frozenset({"/scraping", "/follow", "/follow-manage", "/configuration", "/activity", "/immerse","/diagnostics",})-SPREADS = 0#: 路由树按模式登记的资料页,一个实体种类一条。TREE_PATTERNS = frozenset({"/performers/*", "/studios/*", "/creators/*", "/series/*", "/agencies/*"})@@ -45,8 +44,9 @@ def without_comments(source: str) -> str:def routes_table(source: str) -> str:- start = source.index("const ROUTES=[")- return source[start:source.index("\n];", start)]+ """app.js 里 `ROUTES` 表的正文;没有这张表时是空串。"""+ start = source.find("const ROUTES=[")+ return "" if start < 0 else source[start:source.index("\n];", start)]def braced(source: str, start: int) -> str:@@ -133,9 +133,8 @@ class LegacyShellRouteTests(unittest.TestCase):self.assertEqual(sorted(self.patterns), sorted(TREE_PATTERNS),"路由树按模式登记的页面变了;新增一种同样算加页面")- def test_the_shell_table_keeps_its_spreads_and_registers_nothing_itself(self):- self.assertEqual(self.table.count("...Object.entries("), SPREADS,- "ROUTES 里展开的路由组数量变了;新增一组同样算往旧壳里加页面")+ def test_the_shell_opens_no_page_by_itself(self):+ self.assertEqual(sorted(self.shell), [], "app.js 不再有自己打开的页面:页面做成路由树的元素")self.assertEqual(len(re.findall(r"\bregisterRoute\(", self.source)), 0,"app.js 不登记页面:页面做成路由树的元素")diff --git a/tests/test_web_js.py b/tests/test_web_js.pyindex 5bac26b60..19bca0d5c 100644--- a/tests/test_web_js.py+++ b/tests/test_web_js.py@@ -153,48 +153,6 @@ class WebJsBehaviourTests(unittest.TestCase):for (module, fn, args, want), got in zip(table, self.run_js(cases)):self.assertEqual(got, want, f"{module}.{fn}{tuple(args)}")- # ── 路由匹配 ────────────────────────────────────────────────────────────-- def test_route_patterns_match_what_the_table_says_and_nothing_else(self):- routes = [- {"match": "/", "title": "首页"},- {"match": "/item/:id", "title": "作品"},- {"match": "/playlists/:playlist/:item"},- {"match": "/performers/:name*", "title": None},- ]- self.assertJsResults([- # 精确路径:多一段少一段都不算。- ("routes.js", "matchPath", ["/", "/"], {}),- ("routes.js", "matchPath", ["/", "/item/7"], None),- ("routes.js", "matchPath", ["/stats", "/stats"], {}),- ("routes.js", "matchPath", ["/stats", "/stats/7"], None),- # `:id` 只吃数字,且吃完就得刚好用完。非数字必须落空——每条动态路由- # 自己写这条正则的话,漏写的那条会把 `/item/abc` 当合法 id 送进 `+parts[1]`。- ("routes.js", "matchPath", ["/item/:id", "/item/42"], {"id": 42}),- ("routes.js", "matchPath", ["/item/:id", "/item/abc"], None),- ("routes.js", "matchPath", ["/item/:id", "/item/"], None),- ("routes.js", "matchPath", ["/item/:id", "/item/42/x"], None),- ("routes.js", "matchPath", ["/playlists/:a/:b", "/playlists/3/9"],- {"a": 3, "b": 9}),- # `:name*` 吃掉剩下全部:女优名字里有斜杠,只吃一段会把人名切两半。- ("routes.js", "matchPath", ["/performers/:name*", "/performers/A/B"],- {"name": "A/B"}),- ("routes.js", "matchPath", ["/performers/:name*", "/performers/A"],- {"name": "A"}),- # 尾段为空不算命中,否则 `/performers` 索引页会被实体页抢走。- ("routes.js", "matchPath", ["/performers/:name*", "/performers"], None),- # 先登记先匹配,表里的顺序就是优先级。- ("routes.js", "matchRoute", [routes, "/item/7"],- {"route": {"match": "/item/:id", "title": "作品"}, "params": {"id": 7}}),- ("routes.js", "matchRoute", [routes, "/nowhere"], None),- # 标题:字符串直接用,没有 title 的路由给空串(由调用方兜底文案),- # 匹配不上也是空串。- ("routes.js", "routeLabel", [routes, "/item/7"], "作品"),- ("routes.js", "routeLabel", [routes, "/playlists/1/2"], ""),- ("routes.js", "routeLabel", [routes, "/performers/A/B"], ""),- ("routes.js", "routeLabel", [routes, "/nowhere"], ""),- ])-# ── JAV 标题 ────────────────────────────────────────────────────────────def test_media_suffix_is_stripped_only_for_jav(self):diff --git a/web/app.js b/web/app.jsindex d0b8f4c49..a4a43426c 100644--- a/web/app.js+++ b/web/app.js@@ -7,7 +7,6 @@ import { selectRange, selectionSummary, selectGroup, syncSelectionToolbar } fromimport { MEDIA_SOURCE_ICONS } from './js/ui-components.js';import { initBoardControls } from './dist/peach-ui.js';import { javDisplayName, javTitleHtml } from './js/jav-title.js';-import { matchRoute, routeLabel } from './js/routes.js';import { tagLabel } from './js/tags.js';import { playUiSound, setUiSoundsEnabled, wireUiSounds } from './js/ui-sounds.js';import { appSettingsStore, applySyncedSettings, applyTheme, watchSystemTheme, THEME_OPTIONS, applyDensity, toggleDensity, paintPhotoSizeButton } from './dist/peach-ui.js';@@ -19,14 +18,14 @@ import { junkCountSkeletonHtml, junkPath, junkRoute } from './dist/peach-ui.js';import { catalogSuggestions, catalogEmptyHtml, catalogFilterSkeletonHtml, sidebarTagCounts, sidebarHasCatalogContent } from './dist/peach-ui.js';import { managementSkeletonHtml, pageSkeletonHtml, paintManagementPlaceholder, skeletonKeyOf } from './dist/peach-ui.js';import { dropBars, fetchBars, fetchTopsPage, loadMediaSources } from './dist/peach-ui.js';-import { loadRouter, managedEntry, managedTaken, openManagedRoute, peachHistory, releaseManagedRoute, shellNavigate, startRouting, updateManagedRoute } from './dist/peach-ui.js';-import { ROUTE_META, routeMetaOf } from './dist/peach-ui.js';+import { loadRouter, managedEntry, managedTaken, openManagedRoute, peachHistory, releaseManagedRoute, shellNavigate, updateManagedRoute } from './dist/peach-ui.js';+import { ROUTE_META, bootEntry, isOverlayPath, routeMetaOf } from './dist/peach-ui.js';import { state, barsContext, detailReturnBarsContext, selected, followSelected, selectMode, lastSelectedId, followLastSelectedId, selectSurface } from './dist/peach-ui.js';import { detailReturnPath, detailOriginAnchor, detailOriginAbove, detailReturnNeedsRestore, activeQueue, pendingQueueRoute, presentedItem, followDetailReturnPath } from './dist/peach-ui.js';-import { cameFromSetup, entityJavLayout, notifyShell, pageOpens, runtimeConfigurable, writeShell } from './dist/peach-ui.js';+import { cameFromSetup, entityJavLayout, notifyShell, pageOpens, queueOpens, runtimeConfigurable, writeShell } from './dist/peach-ui.js';import { followDiscoverySeed, followRevision, playlistsRevision } from './dist/peach-ui.js';import { INDEX_TITLES, indexParams, paintIndexSkeleton, peopleLayoutOf } from './dist/peach-ui.js';-import { adoptOverlayState, clearOverlayBackground, holdOverlayBackground, overlayState, retagOverlay, takeOverlayReturn } from './dist/peach-ui.js';+import { clearOverlayBackground, holdOverlayBackground, overlayState, retagOverlay, takeOverlayReturn } from './dist/peach-ui.js';import { javImageKind, syncJavImages, entitySkeletonHtml } from './dist/peach-ui.js';import { avatarInner, configureHoverPreview, coverAnchor, coverImage, entityFaceImg, faceBoxAttrs, faceOrigin, facePos, imageFallbackAttrs, installCardArt, logoUrl, refitNativeImages, releaseHoverPreviews, rememberRepresentatives, setHoverState, upgradeCover, wireImageFallbacks } from './dist/peach-ui.js';import { clickPlayerControl, immerseApi, loadImmerse, loadStage, seekVideoBy, stageApi, toggleVideoPlayback } from './dist/peach-ui.js';@@ -102,66 +101,25 @@ let followSort='new',followDir='desc',followSeed=0;let followDurMin=0,followDurMax=0;/* ────────────────────────────────────────────────────────────────────────── */-/* ── 路由表 ───────────────────────────────────────────────────────────────────- 一屏一条。`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` 顶替。-- 顺序即优先级:先匹配上的赢,所以精确路径写在同前缀的动态路径前面。-- `title`、`nav`、`section`、`refresh` 这几样元数据,路由树那一侧登记了的(`ROUTE_META`,- `frontend/src/history/route-meta.ts`)就不在这里写:读者一律经 `routeMeta(path)`,先查路由树、再查这张表。-- 这张表替掉的是同一份知识的七个副本:`restoreRoute` 的分支链,加上 `navTo`、- `navOn`、`openManage`、`manageSection`、`reloadCurrentSurface`、`refreshAll`- 各自抄的那几条。加一屏只改这张表;同一份知识散成七处时,漏一处的症状还各不相同:URL 能进但侧栏不亮、- 点进去了但「换一批」把你扔回统计页、批量操作后回到首页而不是刚才那一屏。-- 条目按页面分组(目录、播放列表、覆盖、关注、沉浸),每组前一行组名、组与组之间空开两行:- 各组迁进路由树时只删自己那几行。 */-const ROUTES=[- // ── 覆盖 ──- {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 openFollowDetail(params.id,push)}},--- // ── 沉浸 ──- {match:'/immerse',nav:'immerse',title:'沉浸模式',- open:(params,push)=>openTok(immerseStartId(),push)},-];-/* 路由元数据的读法:路由树那一侧登记了的用它的(`ROUTE_META`),没有回落到 `ROUTES`;返回与 `matchRoute`- 同形的 `{route,params}`。按身份或侧栏键找入口路径时同样先查路由树、再查表:一个键只登记在一边。 */-const routeMeta=path=>{const meta=routeMetaOf(path);return meta?{route:meta,params:{}}:matchRoute(ROUTES,path)};-const routePathOf=(key,value)=>Object.keys(ROUTE_META).find(path=>ROUTE_META[path][key]===value)- ??ROUTES.find(spec=>spec[key]===value)?.match;+/* ── 路由元数据 ──+ 标题、侧栏键、管理区身份与「换一批」的行为全站只登记一处(`ROUTE_META`,`frontend/src/history/route-meta.ts`),+ 读者一律经 `routeMeta(path)`,返回 `{route}`;按身份或侧栏键找入口路径经 `routePathOf`。 */+const routeMeta=path=>{const meta=routeMetaOf(path);return meta?{route:meta}:null};+const routePathOf=(key,value)=>Object.keys(ROUTE_META).find(path=>ROUTE_META[path][key]===value);/* 目录:首页、三个筛选态、垃圾文件与回收站。路由树按匹配打开,画在 `#grid`,不是管理区。 */const catalogPage=path=>isCatalogPath(path)||path==='/trash';/* 画进 `#stats` 的那几页(管理区、播放列表页与关注页):路由树按匹配打开、又不随写回从头重开(索引页与资料页- 登记了 `reload: 'reopen'`,目录另判)。 */-const managedPagePath=path=>{const meta=routeMetaOf(path);return !!meta&&meta.reload!=='reopen'&&!catalogPage(path)};-/* 从侧栏、管理条进一屏。还归壳的那几屏按 `ROUTES` 打开。目录(管理条只通到回收站)认领写地址后从头重开。+ 登记了 `reload: 'reopen'`,目录另判;详情、队列与沉浸压在页面上,不算)。 */+const managedPagePath=path=>{+ const meta=routeMetaOf(path);+ return !!meta&&meta.reload!=='reopen'&&!catalogPage(path)&&!isOverlayPath(path)&&path!=='/immerse';+};+/* 从侧栏、管理条进一屏。沉浸模式由壳认领写地址、当场打开。目录(管理条只通到回收站)认领写地址后从头重开。索引页(侧栏只通到它们)退出选择模式、回到本地与字母表,同样认领写地址后从头重开。关注页分「回到」与「重新进入」(`enterFollow`);播放列表页认领写地址后从头重开,再点一次也一样。管理区换地址、交派发打开,再点一次同一页也是新的一次打开;关注管理回到第一页与默认排序,页签沿用地址上的那一档。 */const openRoutePath=path=>{- const hit=matchRoute(ROUTES,path);- if(hit){hit.route.open(hit.params,true);return}+ if(path==='/immerse'){void openTok(immerseStartId());return}if(path==='/follow'){enterFollow();return}if(path==='/playlists'||catalogPage(path)){openRoutedPage(path);return}if(!managedPagePath(path)){@@ -263,16 +221,14 @@ function waitEntityShapes(){});return Promise.race([entityShapesReady||=loadEntityShapes(),deadline]);}-/* 冷启动直接落在详情地址上:详情下面那份列表一次请求都没发过,由 `fillIdleCatalog` 补发一次。 */-let bootDetailDeepLink=false;function renderInitialSurfaceLoading(){const path=decodeURIComponent(location.pathname);- /* 骨架画的就是这个表面,所以先把 `data-surface` 写上:深链冷启动时 `restoreRoute()`- 排在这一步后面,等它写的话骨架会先按默认版式铺一遍,数据到货再跳成分栏。 */+ /* 骨架画的就是这个表面,所以先把 `data-surface` 写上:深链冷启动时壳开始路由排在这一步后面,+ 等它写的话骨架会先按默认版式铺一遍,数据到货再跳成分栏。 */document.body.dataset.surface=location.pathname;if(/^\/(item\/\d+|(?:mix|parts|editions|playlists)\/\d+\/\d+)$/.test(path)){- /* 详情的骨架归舞台岛:路由到位后 `openItem` 取回 React 包就画。下面那份列表照这一次补发。 */- hideDiscoveryBars();bootDetailDeepLink=true;return;+ /* 详情的骨架归舞台岛:路由到位后 `openItem` 取回 React 包就画。下面那份列表由路由树的目录元素补发。 */+ hideDiscoveryBars();return;}if(path.startsWith('/follow/item/')){/* 关注详情同样只等舞台浮窗里那份骨架,页面里不先铺一份;列表等关掉详情才画,不补发。 */@@ -326,7 +282,7 @@ function renderInitialSurfaceLoading(){const syncPageTitle=path=>{const url=new URL(path,location.origin);const pathname=decodeURIComponent(url.pathname);- const label=routeMetaOf(pathname)?.title||routeLabel(ROUTES,pathname);+ const label=routeMetaOf(pathname)?.title;document.title=label?`${label} · Peach`:'Peach · 蜜桃';document.body.dataset.surface=url.pathname;paintNav();@@ -382,17 +338,40 @@ const claimSurface=path=>{surfaceEpoch++;return surfaceToken(path)};/* 地址只经全站那一份历史写(`frontend/src/history/`,`@peach/history`),不直接调 `window.history`:React Router 读写的是同一个对象,绕过它写进去的条目它不知道。详情地址带上 `overlayState()`- 给的 `usr`(压在哪一页上),别的地址不带。`claim:false` 见 `navigatePath`。 */-const route=(path,replace=false,state,{claim=true}={})=>{+ 给的 `usr`(压在哪一页上),别的地址不带。认领写地址保持页面代次,覆盖元素接走一次性的打开请求。 */+const route=(path,replace=false,state)=>{surfaceEpoch++;barsRequestSeq++;- shellNavigate(path,{replace,state,claim});syncPageTitle(path);+ shellNavigate(path,{replace,state});syncPageTitle(path);queueMicrotask(()=>{syncHeaderActions();paintListTitle();paintSidebar();void syncPostSetupTutorial()});};-/* 换到一个路径、由派发器打开(页面里的 `actions.navigate`、教程卡的跳转):地址、标题与随后那一轮- 同步照 `route()` 做,只是这一次不认领。路由树像后退前进一样报给派发器、领一个开次代次:迁进路由树的页面由它的元素- 打开,其余由 `restoreRoute` 按 `ROUTES` 打开。 */-const navigatePath=path=>route(path,false,undefined,{claim:false});+/* 换到一个路径、由路由树按匹配打开(页面里的 `actions.navigate`、教程卡的跳转):不认领,像后退前进一样领一个+ 开次代次,标题、侧栏与教程状态由 `syncRouteChrome` 跟上,顶栏动作与列表标题随后补一轮。 */+const navigatePath=(path,replace=false,state)=>{+ if(replace)peachHistory.replace(path,state);else peachHistory.push(path,state);+ queueMicrotask(()=>{syncHeaderActions();paintListTitle()});+};+/* 点卡的参数只交给这一次覆盖元素打开,不放进浏览器条目(锚点是活节点)。认领写地址保住背景页的开次代次,+ 覆盖组按导航序号挂上,再取走这次请求;队列取齐后只写地址、在线条目转换详情种类的 replace 没有打开请求。 */+let requestedOverlay=null;+let requestedQueue=null;+let initialOverlayOpened=false;+function requestOverlay(path,kind,open){+ holdOverlayBackground();+ requestedOverlay={path,open};+ route(path,false,overlayState(kind));+}+/* 每一次没人认领的历史变化(后退前进、`navigatePath`、React 子树写的地址)之后:标题、侧栏、表面代次与教程状态+ 跟上当前地址,不接着上一次记下的详情背景(跳过几条落到别的详情上时那份背景不属于它;落到详情条目上时由路由树+ 的覆盖元素改接条目自己记的背景)。壳开始路由那一刻也跑一次。页面、沉浸与详情都由路由树按匹配打开。 */+function syncRouteChrome(){+ surfaceEpoch++;+ barsRequestSeq++;+ syncPageTitle(location.href);+ paintSidebar();+ clearOverlayBackground();+ void syncPostSetupTutorial();+}/* 从壳里进路由树按匹配打开的那几页(索引页、资料页):认领写地址,再让 `pageOpens` 加一。换了一页时挂上的元素按地址打开,两件事合成一次;地址落在画着的同一页上时元素不重挂,靠这一下从头重开。 */function openRoutedPage(path){@@ -2025,6 +2004,18 @@ const followFeedShell={},skeleton:()=>followSkeletonHtml('正在读取关注内容'),props:followFeedProps,+ /* 关注详情底下没画着列表(深链进来,或后退前进落到压在列表上的详情、中间去过别的页):让出 `#stats`,+ 不画列表,等关掉详情再按地址打开。关注详情已经开着(组内换条)就不动。 */+ ground:()=>{+ if(stageApi()?.showing()==='follow')return;+ releaseHoverPreviews();disposeStage(false);enterManagementSurface();+ if(followFeedLive())return;+ claimSurface(surfacePath());+ showManagementBody({manage:false});+ // 管理区那一页还挂在 `#stats` 上时先把它卸掉,直接清空会留下一棵管着已不在页面上的节点的根。+ if($('#stats').querySelector('.peach-react'))releaseManagedRoute($('#stats'));+ $('#stats').replaceChildren();+ },};/* 从侧栏、管理页与检查更新的回执进关注页。已经停在关注页再点一次侧栏,或检查更新之后去看(`fresh`),是「重新进入」:回到干净的 /follow、换一粒取样种子,列表从顶上重取。从别的页面过来是「回到」:筛选、取样种子、@@ -2059,6 +2050,11 @@ const followDetailActions={};async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=false){+ if(push){+ if(!location.pathname.startsWith('/follow/item/')&&!preserveReturn)writeShell({followDetailReturnPath:location.pathname+location.search});+ requestOverlay(`/follow/item/${+id}`,'follow',()=>openFollowDetail(id,false,mediaIndex,preserveReturn));+ return;+ }releaseHoverPreviews();id=+id;const entering=!location.pathname.startsWith('/follow/item/');@@ -2067,8 +2063,6 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=falsif(!push&&!preserveReturn)writeShell({followDetailReturnPath:takeOverlayReturn()||'/follow'});// 条目的背景另记:从列表进来记列表这一页(带筛选),组内换条沿用上一条的。if(push)holdOverlayBackground();- // 派发进来(启动、后退前进)时详情开着就是组里另一条:列表已在下面,详情原地换条。- if(!push&&!preserveReturn&&stageApi()?.showing()!=='follow')settleFollowDetailGround();// 换详情不进小窗;小窗里放着别的条目也让位(舞台岛判),两个播放器不同时出声。关注详情开着时原地换条。if(stageApi()?.showing()!=='follow')disposeStage(false,false,{miniplayer:false});if(push)route(`/follow/item/${id}`,false,overlayState('follow'));@@ -2077,18 +2071,6 @@ async function openFollowDetail(id,push=true,mediaIndex=null,preserveReturn=falshelpers:followFeedHelpers,actions:followDetailActions,resume:push?null:urlResume()});scheduleStickySurfaces();}-/* 派发进来的关注详情下面那一层:列表由路由树按条目记的背景画着就原样留着,返回时接着看。深链直接进来(或从- 别的页面后退前进过来)时下面没画着列表:详情岛自己取这一条,列表区只让出位置,关掉详情时才画。侧栏抽屉由- 详情画出来时按这一条的标签铺。 */-function settleFollowDetailGround(){- releaseHoverPreviews();disposeStage(false);enterManagementSurface();- if(followFeedLive())return;- claimSurface(surfacePath());- showManagementBody({manage:false});- // 管理区那一页还挂在 `#stats` 上时先把它卸掉,直接清空会留下一棵管着已不在页面上的节点的根。- if($('#stats').querySelector('.peach-react'))releaseManagedRoute($('#stats'));- $('#stats').replaceChildren();-}/* 关掉详情只是回到列表,不该重新取一遍。重取要等一个网络往返(慢),而且只会取回第一页——@@ -2100,7 +2082,7 @@ async function closeFollowDetail(){route(followDetailReturnPath||'/follow');/* 从资料页在线视图点进来的:资料页一直画在下面,筛选、已加载的几页与滚动位置原样接着看,不从头重开。 */if(entityPageView&&entityPageCurrent()&&!$('#index').hidden)return;- if(location.pathname!=='/follow'){await restoreRoute();return}+ if(location.pathname!=='/follow'){writeShell({pageOpens:pageOpens+1});return}if(!followFeedLive()){writeShell({pageOpens:pageOpens+1});return}readFollowView();pushFollowFeed({view:followView()});}@@ -3224,6 +3206,11 @@ function openQueue(kind,key,itemId,push,anchor=null){/* 队列地址取完数才推(`present`),背景按此刻记;同队列换条在详情地址上,沿用上一条的背景。 */if(push)holdOverlayBackground();const queue=kind==='playlist'?{kind,playlistId:key,fresh:true}:{kind,seedId:key,fresh:!same};+ if(push){+ requestedQueue=()=>openItem(itemId==null?null:+itemId,false,queue,anchor,true);+ writeShell({queueOpens:queueOpens+1});+ return;+ }return openItem(itemId==null?null:+itemId,false,queue,anchor,push);}function openMix(seedId,itemId=seedId,push=true,anchor=null){return openQueue('mix',seedId,itemId,push,anchor)}@@ -3239,21 +3226,6 @@ function hasReturnSurface(){return !!$('#grid').querySelector('[data-id],[data-mix-seed]')||!$('#index').hidden||!$('#stats').hidden;}-/* 同一张骨架的另一半问题:深链冷启动时列表一次请求都没发过,`renderInitialSurfaceLoading`- 占位的那张「正在读取作品」就停在详情下方,写着在读,其实没有任何请求在跑。这里把那- 一次请求补发出去:从列表里点进详情时下面就是那份列表,直接刷新详情页的地址也该有- 同样的东西,否则排序条底下是一整屏空白。- 走的是 `paintCatalogGrid` 直接挂网格那条路——`loadCatalog` 开头就 `disposeStage()`,- 会把刚打开的这一屏详情一起收掉。网格已经画上(哪怕还在取第一页)就不再补发;静态骨架留在- 原位,首屏落地时由 `revealRoutedPage` 淡出。 */-function fillIdleCatalog(){- const grid=$('#grid');- if(gridTaken())return;- const deepLink=bootDetailDeepLink;bootDetailDeepLink=false;- if(!grid.querySelector('.catalog-skeleton')&&!deepLink)return;- const count=$('#count');count.removeAttribute('aria-busy');count.removeAttribute('aria-label');- void paintCatalogGrid(surfaceToken(surfacePath()));-}/* 作品详情整块归舞台岛(`frontend/src/react/stage/`):条目与队列的取数、播放区、侧栏、接着看、写操作与播放器都在 /dist/peach-react.js 里。壳留来处:从哪一张卡进来、关掉回哪一份列表、顶栏换成哪条作品的上下文。@@ -3334,6 +3306,11 @@ const itemDetailActions={};async function openItem(id,push=true,queue=null,anchor=null,queuePush=false){+ if(push&&!queue){+ writeShell({detailReturnPath:location.pathname+location.search});+ requestOverlay('/item/'+(+id),'item',()=>openItem(id,false,null,anchor));+ return;+ }releaseHoverPreviews();id=id==null?null:+id;const origin=anchor?.isConnected?anchor:(detailOriginAnchor?.isConnected?detailOriginAnchor:null);@@ -3342,7 +3319,6 @@ async function openItem(id,push=true,queue=null,anchor=null,queuePush=false){: detailOriginAbove;const returnSurfaceReady=hasReturnSurface();const needsReturnRestore=detailReturnNeedsRestore||(!push&&!returnSurfaceReady);- if(!returnSurfaceReady)fillIdleCatalog();const returnBars=barsContext.type==='item'?detailReturnBarsContext:cloneBarsContext(currentBarsContext());/* 点进来记当前这一页;后退前进进来按条目记的来处,条目没记(冷启动、深链)就沿用上一次记的。队列从详情里换条也以 push=false 进来(`queuePush`),来处已由 `openQueue` 定好,不在这里取。 */@@ -3377,10 +3353,10 @@ async function closeItemDetail(){await stageExit();disposeStage(false,false,{miniplayer:false});writeShell({detailReturnBarsContext:null});clearOverlayBackground();writeShell({barsContext:restore||{type:'home',filters:state}});- /* 下面没有那一屏、要照地址重建时,路由树按匹配打开的管理区经派发重开(领一个开次代次),其余由 `restoreRoute` 打开。 */+ /* 下面没有那一屏、要照地址重建时,管理区不认领写地址、领一个开次代次重开,其余认领写地址后要路由树从头重开。 */if(restoreSurface&&managedPagePath(new URL(returnPath,location.href).pathname)){navigatePath(returnPath);return}route(returnPath);- if(restoreSurface)await restoreRoute();+ if(restoreSurface)writeShell({pageOpens:pageOpens+1});// 播放列表页回来就从头重开、取最新的那一份(详情里可能刚加进或移出了一条)。else{buildBars();if(location.pathname==='/playlists')writeShell({pageOpens:pageOpens+1})}}@@ -3404,9 +3380,10 @@ const immerseHost={failure:(action,error)=>actionFailure(action,error),};const immerseOpen=()=>!!immerseApi()?.isOpen();+let requestedImmerseId;/* 小窗开着时打开沉浸模式先关小窗:两个播放器不同时出声。 */async function openTok(startId=null,push=true){- if(push)route('/immerse');+ if(push){requestedImmerseId=startId;route('/immerse');return}stageApi()?.closeMiniplayer();await (await loadImmerse(immerseHost)).open(startId);}@@ -3534,16 +3511,13 @@ async function refreshAll(automatic=false){if(!$('#stats').hidden){/* 管理区的换批行为写在路由元数据的 `refresh` 上:`reopen` 重开自己,`skip` 不参与(追更页重画要联网,只能由它自己的按钮触发),- 没写的(统计、数据管理、资源同步)落到统计页。播放列表页画着就只重读(`rereadPlaylists`);还归壳的- 那几屏按 `ROUTES` 重开;路由树按匹配打开的那几页原地改写一次不认领的地址,领一个新的开次代次,页面元素- 换一次 key 重开,历史条数不变。 */+ 没写的(统计、数据管理、资源同步)落到统计页。播放列表页画着就只重读(`rereadPlaylists`);别的页原地+ 改写一次不认领的地址,领一个新的开次代次,页面元素换一次 key 重开,历史条数不变。 */const path=decodeURIComponent(location.pathname),refresh=routeMeta(path)?.route.refresh;if(refresh==='skip')return;if(path==='/playlists'){rereadPlaylists();return}const target=refresh==='reopen'?path:'/stats';- const hit=matchRoute(ROUTES,target);- if(hit){await hit.route.open(hit.params,false);return}- if(target===path)route(location.pathname+location.search+location.hash,true,peachHistory.navigation.location.state,{claim:false});+ if(target===path)navigatePath(location.pathname+location.search+location.hash,true,peachHistory.navigation.location.state);else navigatePath(target);return;}@@ -3599,32 +3573,6 @@ function immerseStartId(){return /^\d+$/.test(id||'')?Number(id):undefined;}-/* `origin` 由 `startRouting` 给:启动那一次是 'boot',后退前进是 'history';壳自己写完地址再调时不给。 */-async function restoreRoute(origin){- // 路由树里按匹配打开的页面等这一下才开始打开:壳的状态到这时才齐。- if(origin==='boot')writeShell({pageOpens:1});- surfaceEpoch++;- barsRequestSeq++;- syncPageTitle(location.href);- paintSidebar();- /* 不接着上一次记下的详情背景:跳过几条落到别的详情上时,那份背景不属于它。后退前进落到详情条目上- 时改接条目自己记的背景与来处;启动不读,刷新、深链落在详情上照旧补画目录网格、关掉回缺省来处。 */- clearOverlayBackground();- if(origin==='history')adoptOverlayState(peachHistory.navigation.location.state);- const path=decodeURIComponent(location.pathname);- void syncPostSetupTutorial();- /* 唯一的派发点:路径匹配哪条路由,就把那一屏打开。`push=false`——地址栏本来- 就是它,再 `route()` 一次会往历史里塞一条重复记录。- 路由树登记的管理区、索引页、资料页与目录不在 `ROUTES` 里,由它们的页面元素按匹配打开;- 首页上的 `?state=ads` 由目录元素改写成垃圾文件的地址。 */- const hit=matchRoute(ROUTES,path);- if(hit)await hit.route.open(hit.params,false);- /* 索引页、资料页与目录由路由树按匹配打开:后退前进与启动时元素自己开;壳直接调来重开当前地址时要它从头再开。 */- else if(routeMetaOf(path)?.reload==='reopen'||catalogPage(path)){if(!origin)writeShell({pageOpens:pageOpens+1})}- /* 播放列表页与关注页同样由路由树按匹配打开,壳直接调来时同样要它按当前地址再开一次。 */- else if(path==='/playlists'||path==='/follow'){if(!origin)writeShell({pageOpens:pageOpens+1})}- else if(!managedPagePath(path)){showHomeSurfaces();disposeStage(false)}-}/* 左侧导航、管理条、页面标题和面包屑只认 location 和本地设置,一个请求都不等。挂在下面那条链上时它们排在 /api/sources 和 /api/facets 后面,实测让骨架先顶着一个没有标题的空壳站了约半秒。左侧导航先由 mountSidebar() 同步铺好骨架,@@ -3632,8 +3580,8 @@ async function restoreRoute(origin){entityShapesReady=loadEntityShapes();renderInitialSurfaceLoading();mountSidebar();-/* 后退前进由 React Router 派发给 restoreRoute(`startRouting`),跟侧栏搭同一次 React 包请求。- 管理区那几页由路由树画,经这一组回到壳(`frontend/src/react/router/shell-actions.ts`)。 */+/* 客户端导航跟侧栏搭同一次 React 包请求。每一页、沉浸与详情都由路由树按匹配打开,经这一组回到壳+ (`frontend/src/react/router/shell-actions.ts`)。 */const shellActions={openItem:id=>void openItem(id),openEntity:(kind,name)=>void openEntity(kind,name),@@ -3686,8 +3634,28 @@ const shellActions={enterManagementSurface();showManagementBody({manage:kind==='management'});},clearSearch:()=>clearSearchField(),- openImmerse:id=>void openTok(id,false),- closeStage:()=>disposeStage(false),+ openImmerse:id=>{+ const start=requestedImmerseId===undefined?id:requestedImmerseId;+ requestedImmerseId=undefined;void openTok(start,false);+ },+ openQueueRequest:()=>{+ const open=requestedQueue;requestedQueue=null;+ if(open)void open();+ },+ /* 覆盖地址要打开的那一条(作品详情、关注详情、四种队列),地址栏已经是它。 */+ openOverlay:target=>{+ const requested=requestedOverlay;+ requestedOverlay=null;+ if(peachHistory.navigation.claimed&&(!bootEntry()||initialOverlayOpened)){+ if(requested?.path===location.pathname)void requested.open();+ return;+ }+ if(bootEntry())initialOverlayOpened=true;+ if(target.kind==='item')void openItem(target.id,false);+ else if(target.kind==='follow')void openFollowDetail(target.id,false);+ else void openQueue(target.queue,target.key,target.item,false);+ },+ closeStage:()=>{if(stageOpen())disposeStage(false)},grid:{helpers:gridHelpers,actions:gridActions},// 索引页与资料页的元素用。@@ -3727,14 +3695,10 @@ const shellActions={/* 地址上没写来源时的缺省:本地加 115,离线的那一处摘掉。 */defaultLoc:()=>onlineDefaultLoc('local,115'),/* 整页打开:筛选已由目录元素照地址写进 `state`。`retitle` 是首页 `?state=ads` 改写成垃圾文件地址的那一下:- 改写认领了,没经过派发,标题、侧栏与教程状态在这里补;`entering` 是从别处回到首页,顶部三层的缓存作废。+ 改写认领了,标题、侧栏与教程状态在这里补;`entering` 是从别处回到首页,顶部三层的缓存作废。回收站清掉搜索框,别的页把地址上的搜索词摆回框里。 */open:(path,{entering=false,retitle=false}={})=>{- if(retitle){- surfaceEpoch++;barsRequestSeq++;- syncPageTitle(location.href);paintSidebar();clearOverlayBackground();- syncHeaderActions();paintListTitle();void syncPostSetupTutorial();- }+ if(retitle){syncRouteChrome();syncHeaderActions();paintListTitle()}if(entering)dropBars();if(path==='/trash'){clearSearchField();showHomeSurfaces()}else{$('#q').value=state.q;rememberSearchValue()}@@ -3742,10 +3706,23 @@ const shellActions={},/* 壳认领写了地址、筛选已在 `state` 里:只重取。 */load:()=>{handOff(loadCatalog())},+ /* 没有背景的作品与队列地址(深链、刷新):详情下面那份列表一次请求都没发过,补发一次,不留一张写着在读、+ 其实没有请求在跑的骨架。走 `paintCatalogGrid` 直接挂网格:`loadCatalog` 开头就 `disposeStage()`,会把这一屏+ 详情一起收掉。网格已经画上(哪怕还在取第一页)就不再补发;不是启动那一条时只接着那张骨架。 */+ fill:()=>{+ if(gridTaken())return;+ if(!bootEntry()&&!$('#grid').querySelector('.catalog-skeleton'))return;+ const count=$('#count');count.removeAttribute('aria-busy');count.removeAttribute('aria-label');+ void paintCatalogGrid(surfaceToken(surfacePath()));+ },/* 离开目录:收起网格、首页新作行与处理横幅。 */release:()=>{clearCatalogGrid();clearHomeFeed();releaseManagedRoute($('#libraryProcessingNotice'))},},};+/* 壳开始路由之前(来源、设置与形状名单读齐之前)没人认领的变化不跟:开始那一刻按当时的地址跑一次。+ 订阅排在路由树之前,同一次变化里这一轮先跑,页面再按匹配打开。 */+let routing=false;+peachHistory.listen(navigation=>{if(routing&&!navigation.claimed)queueMicrotask(syncRouteChrome)});loadRouter(shellActions).catch(error=>console.error('客户端导航装载失败',error));mountManageHeader();mountBatchDock();@@ -3754,7 +3731,12 @@ buildManageBar();结果没人看,却排在这一页自己的数据前面。 */Promise.all([loadSourceStatus(),loadSyncedSettings(),entityShapesReady]).then(()=>wantsDiscoveryBars()?buildBars():null)- .then(async()=>{syncNavigation();wireAllDrag();await startRouting(restoreRoute);scheduleStickySurfaces()});+ .then(()=>{+ syncNavigation();wireAllDrag();+ // 路由树里按匹配打开的页面等这一下才开始打开:壳的状态到这时才齐。+ routing=true;writeShell({pageOpens:1});syncRouteChrome();+ scheduleStickySurfaces();+ });;(()=>{/* Board 外壳:媒体库选择、侧栏底部、玻璃折射。 */diff --git a/web/js/routes.js b/web/js/routes.jsdeleted file mode 100644index ca3da2390..000000000--- a/web/js/routes.js+++ /dev/null@@ -1,62 +0,0 @@-/* 路由匹配:路径字符串进、参数出。不碰 DOM,也不认识任何一个页面函数。-- 「这个路径是哪一屏」只在这张表里声明一次。散成七份的话——`restoreRoute()` 一条- 二十五分支的 if 链,加上 `navTo`/`navOn`/`openManage`/`manageSection`/- `reloadCurrentSurface`/`refreshAll` 各自关心的那几条——加一屏要改七处,- 漏一处的症状各不相同:URL 能进但侧栏不亮、点进去了但换一批把你扔回统计页、- 批量操作后回到首页而不是刚才那一屏。真实踩过的就有抽屉漏了追更和播放列表那次。-- 现在只有一张 ROUTES 表(在 app.js 里,因为它要引用各个 `open*`),匹配与取参- 这段纯逻辑放在这里,可以单独读、单独测。-- `match` 的写法只有三种,故意不上正则——路由是给人读的清单,不是模式语言:-- - `'/stats'`:精确路径。- - `'/item/:id'`:`:name` 吃掉一段,且只吃数字。这一条由 `match` 统一判,不让每条动态路由各写一遍- `/^\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) || '');-}