Peach: Local-first video metadata scraper and media manager.
perf(web): 冷启动的长任务从一百七八十毫秒降到八十毫秒上下,骨架首帧提前一百多毫秒
longmeidaod7b2665d2487
diff --git a/frontend/test/skeleton-tier-fill.test.ts b/frontend/test/skeleton-tier-fill.test.tsnew file mode 100644index 000000000..524321adf--- /dev/null+++ b/frontend/test/skeleton-tier-fill.test.ts@@ -0,0 +1,70 @@+/* 横向骨架铺到右缘:铺满,而且整批只让浏览器布局几次。+ *+ * 改过 DOM 之后再读一次宽度,浏览器就得当场把整页布局一遍。冷启动时资料页那几排骨架逐枚+ * 追加、逐枚量,实测一排一百多毫秒。这里用桩出来的几何数「改了又读」发生了几次。 */+import { afterEach, describe, expect, it } from 'vitest';++// @ts-expect-error 遗留模块由浏览器直接加载,此测试调用实际实现。+import { fillSkeletonTier, fitSkeleton } from '../../web/js/ui-components.js';++const ROW = 1000;+const SLOT = 100;+let layouts = 0;+let dirty = false;+const rect = (left: number, right: number) => ({ left, right, top: 0, bottom: 20, width: right - left, height: 20 });+const original = HTMLElement.prototype.getBoundingClientRect;++function row(kind: string): HTMLElement {+ const node = document.createElement('div');+ node.dataset.skeletonTier = kind;+ const read = () => { if (dirty) { layouts++; dirty = false; } };+ Object.defineProperty(node, 'clientWidth', { get: () => { read(); return ROW; } });+ Object.defineProperty(node, 'scrollWidth', { get: () => { read(); return Math.max(ROW, node.children.length * SLOT); } });+ const insert = node.insertAdjacentHTML.bind(node);+ node.insertAdjacentHTML = (where: InsertPosition, html: string) => { dirty = true; insert(where, html); };+ return node;+}++HTMLElement.prototype.getBoundingClientRect = function getBoundingClientRect(this: HTMLElement) {+ const parent = this.parentElement;+ if (this.dataset.skeletonTier) { if (dirty) { layouts++; dirty = false; } return rect(0, ROW) as DOMRect; }+ if (parent?.dataset.skeletonTier) {+ if (dirty) { layouts++; dirty = false; }+ const index = [...parent.children].indexOf(this);+ return rect(index * SLOT, (index + 1) * SLOT) as DOMRect;+ }+ return original.call(this);+};++afterEach(() => { layouts = 0; dirty = false; document.body.replaceChildren(); });++describe('横向骨架补满', () => {+ it('几排一起补:每排都越过右缘,整批只布局两次', () => {+ const root = document.createElement('div');+ const rows = [row('av'), row('brandpill'), row('pill')];+ root.append(...rows);+ document.body.append(root);+ fitSkeleton(root);+ for (const node of rows) expect(node.children.length * SLOT).toBeGreaterThan(ROW);+ expect(layouts).toBe(2);+ });++ it('已经铺满的那排再补一次不追加', () => {+ const root = document.createElement('div');+ const node = row('pill');+ root.append(node);+ document.body.append(root);+ fitSkeleton(root);+ const filled = node.children.length;+ fitSkeleton(root);+ expect(node.children.length).toBe(filled);+ });++ it('单独补一排也越过右缘,多出来的不超过一轮宽度序列', () => {+ const node = row('av');+ document.body.append(node);+ fillSkeletonTier(node, 'av');+ expect(node.children.length * SLOT).toBeGreaterThan(ROW);+ expect(node.children.length).toBeLessThanOrEqual(ROW / SLOT + 2);+ });+});diff --git a/tests/test_source_assertion_ratchet.py b/tests/test_source_assertion_ratchet.pyindex 8b6f040ff..b40cfb423 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": 4576,+ "test_web_ui.py": 4574,"test_windows_update.py": 3,}diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 08a639423..53adb2b5f 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -3415,10 +3415,7 @@ class WebUiSourceTests(unittest.TestCase):写死的话宽屏最后一行留一截豁口——用户实测首页第二行只有一张卡;窄屏和手机端又多出一堆要横滑才看得见的占位。算出来就不必再为断点各写一套。"""- self.assertPageContains("export function fillSkeletonTier(row,kind){")- self.assertPageContains(- " row.insertAdjacentHTML('beforeend',slot(widths[i%widths.length]));\n"- " if(row.scrollWidth>row.clientWidth)break;")+ # 横排铺到右缘、整批只布局几次,由 `frontend/test/skeleton-tier-fill.test.ts` 守。self.assertPageContains("export function fitSkeleton(root){")self.assertPageContains(" const columns=style.gridTemplateColumns.split(' ').filter(Boolean).length;")diff --git a/web/app.js b/web/app.jsindex d0405f186..4c3fd7ce6 100644--- a/web/app.js+++ b/web/app.js@@ -10984,7 +10984,10 @@ if(/Chrome|Chromium|Edg\//.test(navigator.userAgent)){const width=Math.round(node.clientWidth),height=Math.round(node.clientHeight);if(!width||!height)return;const radius=Math.min(parseFloat(getComputedStyle(node).borderRadius)||22,width/2,height/2);const key=`${width}:${height}:${radius}`;if(previous===key)return;previous=key;const ratio=Math.min(1,600/width,600/height);const w=Math.max(2,Math.round(width*ratio)),h=Math.max(2,Math.round(height*ratio));- const canvas=document.createElement('canvas');canvas.width=w;canvas.height=h;const ctx=canvas.getContext('2d');const pixels=ctx.createImageData(w,h);+ /* 画布只拿来写一次像素、读一次 PNG,走 CPU 那一种:默认的 GPU 画布在 toDataURL 时要把+ 像素读回来,第一次还得先建 GPU 上下文,冷启动实测单这一下就是一百毫秒上下,之后的+ 重画也时不时要和合成抢 GPU 等几十毫秒。 */+ const canvas=document.createElement('canvas');canvas.width=w;canvas.height=h;const ctx=canvas.getContext('2d',{willReadFrequently:true});const pixels=ctx.createImageData(w,h);const distance=(x,y)=>{const qx=Math.abs(x-width/2)-(width/2-radius),qy=Math.abs(y-height/2)-(height/2-radius);return Math.hypot(Math.max(qx,0),Math.max(qy,0))+Math.min(Math.max(qx,qy),0)-radius};const depth=Math.min(24,Math.min(width,height)/3);for(let y=0;y<h;y++)for(let x=0;x<w;x++){diff --git a/web/js/ui-components.js b/web/js/ui-components.jsindex 16c1345fa..bf17529f0 100644--- a/web/js/ui-components.js+++ b/web/js/ui-components.js@@ -751,22 +751,40 @@ function armSkeletonReveal(root){}}-/** 一行横向骨架:逐枚追加到溢出容器右缘为止。上限只是死循环的护栏。 */-export function fillSkeletonTier(row,kind){- const slot=SKELETON_SLOT[kind],widths=SKELETON_SLOT_WIDTHS[kind];- if(!slot||!row)return;- for(let i=0;i<64;i++){- row.insertAdjacentHTML('beforeend',slot(widths[i%widths.length]));- if(row.scrollWidth>row.clientWidth)break;+const SKELETON_TIER_LIMIT=64;+/* 横向骨架铺到溢出容器右缘为止。每量一次宽度就是一次整页布局,逐枚追加、逐枚量的话一排+ 要布局十几二十次,冷启动实测一排一百多毫秒。所以按轮来:先铺一轮宽度序列,量一次,按+ 量到的平均宽度把缺的那截一次补齐,再量一次确认。几排走同一轮,先全量再全写,合起来也+ 只布局这几次。上限只是死循环的护栏。 */+function fillSkeletonTiers(jobs){+ /* 同一排会再补一次(名单到了、容器改宽):已经越过右缘的那排不再追加。空排不必先量。 */+ jobs=jobs.filter(job=>job.row&&SKELETON_SLOT[job.kind]&&(!job.row.children.length||job.row.scrollWidth<=job.row.clientWidth))+ .map(job=>({...job,start:job.row.children.length,added:0}));+ const add=(job,count)=>{+ const slot=SKELETON_SLOT[job.kind],widths=SKELETON_SLOT_WIDTHS[job.kind];+ let html='';+ for(const end=Math.min(SKELETON_TIER_LIMIT,job.added+count);job.added<end;job.added++)html+=slot(widths[job.added%widths.length]);+ job.row.insertAdjacentHTML('beforeend',html);+ };+ for(const job of jobs)add(job,SKELETON_SLOT_WIDTHS[job.kind].length);+ for(let round=0;round<4;round++){+ const short=jobs.filter(job=>job.added<SKELETON_TIER_LIMIT&&job.row.scrollWidth<=job.row.clientWidth).map(job=>{+ const first=job.row.children[job.start].getBoundingClientRect(),last=job.row.lastElementChild.getBoundingClientRect();+ const each=Math.max(1,(last.right-first.left)/job.added);+ return [job,Math.ceil((job.row.getBoundingClientRect().right-last.right)/each)+1];+ });+ if(!short.length)break;+ for(const [job,count] of short)add(job,Math.max(1,count));}- armSkeletonReveal(row);+ for(const job of jobs)armSkeletonReveal(job.row);}+export function fillSkeletonTier(row,kind){fillSkeletonTiers([{row,kind}])}/** 骨架落进 DOM 之后按实际尺寸补齐:横向一行铺满,卡片网格补到整行且盖住视口余量。 */export function fitSkeleton(root){if(!root)return;const scoped=selector=>[...(root.matches?.(selector)?[root]:[]),...root.querySelectorAll(selector)];- for(const row of scoped('[data-skeleton-tier]'))fillSkeletonTier(row,row.dataset.skeletonTier);+ fillSkeletonTiers(scoped('[data-skeleton-tier]').map(row=>({row,kind:row.dataset.skeletonTier})));for(const grid of scoped('.skeletonpanel[data-fill]>div,.index-skeleton[data-fill]>section>div')){const first=grid.firstElementChild,style=getComputedStyle(grid);/* 横排的推荐行不是网格,列数无从谈起,按整行补会把它裁成一张。 */