Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor(web): 删掉壳里已无调用方的 wireLoadMore

longmeidao5346d3e90aab
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 000d7854d..1fbf36dcf 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -23,7 +23,7 @@
- 筛选内层复用 `filterChipHtml`、`sortControlsHtml`,首页与关注页提供查询键及读数;`collectionHeaderHtml` 只剩资料页骨架那一排读数。横向行复用 `wireHorizontalScroller`,拖动、滚轮、渐隐与卸载清理归同一个生命周期。
- 选择范围与工具条复用 `frontend/src/selection.ts`;馆藏、关注与复核保持各自身份、可见顺序、默认选择及写入权限。批量失败项的保留由业务负责。
- React 设置分区复用 `frontend/src/react/settings/section.tsx`:`Section` 提供标题、卡片与表单外壳,`Footer`、`Note`、`ErrorText`、`FactList`、`Progress`、`Disclosure` 补齐 BoardUI 注册表没有的底栏、行内提示、读数、进度与折叠。`use-action.ts` 的 `useAction` 负责提交互斥、卸载取消与原位错误,`busyProps` 写忙态。密码字段校验与服务端回执仍归各分区,不自动重试写入。后台任务(口味读取、封面采集、amane 桥重建、关注检查与查找)共用 `frontend/src/react/background-job.ts` 的 `useBackgroundJob`。
-- 增量列表复用 `wireLoadMore` 的请求锁、原位重试与卸载清理;页面注入读取、追加、代际判定和可用条件。首页页码在读取成功后推进,照片沿用随机种子,关注合并分组。显式页码继续使用 `pagination.ts`。
+- 增量列表复用 `frontend/src/react/catalog-grid/catalog-grid-page.tsx` 的 `LoadMore`:请求互斥、失败留原位重试、卸载即停;目录、资料页照片墙与关注页注入读取和可用条件。首页页码在读取成功后推进,照片沿用随机种子,关注合并分组。显式页码继续使用 `pagination.ts`。
- 在图上框一块由 `frontend/src/crop-geometry.ts`(纯算术)加 `react/crop/crop-frame.tsx`(一张图、四块压暗、一个可拖可缩的框)承担,换头像与裁封面共用;坐标一律是源图像素、右下开区间,显示像素只在进出这一层时换算。不引 `react-image-crop` 那类库:要的就是一个能拖能缩的矩形,换到的只有把手样式,代价是一条新依赖和一套它自己的坐标约定。详情页仍是遗留壳,所以裁封面做成 island 从 `web/app.js` 挂(ADR-0031),交互不写两遍。
- 后台任务复用 `watchJob`、`followJobProgress` 默认面板及 `jobActivityHtml` 的真实计数/未知总量显示;关注、来源扫描、链接检查和扫描采集共用渲染。业务保留启动、终态回执和结果面板,不新增轮询循环。
- 图标按钮统一清除浏览器内边距并居中 SVG,不覆盖业务显隐。Remix Icon 由 `vendor_web_dependencies.mjs` 生成设置导航 symbol;随机按钮保留原有双路径动画。
diff --git a/frontend/src/react/catalog-grid/catalog-grid-page.tsx b/frontend/src/react/catalog-grid/catalog-grid-page.tsx
index f1170929c..6e875420d 100644
--- a/frontend/src/react/catalog-grid/catalog-grid-page.tsx
+++ b/frontend/src/react/catalog-grid/catalog-grid-page.tsx
@@ -5,7 +5,7 @@
* 起来(同遗留层 `revealSkeleton`),骨架还没到显示门槛就取完的直接落内容。
*
* 读数行(`#count`)的结构归壳,网格每接一页经 `onCount` 报一次,再把读数按位错峰写进
- * 那一格(遗留层 `popCount`)。无限滚动的判据照抄遗留层 `wireLoadMore`:哨兵进入视口 320px
+ * 那一格(遗留层 `popCount`)。无限滚动见下面的 `LoadMore`:哨兵进入视口 320px
* 内自动取下一页,点它等于手动取;失败在哨兵后面留一条可重试的 Note,之后只有手动才重试。 */
import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from 'react';
import { useInfiniteQuery, type InfiniteData, type QueryKey } from '@tanstack/react-query';
diff --git a/frontend/test/shared-list-controls.test.ts b/frontend/test/shared-list-controls.test.ts
index c46616bad..539192109 100644
--- a/frontend/test/shared-list-controls.test.ts
+++ b/frontend/test/shared-list-controls.test.ts
@@ -1,51 +1,10 @@
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { afterEach, expect, it, vi } from 'vitest';
// @ts-expect-error 浏览器共享控件使用正式实现。
-import { wireLoadMore, wireHorizontalScroller, rubberBand, sortControlsHtml, filterChipHtml } from '../../web/js/ui-components.js';
+import { wireHorizontalScroller, rubberBand, sortControlsHtml, filterChipHtml } from '../../web/js/ui-components.js';
-let intersections: (() => void)[], disconnects: ReturnType<typeof vi.fn>[];
-beforeEach(() => {
- intersections=[];disconnects=[];
- vi.stubGlobal('IntersectionObserver',class {
- disconnect=vi.fn();
- constructor(callback: (entries: {isIntersecting:boolean}[])=>void){intersections.push(()=>callback([{isIntersecting:true}]));disconnects.push(this.disconnect)}
- observe(){}
- });
-});
afterEach(async () => {document.body.replaceChildren();await new Promise(resolve=>setTimeout(resolve,0));vi.unstubAllGlobals()});
function button(){const node=document.createElement('button');document.body.append(node);return node}
-it('点击与观察器共享请求锁,重接消费者仍只追加一次', async () => {
- const node=button(),apply=vi.fn();let done!:(value:number)=>void;
- const read=vi.fn(()=>new Promise<number>(resolve=>{done=resolve}));
- const control=wireLoadMore(node,{read,apply});
- const pending=control.run();node.click();intersections[0]!();
- expect(wireLoadMore(node,{read,apply})).toBe(control);
- expect(read).toHaveBeenCalledOnce();expect(node.getAttribute('aria-busy')).toBe('true');expect(node.disabled).toBe(false);
- done(2);await pending;
- expect(apply).toHaveBeenCalledExactlyOnceWith(2);expect(node.hasAttribute('aria-busy')).toBe(false);
-});
-
-it('失败保留原位重试,观察器不会自动重复失败请求', async () => {
- const node=button(),apply=vi.fn();
- const read=vi.fn().mockRejectedValueOnce(new Error('网络暂不可用')).mockResolvedValueOnce(3);
- const control=wireLoadMore(node,{read,apply});await control.run();
- expect(document.querySelector('[role="alert"]')).not.toBeNull();
- intersections[0]!();await control.run();expect(read).toHaveBeenCalledOnce();
- document.querySelector<HTMLButtonElement>('[data-note-action]')!.click();
- await vi.waitFor(()=>expect(apply).toHaveBeenCalledExactlyOnceWith(3));
- expect(document.querySelector('[role="alert"]')).toBeNull();
-});
-
-it('导航代际变化或卸载后不接受在途结果,卸载断开观察器', async () => {
- const node=button(),apply=vi.fn();let current=true,done!:(value:number)=>void,signal!:AbortSignal;
- const read=(next:AbortSignal)=>{signal=next;return new Promise<number>(resolve=>{done=resolve})};
- const control=wireLoadMore(node,{read,apply,isCurrent:()=>current});
- const first=control.run();current=false;done(1);await first;expect(apply).not.toHaveBeenCalled();
- current=true;const next=control.run();node.remove();
- await vi.waitFor(()=>expect(signal.aborted).toBe(true));done(2);await next;
- expect(disconnects[0]).toHaveBeenCalledOnce();expect(apply).not.toHaveBeenCalled();
-});
-
it('在横排上开头的滚轮手势整段归这一排,鼠标一格逐帧走完、半路接着加,拦不住的留给页面,重复绑定与移除都释放资源', async () => {
const node=button();let left=0,now=1000;const disconnect=vi.fn();
vi.stubGlobal('ResizeObserver',class {observe(){}disconnect=disconnect});
diff --git a/tests/test_source_assertion_ratchet.py b/tests/test_source_assertion_ratchet.py
index fee7e48e6..5109928e1 100644
--- a/tests/test_source_assertion_ratchet.py
+++ b/tests/test_source_assertion_ratchet.py
@@ -53,7 +53,7 @@ BASELINE: dict[str, int] = {
"test_web_e2e.py": 2,
"test_web_js.py": 1,
"test_web_settings.py": 8,
- "test_web_ui.py": 3644,
+ "test_web_ui.py": 3639,
"test_windows_update.py": 3,
}
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 74778574d..ec084014a 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -9793,27 +9793,6 @@ class WebUiSourceTests(unittest.TestCase):
self.assertIn("showManagementBody(", body,
name + " 自己铺页面主体,多半又抄漏了一行")
- def test_infinite_scroll_is_wired_through_one_helper(self):
- """「载入更多」的观察器只许有一份实现。
-
- 它此前抄了三份:关注流、实体合集、照片墙。已经开始漂——后两份有 `hidden`
- 判断,关注那份没有。藏起来的按钮观察它没有意义,漏掉只是浪费一个观察器,
- 但下一次抄漏的可能就不是这一行。
-
- 重画会换掉按钮节点,所以 disconnect 不能省:旧观察器还盯着已脱离文档的节点,
- 既不会触发也不会被回收。
- """
- body = self._js_function("wireLoadMore")
- self.assertIn("observer.disconnect()", body, "卸载必须断开观察器")
- self.assertIn("busy||button.hidden||!button.isConnected", body)
- self.assertIn("current.isCurrent?.()!==false", body)
- self.assertIn("request?.abort()", body)
- self.assertIn("rootMargin:'320px'", body)
- self.assertEqual(self.page.count("new IntersectionObserver"), 1,
- "共享分页只有这一个观察器")
- # 资料页照片墙与关注流的翻页在 `entity-body`、`follow-feed` 岛里,用的是卡片网格那枚
- # `LoadMore`,同一套判据。
-
def test_the_identity_name_leaves_room_for_descenders(self):
"""身份格子里的名字不能被行框切掉下伸部。
diff --git a/web/app.js b/web/app.js
index 54e9e7fc8..6532f2bee 100644
--- a/web/app.js
+++ b/web/app.js
@@ -23,7 +23,7 @@ import {
dissolveValue, popBadges, revealSkeleton, revealTexts, setIconSwap, swapText,
boardTabsHtml, mountFilterFrame, filterChipHtml, moveGlidePane, glideEase, sortControlsHtml, collectionHeaderHtml, wireHorizontalScroller, noteHtml, presentMenu, gaugeHtml, scrollerHtml, searchInputHtml, selectFieldHtml,
SKELETON_REVEAL_DELAY, setActionBusy, skeletonHtml, spinnerHtml, growCollapse, wireAnchoredMenu, wireBusyActions, wireCollapse, wireDialSlider, wireDragReorder,
- wireIconSwitch, wireOverlayScrollbars, wireScrollers, wireSelectField, configurationSkeletonHtml, wireLoadMore, wireAutoScroll, stopAutoScroll, scrollMovesAnchor,
+ wireIconSwitch, wireOverlayScrollbars, wireScrollers, wireSelectField, configurationSkeletonHtml, wireAutoScroll, stopAutoScroll, scrollMovesAnchor,
postSetupTutorialMarker, setPostSetupTutorialMarker, postSetupTutorialCollapsed, setPostSetupTutorialCollapsed,
postSetupTutorialSkipped, setPostSetupTutorialSkipped, postSetupTutorialSignature,
nextPostSetupTutorialRequest, isCurrentPostSetupTutorialRequest, resetPostSetupTutorialState,
@@ -6777,7 +6777,6 @@ $('#scrim').onclick=()=>openDrawer(false);
async function loadCatalog(){
const requestSeq=++loadRequestSeq;
const surface=claimSurface(surfacePath());
- wireLoadMore($('#loadSentinel'),{}).destroy();
// 已经挂着就让它接着跑:重挂要先清空容器,而它这一刻要说的话跟上一刻是同一句。
if(isCatalogPath(location.pathname)&&!islandMounted($('#libraryProcessingNotice')))
void mountIsland('library-processing',$('#libraryProcessingNotice'),{toast,mode:'notice'},{isCurrent:()=>surfaceCurrent(surface)});
diff --git a/web/js/ui-components.js b/web/js/ui-components.js
index c8fabcef7..e8c001d99 100644
--- a/web/js/ui-components.js
+++ b/web/js/ui-components.js
@@ -443,41 +443,6 @@ export function moveGlidePane(pane,from,box,axis='x'){
pane.style.translate=settled;
}
-const incrementalControls=new Map();
-let incrementalCleanup;
-/** 分页请求互斥,失败留在原位手动重试,卸载后丢弃结果。 */
-export function wireLoadMore(button,options){
- if(!button)return;
- const existing=incrementalControls.get(button);
- if(existing){existing.options=options;return existing}
- let busy=false,failed=false,errorNode=null,request=null,disposed=false;
- const clearError=()=>{errorNode?.remove();errorNode=null;failed=false};
- const control={options,async run(manual=false){
- const current=control.options;
- if(disposed||busy||button.hidden||!button.isConnected||(!manual&&failed)||current.enabled?.()===false)return;
- clearError();busy=true;request=new AbortController();
- const alive=()=>!disposed&&!request.signal.aborted&&button.isConnected&&current.isCurrent?.()!==false;
- setActionBusy(button,true);
- try{
- const result=await current.read(request.signal);
- if(alive())await current.apply?.(result);
- }catch(error){
- if(alive()&&error?.name!=='AbortError'){
- failed=true;errorNode=document.createElement('div');
- errorNode.innerHTML=noteHtml(error?.message||String(error),{variant:'error',actionLabel:'重试'});
- errorNode.querySelector('[data-note-action]').onclick=()=>control.run(true);
- button.after(errorNode);
- }
- }finally{busy=false;setActionBusy(button,false)}
- },destroy(){disposed=true;request?.abort();observer.disconnect();button.removeEventListener('click',click);clearError();incrementalControls.delete(button);if(!incrementalControls.size){incrementalCleanup?.disconnect();incrementalCleanup=null}}};
- const click=()=>control.run(true);
- button.addEventListener('click',click);
- const observer=new IntersectionObserver(entries=>{if(entries.some(entry=>entry.isIntersecting))void control.run()},{rootMargin:'320px'});
- observer.observe(button);incrementalControls.set(button,control);
- if(!incrementalCleanup){incrementalCleanup=new MutationObserver(()=>{for(const [node,item] of incrementalControls)if(!node.isConnected)item.destroy()});incrementalCleanup.observe(document.body,{childList:true,subtree:true})}
- return control;
-}
-
/** 两行筛选浮层;页面拥有槽位里的控件与查询状态。 */
export function mountFilterFrame(top,bottom,{views,tags,readout,controls}){
let frame=top.closest('[data-filter-frame]');