Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(web): 清理应用卸载的页面请求和常驻辅助资源

longmeidao84d0b01332b4
diff --git a/frontend/src/history/index.ts b/frontend/src/history/index.ts
index dc1082a6c..5c644f55c 100644
--- a/frontend/src/history/index.ts
+++ b/frontend/src/history/index.ts
@@ -113,6 +113,6 @@ export {
export { ROUTE_META, routeMetaOf, type RouteMeta } from './route-meta';
export {
connectManagedRoutes, failManagedRoute, listenManagedEntry, managedEntries, managedEntry, managedTaken, openManagedRoute,
- openResidentSurface, preloadManagedRoutes, releaseManagedRoute, updateManagedRoute,
+ openResidentSurface, preloadManagedRoutes, releaseAllManagedRoutes, releaseManagedRoute, updateManagedRoute,
type ManagedEntry, type ManagedOpenOptions, type ManagedPrefetch,
} from './managed';
diff --git a/frontend/src/history/managed.ts b/frontend/src/history/managed.ts
index 0bb795cf6..70fa76bf8 100644
--- a/frontend/src/history/managed.ts
+++ b/frontend/src/history/managed.ts
@@ -184,6 +184,12 @@ export function releaseManagedRoute(container: Element, ...more: Element[]): voi
for (const shown of removed) if (!shown.resident) shown.host.remove();
}
+/** 应用卸载收起全部登记,并中止尚未成为页面的首屏请求。 */
+export function releaseAllManagedRoutes(): void {
+ const [first, ...rest] = new Set([...entries.keys(), ...pending.keys()]);
+ if (first) releaseManagedRoute(first, ...rest);
+}
+
/** 某一面渲染抛错、路由树的错误边界接住之后调:只撤这一面的登记与宿主,别的面照画。之后
* `managedTaken` 回 false、`updateManagedRoute` 对它是空操作,壳下一次打开就重开。代次对不上(这一格
* 已经收起或重开过)是空操作:过期的那一面不能撤掉壳刚开的新一面。常驻面的宿主是壳的节点,只卸组件、
diff --git a/frontend/src/query/media-sources.ts b/frontend/src/query/media-sources.ts
index 073166f85..4ae9994cc 100644
--- a/frontend/src/query/media-sources.ts
+++ b/frontend/src/query/media-sources.ts
@@ -33,11 +33,15 @@ const stopped = (error: unknown) => (error as { name?: unknown } | null)?.name =
* 查询函数不读 Query 交给它的 `signal`:读了它,页面上最后一个观察者卸载时 Query 会撤回这一趟,
* 壳拿到的是上一份旧数据。同时在途的同一请求由 Query 合并成一次;合并上的若是页面那一趟,
* 它带着页面自己的 `signal`,页面中止时这一趟以中止收场,壳就自己再发一次。 */
-export async function loadMediaSources(): Promise<MediaSourcesData> {
- const fetchOnce = () => queryClient.fetchQuery({ queryKey: MEDIA_SOURCES_KEY, queryFn: () => fetchMediaSources() });
+export async function loadMediaSources(signal?: AbortSignal): Promise<MediaSourcesData> {
+ signal?.throwIfAborted();
+ const fetchOnce = () => queryClient.fetchQuery({ queryKey: MEDIA_SOURCES_KEY, queryFn: () => fetchMediaSources(signal) });
try {
- return await fetchOnce();
+ const data = await fetchOnce();
+ signal?.throwIfAborted();
+ return data;
} catch (error) {
+ signal?.throwIfAborted();
if (!stopped(error)) throw error;
return await fetchOnce();
}
diff --git a/frontend/src/react/toaster.tsx b/frontend/src/react/toaster.tsx
index 45ee47cf8..f0d234cc5 100644
--- a/frontend/src/react/toaster.tsx
+++ b/frontend/src/react/toaster.tsx
@@ -5,7 +5,7 @@
* `web/css/17-overlay.css` 的 `#toasts` 一节。宿主不带 `.peach-react`:那一层的 Preflight 会把
* Sonner 自己的按钮样式清掉,而这里用到的 Board token 本来就挂在 `:root` 上。 */
import type { CSSProperties } from 'react';
-import { createRoot } from 'react-dom/client';
+import { createRoot, type Root } from 'react-dom/client';
import { Toaster, toast } from 'sonner';
import type * as Bundle from './bundle';
@@ -16,14 +16,23 @@ const glyph = (html: string, draw: boolean) => (
<span data-toast-glyph={draw ? 'draw' : 'still'} aria-hidden="true" dangerouslySetInnerHTML={{ __html: html }} />
);
-let mounted = false;
+let mounted: { host: Element; root: Root } | null = null;
+
+/** 应用卸载时撤下 Sonner 的订阅与计时;同一宿主之后可重新挂载。 */
+export function unmountToaster(): void {
+ const current = mounted;
+ mounted = null;
+ current?.root.unmount();
+}
export const mountToaster: typeof Bundle.mountToaster = (host, icons) => {
- if (mounted) return;
- mounted = true;
+ if (mounted?.host === host) return;
+ unmountToaster();
+ const root = createRoot(host);
+ mounted = { host, root };
/* 底边读 `--toast-bottom`:教程卡在右下角时,遗留层把它写成卡上沿之上的位置;没写就是
Sonner 的默认边距。宽度和教程卡同宽,两块叠在一列里左右对齐。 */
- createRoot(host).render(
+ root.render(
<Toaster position="bottom-right" closeButton gap={8}
style={{ '--width': '400px' } as CSSProperties}
offset={{ right: 24, bottom: 'var(--toast-bottom, 24px)' }}
diff --git a/frontend/src/ui-kit/middle-truncate.ts b/frontend/src/ui-kit/middle-truncate.ts
index b9f0a5135..fcd38d372 100644
--- a/frontend/src/ui-kit/middle-truncate.ts
+++ b/frontend/src/ui-kit/middle-truncate.ts
@@ -12,8 +12,10 @@ const segmenter=typeof Intl.Segmenter==='function'
? new Intl.Segmenter(undefined,{granularity:'grapheme'})
: null;
const states=new WeakMap<Element,TruncateState>();
-const observed=new WeakSet<Element>();
+let observed=new WeakSet<Element>();
let resizeObserver:ResizeObserver|null=null;
+let disposeTruncation:(()=>void)|null=null;
+let tracked=new Set<Element>();
const graphemes=(value:unknown)=>segmenter
? [...segmenter.segment(String(value??''))].map(part=>part.segment)
@@ -95,6 +97,7 @@ const bind=(element:Element)=>{
if(!states.has(element))states.set(element,{full:element.textContent||'',rendered:element.textContent||'',raf:0});
if(!observed.has(element)){
observed.add(element);
+ tracked.add(element);
/* 按父级量的元素跟着父级的尺寸重算:它自己的盒子只会随文字变,不会随窗口变。 */
if(element.dataset.middleTruncateWithin!==undefined&&element.parentElement)resizeObserver?.observe(element.parentElement);
else resizeObserver?.observe(element);
@@ -109,13 +112,20 @@ const scan=(node:Node)=>{
element.querySelectorAll('[data-middle-truncate]').forEach(bind);
};
-function initMiddleTruncate(root:Document|Element=document):void{
+function initMiddleTruncate(root:Document|Element=document):()=>void{
+ disposeTruncation?.();
+ observed=new WeakSet<Element>();tracked=new Set<Element>();
+ const elements=tracked;
+ let live=true;
resizeObserver=new ResizeObserver(entries=>entries.forEach(entry=>{
+ if(!live)return;
schedule(entry.target);
entry.target.querySelectorAll?.(':scope>[data-middle-truncate-within]').forEach(schedule);
}));
+ const resize=resizeObserver;
scan((root as Document).documentElement||root);
const mutations=new MutationObserver(records=>records.forEach(record=>{
+ if(!live)return;
record.addedNodes.forEach(scan);
const element=record.target.nodeType===Node.TEXT_NODE?record.target.parentElement:record.target as Element;
const target=element?.closest?.('[data-middle-truncate]') as HTMLElement|null|undefined;
@@ -128,8 +138,8 @@ function initMiddleTruncate(root:Document|Element=document):void{
}
}));
mutations.observe((root as Document).body||root,{childList:true,characterData:true,subtree:true});
- document.fonts?.ready?.then(()=>root.querySelectorAll('[data-middle-truncate]').forEach(schedule));
- root.addEventListener('copy',event=>{
+ document.fonts?.ready?.then(()=>{if(live)root.querySelectorAll('[data-middle-truncate]').forEach(schedule)});
+ const copy:EventListener=event=>{
const selection=document.getSelection();
if(!selection||selection.isCollapsed)return;
const anchor=selection.anchorNode?.nodeType===Node.ELEMENT_NODE?selection.anchorNode as Element:selection.anchorNode?.parentElement;
@@ -137,7 +147,17 @@ function initMiddleTruncate(root:Document|Element=document):void{
const state=target&&states.get(target);
if(!state||!target.contains(selection.focusNode)||!(event as ClipboardEvent).clipboardData)return;
(event as ClipboardEvent).clipboardData?.setData('text/plain',state.full);event.preventDefault();
- });
+ };
+ root.addEventListener('copy',copy);
+ const dispose=()=>{
+ if(!live)return;live=false;
+ resize.disconnect();mutations.disconnect();root.removeEventListener('copy',copy);
+ for(const element of elements){const state=states.get(element);if(state?.raf){cancelAnimationFrame(state.raf);state.raf=0}}
+ elements.clear();
+ if(disposeTruncation===dispose){disposeTruncation=null;resizeObserver=null}
+ };
+ disposeTruncation=dispose;
+ return dispose;
}
export { initMiddleTruncate, middleTruncateText };
diff --git a/frontend/test/managed-lifetime.test.ts b/frontend/test/managed-lifetime.test.ts
new file mode 100644
index 000000000..ed21e4685
--- /dev/null
+++ b/frontend/test/managed-lifetime.test.ts
@@ -0,0 +1,37 @@
+import { expect, it, vi } from 'vitest';
+
+it('应用收起全部页面时同时取消未落地预取,晚到响应不挂宿主', async () => {
+ vi.resetModules();
+ const managed = await import('../src/history/managed');
+ const container = document.createElement('div');
+ container.textContent = '正在读取'; document.body.append(container);
+ let signal: AbortSignal | undefined;
+ let release = () => {}, entered = () => {};
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const started = new Promise<void>(resolve => { entered = resolve; });
+ managed.connectManagedRoutes(Promise.resolve(async (_path, _props, current) => {
+ signal = current; entered(); await gate;
+ }));
+ const place = vi.fn(() => container);
+ const opened = managed.openManagedRoute('/', {}, { container, isCurrent: () => true, place });
+ await started;
+ managed.releaseAllManagedRoutes();
+ expect(signal?.aborted).toBe(true);
+ release(); expect(await opened).toBe(false);
+ expect(place).not.toHaveBeenCalled(); expect(container.textContent).toBe('正在读取');
+ expect(managed.managedEntries()).toEqual([]); container.remove();
+});
+
+it('应用收起全部登记只撤页面宿主,保留静态常驻容器', async () => {
+ vi.resetModules();
+ const managed = await import('../src/history/managed');
+ const page = document.createElement('div'), resident = document.createElement('div');
+ document.body.append(page, resident);
+ managed.connectManagedRoutes(Promise.resolve(async () => {}));
+ await managed.openManagedRoute('/', {}, { container: page, isCurrent: () => true });
+ await managed.openResidentSurface('batch-dock', resident);
+ expect(managed.managedEntries()).toHaveLength(2);
+ managed.releaseAllManagedRoutes(); managed.releaseAllManagedRoutes();
+ expect(managed.managedEntries()).toEqual([]); expect(page.children).toHaveLength(0);
+ expect(resident.isConnected).toBe(true); page.remove(); resident.remove();
+});
diff --git a/frontend/test/middle-truncate-lifetime.test.ts b/frontend/test/middle-truncate-lifetime.test.ts
new file mode 100644
index 000000000..6ac660a00
--- /dev/null
+++ b/frontend/test/middle-truncate-lifetime.test.ts
@@ -0,0 +1,23 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { initMiddleTruncate } from '../src/ui-kit/middle-truncate';
+
+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+it('截断观察者与复制监听可销毁,重挂同一元素重新观察', () => {
+ vi.useFakeTimers();
+ const observers: { observe: ReturnType<typeof vi.fn>; disconnect: ReturnType<typeof vi.fn> }[] = [];
+ vi.stubGlobal('ResizeObserver', class {
+ observe = vi.fn(); disconnect = vi.fn(); unobserve = vi.fn();
+ constructor() { observers.push(this); }
+ });
+ const root = document.createElement('div'); root.innerHTML = '<span data-middle-truncate>完整文件名</span>';
+ document.body.append(root);
+ const remove = vi.spyOn(root, 'removeEventListener');
+ const first = initMiddleTruncate(root); first(); first();
+ expect(observers[0]?.disconnect).toHaveBeenCalledTimes(1);
+ expect(remove.mock.calls.filter(([name]) => name === 'copy')).toHaveLength(1);
+ const second = initMiddleTruncate(root);
+ expect(observers[1]?.observe).toHaveBeenCalledWith(root.firstElementChild);
+ second(); expect(observers[1]?.disconnect).toHaveBeenCalledTimes(1);
+ root.remove();
+});
diff --git a/frontend/test/query/media-sources.test.ts b/frontend/test/query/media-sources.test.ts
index dcb886478..6414e33eb 100644
--- a/frontend/test/query/media-sources.test.ts
+++ b/frontend/test/query/media-sources.test.ts
@@ -80,3 +80,25 @@ it('取不到时照常抛出,由壳落成空表', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 503, json: async () => ({}) })));
await expect(loadMediaSources()).rejects.toThrow();
});
+
+it('应用取消信号中止真实来源请求且不再重试', async () => {
+ const calls = pendingFetch(), application = new AbortController();
+ const request = loadMediaSources(application.signal);
+ const rejection = expect(request).rejects.toMatchObject({ name: 'AbortError' });
+ await flush(); expect(calls[0]!.signal).toBe(application.signal);
+ application.abort(); await rejection; await flush();
+ expect(calls).toHaveLength(1);
+});
+
+it('已取消应用不发来源请求,页面合并请求取消也不恢复已卸载应用', async () => {
+ const calls = pendingFetch(), application = new AbortController();
+ application.abort(); await expect(loadMediaSources(application.signal)).rejects.toMatchObject({ name: 'AbortError' });
+ expect(calls).toHaveLength(0);
+ const pageScope = new AbortController(), applicationScope = new AbortController();
+ const page = prefetchMediaSources(pageScope.signal);
+ await flush(); const app = loadMediaSources(applicationScope.signal);
+ const pageRejection = expect(page).rejects.toMatchObject({ name: 'AbortError' });
+ const appRejection = expect(app).rejects.toMatchObject({ name: 'AbortError' });
+ applicationScope.abort(); pageScope.abort(); await Promise.all([pageRejection, appRejection]); await flush();
+ expect(calls).toHaveLength(1);
+});
diff --git a/frontend/test/react/toaster.test.tsx b/frontend/test/react/toaster.test.tsx
index 5620d2730..0a2549db0 100644
--- a/frontend/test/react/toaster.test.tsx
+++ b/frontend/test/react/toaster.test.tsx
@@ -1,7 +1,7 @@
import { act } from 'react';
-import { beforeAll, expect, it, vi } from 'vitest';
+import { afterAll, beforeAll, expect, it, vi } from 'vitest';
-import { mountToaster, showToast } from '../../src/react/toaster';
+import { mountToaster, showToast, unmountToaster } from '../../src/react/toaster';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -11,6 +11,7 @@ beforeAll(async () => {
document.body.append(host);
await act(async () => mountToaster(host, { success: '<svg data-glyph="check"></svg>', error: '<svg data-glyph="alert"></svg>' }));
});
+afterAll(async () => { await act(async () => unmountToaster()); host.remove(); });
const toastsWith = (text: string) => [...host.querySelectorAll<HTMLElement>('[data-sonner-toast]')]
.filter((node) => node.textContent?.includes(text));
@@ -49,3 +50,15 @@ it('成功的勾画出来,失败的圈不画,正文按调用点给的 HTML
expect(bad.dataset.type).toBe('error');
expect(bad.querySelector('[data-toast-glyph="still"] [data-glyph="alert"]')).not.toBeNull();
});
+
+it('同宿主重复挂载共用栈,卸载后可重挂,换宿主撤下原栈', async () => {
+ const next = document.createElement('div'); document.body.append(next);
+ const icons = { success: '', error: '' };
+ await act(async () => mountToaster(next, icons));
+ const original = next.firstElementChild;
+ expect(original).not.toBeNull(); expect(host.children).toHaveLength(0);
+ await act(async () => mountToaster(next, icons)); expect(next.firstElementChild).toBe(original);
+ await act(async () => { unmountToaster(); unmountToaster(); }); expect(next.children).toHaveLength(0);
+ await act(async () => mountToaster(next, icons)); expect(next.firstElementChild).not.toBe(original);
+ await act(async () => unmountToaster()); next.remove();
+});