Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(web): 撤回非覆盖导航中尚未取齐的队列请求

longmeidao632bb74f2daf
diff --git a/frontend/e2e/item-detail.test.ts b/frontend/e2e/item-detail.test.ts
index c1689b6ec..8e1bb45c7 100644
--- a/frontend/e2e/item-detail.test.ts
+++ b/frontend/e2e/item-detail.test.ts
@@ -10,11 +10,12 @@ import { after, before, describe, it } from 'node:test';
import type { Browser, Page } from 'playwright-core';
import { layout, launch, VIEWPORTS } from './harness.ts';
-import { ITEM, NAMES, PLAYLIST, RELATED, openItemPage } from './item-fixture.ts';
+import { CATALOG, ITEM, NAMES, PLAYLIST, RELATED, openItemPage } from './item-fixture.ts';
const DESKTOP = VIEWPORTS.find((viewport) => !viewport.mobile)!;
const MOBILE = VIEWPORTS.find((viewport) => viewport.mobile)!;
const DETAIL_READY = '#stage[open] [data-item-side]';
+const PART_CARD = `#grid [data-media-card][data-id="${ITEM.part}"] [data-media-title]`;
/** 桩里的片源没有正片,播放器拿到空响应会报一条 VIDEOJS 错误;量的不是它。 */
const withoutPlayer = (problems: string[]) => problems.filter((line) => !line.includes('VIDEOJS'));
const pathIs = (page: Page, path: string) => page.waitForFunction(
@@ -50,6 +51,99 @@ describe('作品详情岛', () => {
await browser.close();
});
+ for (const destination of ['/activity', '/performers']) {
+ it(`分卷等待响应时后退到 ${destination}:舞台撤回,晚到的响应不能改变地址或历史深度`, { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, '/', DESKTOP, { ready: PART_CARD, catalogIds: [...CATALOG, ITEM.part] });
+ let release = () => {};
+ try {
+ const page = opened.page;
+ await page.evaluate(async (path) => {
+ const moduleUrl = '/dist/peach-ui.js';
+ const { peachHistory } = await import(moduleUrl);
+ peachHistory.push(path);
+ }, destination);
+ await pathIs(page, destination);
+ await page.evaluate(async () => { const moduleUrl = '/dist/peach-ui.js'; (await import(moduleUrl)).peachHistory.push('/') });
+ await page.locator(PART_CARD).waitFor();
+ const depth = await page.evaluate(() => history.length);
+ let arrived = () => {};
+ const requested = new Promise<void>(resolve => { arrived = resolve });
+ const gate = new Promise<void>(resolve => { release = resolve });
+ let finished = () => {};
+ const responded = new Promise<void>(resolve => { finished = resolve });
+ await page.route((url) => url.pathname === '/api/parts', async route => {
+ arrived();
+ await gate;
+ try { await route.fallback() }
+ catch (error) { assert.match(route.request().failure()?.errorText || '', /ERR_ABORTED/, String(error)) }
+ finally { finished() }
+ });
+ await page.locator(PART_CARD).click();
+ await requested;
+ await page.locator('#stage[open]').waitFor();
+ assert.equal(await page.evaluate(() => location.pathname), '/');
+ assert.equal(await page.evaluate(() => history.length), depth, '队列未取齐时没有临时历史条目');
+ await page.goBack();
+ await pathIs(page, destination);
+ await page.waitForFunction(() => !document.querySelector('#stage[open]'));
+ const seq = await page.evaluate(async () => { const moduleUrl = '/dist/peach-ui.js'; return (await import(moduleUrl)).peachHistory.navigation.seq });
+ release();
+ await responded;
+ await page.waitForTimeout(500);
+ assert.equal(await page.locator('#stage[open]').count(), 0);
+ assert.equal(await page.evaluate(() => location.pathname), destination);
+ assert.equal(await page.evaluate(() => history.length), depth);
+ assert.equal(await page.evaluate(async () => { const moduleUrl = '/dist/peach-ui.js'; return (await import(moduleUrl)).peachHistory.navigation.seq }), seq);
+ assert.deepEqual(opened.stub.writes, []);
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally { release(); await opened.close() }
+ });
+ }
+
+ it('点分卷的同一任务里重放源页 POP:队列意图不取数、不铺舞台、不写条目', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, '/', DESKTOP, { ready: PART_CARD, catalogIds: [...CATALOG, ITEM.part] });
+ try {
+ const page = opened.page;
+ const depth = await page.evaluate(() => history.length);
+ await page.locator(PART_CARD).evaluate(node => {
+ (node as HTMLElement).click();
+ window.dispatchEvent(new PopStateEvent('popstate', { state: history.state }));
+ });
+ await page.waitForTimeout(500);
+ assert.equal(opened.stub.reads.get('/api/parts') || 0, 0);
+ assert.equal(await page.locator('#stage[open]').count(), 0);
+ assert.deepEqual(await page.evaluate(() => [location.pathname, history.length]), ['/', depth]);
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally { await opened.close() }
+ });
+
+ it('首次舞台宿主接上时重放源页 POP:包已到货的旧队列请求也不能开舞台', { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, '/', DESKTOP, { ready: PART_CARD, catalogIds: [...CATALOG, ITEM.part] });
+ try {
+ const page = opened.page;
+ assert.equal(await page.locator('[data-stage-host]').count(), 0);
+ const depth = await page.evaluate(() => history.length);
+ await page.evaluate(() => {
+ const append = document.body.append.bind(document.body);
+ document.body.append = (...nodes: (Node | string)[]) => {
+ append(...nodes);
+ if (nodes.some(node => node instanceof HTMLElement && node.hasAttribute('data-stage-host'))) {
+ document.body.append = append;
+ document.body.dataset.queueStagePop = '1';
+ window.dispatchEvent(new PopStateEvent('popstate', { state: history.state }));
+ }
+ };
+ });
+ await page.locator(PART_CARD).click();
+ await page.locator('body[data-queue-stage-pop]').waitFor({ state: 'attached' });
+ await page.waitForTimeout(500);
+ assert.equal(opened.stub.reads.get('/api/parts') || 0, 0);
+ assert.equal(await page.locator('#stage[open]').count(), 0);
+ assert.deepEqual(await page.evaluate(() => [location.pathname, history.length]), ['/', depth]);
+ assert.deepEqual(withoutPlayer(opened.problems), []);
+ } finally { await opened.close() }
+ });
+
it('目录点卡进详情:地址换成这一条;关掉回列表不重取', { timeout: 60_000 }, async () => {
const opened = await openItemPage(browser, '/', DESKTOP, { ready: `#grid [data-media-card][data-id="${ITEM.plain}"]` });
try {
diff --git a/frontend/e2e/item-fixture.ts b/frontend/e2e/item-fixture.ts
index 60d50bf89..8191709dc 100644
--- a/frontend/e2e/item-fixture.ts
+++ b/frontend/e2e/item-fixture.ts
@@ -83,7 +83,7 @@ export interface ItemStub {
const body = (request: Request) => JSON.parse(request.postData() || '{}') as Record<string, unknown>;
-async function stub(page: Page): Promise<ItemStub> {
+async function stub(page: Page, catalogIds: readonly number[] = CATALOG): Promise<ItemStub> {
const state: ItemStub = { writes: [], reads: new Map() };
const read = (path: string) => state.reads.set(path, (state.reads.get(path) || 0) + 1);
const playlists = new Map<number, { id: number; name: string; ids: number[]; current: number | null }>([
@@ -101,7 +101,7 @@ async function stub(page: Page): Promise<ItemStub> {
return route.fulfill({ json: respond(new URL(request.url()), request) });
});
await json('/api/item', (url) => DETAILS.get(Number(url.searchParams.get('id'))) || { error: '这一条已不在账本里' });
- await json('/api/items', () => ({ items: CATALOG.map(card), total: CATALOG.length, has_more: false }));
+ await json('/api/items', () => ({ items: catalogIds.map(card), total: catalogIds.length, has_more: false }));
await json('/api/related', () => ({ items: RELATED.map(card) }));
await json('/api/parts', () => PARTS);
await json('/api/editions', () => EDITIONS);
@@ -168,14 +168,16 @@ export interface ItemVisit extends Visit {
/** 打开一页:桩与设置装好之后重新载入,等到 `ready` 出现、等待态结束。 */
export async function openItemPage(browser: Browser, path: string, viewport: Viewport,
- { settings = {}, ready = '#stage[open] [data-item-side]' }: { settings?: Record<string, unknown>; ready?: string } = {},
+ { settings = {}, ready = '#stage[open] [data-item-side]', catalogIds }: {
+ settings?: Record<string, unknown>; ready?: string; catalogIds?: readonly number[];
+ } = {},
): Promise<ItemVisit> {
const opened = await visit(browser, '/', viewport);
const page = opened.page;
await page.context().addInitScript((value) => {
localStorage.setItem('peach.settings.v1', JSON.stringify(value));
}, { detailAutoplay: false, relatedLimit: 12, ...settings });
- const stubbed = await stub(page);
+ const stubbed = await stub(page, catalogIds);
await page.goto(new URL(path, page.url()).toString(), { waitUntil: 'load' });
await page.locator(ready).first().waitFor({ timeout: 15_000 });
await settle(page);
diff --git a/web/app.js b/web/app.js
index a4a43426c..794b26a1d 100644
--- a/web/app.js
+++ b/web/app.js
@@ -355,8 +355,15 @@ const navigatePath=(path,replace=false,state)=>{
覆盖组按导航序号挂上,再取走这次请求;队列取齐后只写地址、在线条目转换详情种类的 replace 没有打开请求。 */
let requestedOverlay=null;
let requestedQueue=null;
+let queueOpenRequest=null;
let initialOverlayOpened=false;
+function cancelQueueRequest(){
+ if(queueOpenRequest)queueOpenRequest.cancelled=true;
+ queueOpenRequest=null;requestedQueue=null;
+ writeShell({pendingQueueRoute:null});
+}
function requestOverlay(path,kind,open){
+ cancelQueueRequest();
holdOverlayBackground();
requestedOverlay={path,open};
route(path,false,overlayState(kind));
@@ -904,7 +911,8 @@ function urlResume(){
function stageExit(){return stageApi()?.exit()||Promise.resolve()}
/* 离开详情。正在放的视频默认进小窗接着放;显式关闭(叉、Escape)、换成别的详情和删掉当前条目
都传 miniplayer:false。 */
-function disposeStage(push=false,preserveInlineOrigin=false,{miniplayer=true}={}){
+function disposeStage(push=false,preserveInlineOrigin=false,{miniplayer=true,preserveQueueRequest=null}={}){
+ if(queueOpenRequest!==preserveQueueRequest)cancelQueueRequest();
stageApi()?.dispose({miniplayer});
writeShell({activeQueue:null,pendingQueueRoute:null,presentedItem:null});
if(!preserveInlineOrigin){
@@ -3207,7 +3215,9 @@ function openQueue(kind,key,itemId,push,anchor=null){
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);
+ cancelQueueRequest();
+ const request=queueOpenRequest={seq:peachHistory.navigation.seq,cancelled:false};
+ requestedQueue=()=>openItem(itemId==null?null:+itemId,false,queue,anchor,true,request);
writeShell({queueOpens:queueOpens+1});
return;
}
@@ -3253,7 +3263,7 @@ const itemDetailActions={
const returnBars=detailReturnBarsContext;
writeShell({barsContext:{type:'item',id:item.id,filters:returnBars?.type==='entity'
? {...returnBars.filters}:emptyEntityFilters()}});
- if(pendingQueueRoute){route(`${pendingQueueRoute}/${item.id}`,false,overlayState('item'));writeShell({pendingQueueRoute:null})}
+ if(pendingQueueRoute){queueOpenRequest=null;route(`${pendingQueueRoute}/${item.id}`,false,overlayState('item'));writeShell({pendingQueueRoute:null})}
buildBars();
},
/* 取数时发现要换去别处:保存过的在线资产转关注详情,队列取不到退回普通详情,播放列表空了
@@ -3305,7 +3315,9 @@ const itemDetailActions={
failure:(action,error)=>actionFailure(action,error),
};
-async function openItem(id,push=true,queue=null,anchor=null,queuePush=false){
+async function openItem(id,push=true,queue=null,anchor=null,queuePush=false,queueRequest=null){
+ if(queueRequest?.cancelled)return;
+ if(!queueRequest)cancelQueueRequest();
if(push&&!queue){
writeShell({detailReturnPath:location.pathname+location.search});
requestOverlay('/item/'+(+id),'item',()=>openItem(id,false,null,anchor));
@@ -3328,7 +3340,7 @@ async function openItem(id,push=true,queue=null,anchor=null,queuePush=false){
if(push)holdOverlayBackground();
/* 换详情不进小窗;小窗里放着别的条目也让位(舞台岛判),两个播放器不同时出声。作品详情开着时
(队列换卷、相关作品)舞台原地换条,不拆。 */
- if(stageApi()?.showing()!=='item')disposeStage(false,true,{miniplayer:false});
+ if(stageApi()?.showing()!=='item')disposeStage(false,true,{miniplayer:false,preserveQueueRequest:queueRequest});
writeShell({detailOriginAnchor:origin,detailOriginAbove:above,detailReturnNeedsRestore:needsReturnRestore});
writeShell({detailReturnBarsContext:returnBars});
writeShell({activeQueue:queue&&{kind:queue.kind,seedId:queue.seedId,playlistId:queue.playlistId}});
@@ -3336,9 +3348,14 @@ async function openItem(id,push=true,queue=null,anchor=null,queuePush=false){
? `${QUEUE_ROUTES[queue.kind]}/${queue.kind==='playlist'?queue.playlistId:queue.seedId}`:null});
if(push&&!queue)route('/item/'+id,false,overlayState('item'));
const stage=await loadStage(stageHost);
+ if(queueRequest?.cancelled)return;
+ const actions=queueRequest?{...itemDetailActions,
+ present:(item,queue)=>{if(!queueRequest.cancelled)itemDetailActions.present(item,queue)},
+ redirect:to=>{if(!queueRequest.cancelled)itemDetailActions.redirect(to)},
+ }:itemDetailActions;
await stage.open({kind:'item',
id,queue,relatedLimit:appSettings.relatedLimit>0?+appSettings.relatedLimit:0,
- helpers:itemDetailHelpers,actions:itemDetailActions,
+ helpers:itemDetailHelpers,actions,
grid:{helpers:gridHelpers,actions:gridActions},
layout:catalogGridLayout(),selectMode,selected:new Set(selected),seekSeconds:appSettings.seekSeconds,
resume:push||id==null?null:urlResume(),
@@ -3722,7 +3739,11 @@ const shellActions={
/* 壳开始路由之前(来源、设置与形状名单读齐之前)没人认领的变化不跟:开始那一刻按当时的地址跑一次。
订阅排在路由树之前,同一次变化里这一轮先跑,页面再按匹配打开。 */
let routing=false;
-peachHistory.listen(navigation=>{if(routing&&!navigation.claimed)queueMicrotask(syncRouteChrome)});
+peachHistory.listen(navigation=>{
+ /* 取齐前地址仍在源页:任何非覆盖历史变化(包括同地址 POP)都撤回这一趟,晚到的包或响应不能再开舞台。 */
+ if(queueOpenRequest&&navigation.seq!==queueOpenRequest.seq&&!isOverlayPath(navigation.location.pathname))disposeStage(false);
+ if(routing&&!navigation.claimed)queueMicrotask(syncRouteChrome);
+});
loadRouter(shellActions).catch(error=>console.error('客户端导航装载失败',error));
mountManageHeader();
mountBatchDock();