Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(settings): 来源与订阅的骨架按终态的行数、底栏与高度占位

longmeidao4972b111dd2d
diff --git a/frontend/e2e/configuration-skeleton.test.ts b/frontend/e2e/configuration-skeleton.test.ts
index d39ab3dda..edec88bed 100644
--- a/frontend/e2e/configuration-skeleton.test.ts
+++ b/frontend/e2e/configuration-skeleton.test.ts
@@ -117,6 +117,57 @@ describe('配置页等待态', () => {
}
});
}
+ /* 来源与订阅有四块另取数据的分区:整页骨架、分区骨架与读回后的终态,每块的标题与卡片都在
+ 同一位置、同样高,下面的分区不跟着跳。正文高度按上一次画好时记下的值占位,所以先正常打开一次。 */
+ it('来源与订阅的整页骨架、分区骨架与读回的分区同位同高', { timeout: 90_000 }, async () => {
+ const opened = await visit(browser, '/settings/subscriptions', VIEWPORTS[0]);
+ let release = () => {};
+ let mount = () => {};
+ try {
+ const { page } = opened;
+ const names = ['来源凭据', '关注采集', '资源搜索', '作品资料站点'];
+ /* 骨架淡出时新旧两份 `.ui-configpage` 可能同时在:取最后挂上的那一份。 */
+ const sections = () => page.locator('.ui-configpage').last().evaluate((root, names) => names.map((name) => {
+ const section = root.querySelector(`[aria-label="${name}"]`);
+ if (!section) return null;
+ const r = section.getBoundingClientRect();
+ return { name, y: r.y, height: r.height };
+ }), names);
+ const done = () => page.waitForFunction(() => document.querySelector('.ui-configpage section[aria-label="来源凭据"]')
+ && !document.querySelector('.ui-configpage [data-skeleton]'), null, { timeout: 30_000 });
+ await done();
+ await settle(page);
+ /* 两道门:配置读回之前是整页骨架;配置放行、分区自己的数据还压着时是分区骨架。 */
+ const configuration = new Promise<void>((resolve) => { mount = resolve });
+ const held = new Promise<void>((resolve) => { release = resolve });
+ await page.route('**/api/configuration', async (route) => { await configuration; await route.continue() });
+ for (const url of ['**/api/follow/credentials', '**/api/configuration/indexers', '**/api/follow/schedule', '**/api/feeds/schedule']) {
+ await page.route(url, async (route) => { await held; await route.continue() });
+ }
+ await page.reload({ waitUntil: 'commit' });
+ await page.locator('[data-skeleton="board/settings/subscriptions"]').waitFor();
+ const pageSkeleton = await sections();
+ mount();
+ await page.getByLabel('正在读取来源凭据', { exact: true }).waitFor();
+ const sectionSkeleton = await sections();
+ release();
+ await done();
+ await settle(page);
+ const live = await sections();
+ for (const [phase, shape] of [['整页骨架', pageSkeleton], ['分区骨架', sectionSkeleton]] as const) {
+ shape.forEach((section, i) => {
+ const end = live[i]!;
+ assert.ok(section && Math.abs(section.y - end.y) <= 1 && Math.abs(section.height - end.height) <= 1,
+ `${phase}「${names[i]}」${JSON.stringify(section)},读回后 ${JSON.stringify(end)}`);
+ });
+ }
+ assert.deepEqual(opened.problems, []);
+ } finally {
+ mount();
+ release();
+ await opened.close();
+ }
+ });
for (const path of ['/settings/library', '/review']) {
it(`${path} 的明暗主题使用透明容器与灰色 Pills 选中底色`, { timeout: 60_000 }, async () => {
const opened = await visit(browser, path, VIEWPORTS[0]);
diff --git a/frontend/src/configuration-skeleton.ts b/frontend/src/configuration-skeleton.ts
index 248b44418..4e37dc115 100644
--- a/frontend/src/configuration-skeleton.ts
+++ b/frontend/src/configuration-skeleton.ts
@@ -2,6 +2,7 @@ import { islandButton, islandSelect } from './island-skeleton';
import { CONFIGURATION_SECTIONS } from './history/settings-route';
import { diagnosticsSkeleton } from './diagnostics-skeleton';
import { LIBRARY_FOLDER_HELP, POLICY_SUMMARY } from './react/settings/library-policy-copy';
+import { ENTRY_LINKS_HELP, ENTRY_LINKS_HINT } from './configuration-copy';
const wait = 'disabled data-skeleton-action';
const text = (width = '60%') => `<span class="skeleton skeleton-text" style="width:${width}"></span>`;
@@ -10,7 +11,12 @@ const button = (label: string, variant: 'primary' | 'secondary' = 'primary') =>
const footer = (content: string) => `<div class="-ml-3 flex flex-wrap items-center justify-end gap-3 rounded-b-2xl border-t border-separator-border bg-card-footer px-3 py-3">${content}</div>`;
const stack = (content: string) => `<div class="flex flex-col gap-4 py-4 pr-3">${content}</div>`;
const section = (title: string, content: string, actions = '') => `<section aria-label="${title}" class="flex w-full flex-col gap-2 wrap-anywhere"><p class="w-full px-3 text-body-2-medium text-text-secondary">${title}</p><div class="flex w-full flex-col rounded-2xl bg-background-secondary-default pl-3">${content}${actions ? footer(actions) : ''}</div></section>`;
-const row = (label: string, description = '', control = 'ui-configuration-skeleton-toggle') => `<div class="flex min-h-[52px] w-full items-center justify-between gap-4 py-2.5 pr-2.5 border-b border-separator-border last:border-b-0"><div class="flex min-w-0 flex-col"><p class="text-body-regular text-text-primary">${label}</p>${description ? `<p class="text-body-2-regular text-text-secondary">${description}</p>` : ''}</div><span class="skeleton ${control}"></span></div>`;
+const controlRow = (label: string, description: string, control: string) => `<div class="flex min-h-[52px] w-full items-center justify-between gap-4 py-2.5 pr-2.5 border-b border-separator-border last:border-b-0"><div class="flex min-w-0 flex-col"><p class="text-body-regular text-text-primary">${label}</p>${description ? `<p class="text-body-2-regular text-text-secondary">${description}</p>` : ''}</div>${control}</div>`;
+const row = (label: string, description = '', control = 'ui-configuration-skeleton-toggle') => controlRow(label, description, `<span class="skeleton ${control}"></span>`);
+/* 只读一句读数的行(「每 3 个月」):右边是一段文字宽的占位,行高同开关行。 */
+const valueRow = (label: string, width = '4em') => controlRow(label, '', text(width));
+const block = (height: number) => `<span class="skeleton ui-configuration-skeleton-input" style="width:100%;height:${height}px"></span>`;
+const hostField = (label: string, hint: string) => `<div class="flex w-full flex-col items-start gap-1"><span class="text-body-medium text-text-primary">${label}</span>${input()}<span class="pt-px text-caption-1-medium text-text-secondary">${hint}</span></div>`;
/* 「媒体库与目录」按媒体库分组,组数和每组文件夹数各家不同:上次画出来的形状记在本机,
* 骨架照着它排,第一次打开按一组一个文件夹。CloudDrive 代理与自动发现两块也按上次有没有决定。 */
@@ -38,6 +44,17 @@ export function rememberedSectionHeight(key: string, fallback: number): number {
} catch { return fallback }
}
+/* 来源与订阅里另取数据的分区:正文高度的记忆键与第一次打开时的默认值。来源凭据的站点清单由
+ * Peach 自己定,默认值取全部站点收起时的高度;资源搜索默认没有索引器,只有帮助那一行。 */
+export const SECTION_BODY = {
+ credentials: { key: 'source-credentials', fallback: 1498 },
+ indexers: { key: 'indexers', fallback: 18 },
+ javBrowser: { key: 'jav-browser', fallback: 100 },
+} as const;
+export type SectionBody = keyof typeof SECTION_BODY;
+export const sectionBodyHeight = (name: SectionBody): number =>
+ rememberedSectionHeight(SECTION_BODY[name].key, SECTION_BODY[name].fallback);
+
function mediaShape(): MediaShape {
try {
const value = JSON.parse(localStorage.getItem(MEDIA_SHAPE_KEY) || 'null') as Partial<MediaShape> | null;
@@ -87,10 +104,11 @@ export function configurationContentSkeleton(chosen: string): string {
case '系统诊断': return diagnosticsSkeleton();
case '媒体库与入库': return media();
case '来源与订阅': return `<div>${button('采集来源与登录状态', 'secondary')}</div>`
- + section('来源凭据', stack(`${text('40%')}${input()}${text('70%')}`))
- + section('关注采集', row('首次采集范围', '', 'ui-configuration-skeleton-select') + row('头像刷新') + row('favicon 刷新'))
- + section('资源搜索', stack(`${text('40%')}${input()}`))
- + section('作品资料站点', stack(`${input()}${input()}`), button('保存配置'));
+ + section('来源凭据', stack(block(sectionBodyHeight('credentials'))))
+ + section('关注采集', controlRow('自动检查更新', '', `<span class="flex items-center gap-2"><span class="skeleton ui-configuration-skeleton-toggle"></span><span class="skeleton ui-configuration-skeleton-input" style="width:96px"></span></span>`)
+ + valueRow('订阅源拉取') + row('首次采集范围', '', 'ui-configuration-skeleton-select') + valueRow('头像刷新') + valueRow('favicon 刷新'))
+ + section('资源搜索', stack(block(sectionBodyHeight('indexers'))), button('添加索引器', 'secondary') + button('保存配置'))
+ + section('作品资料站点', stack(`<p class="text-body-2-regular text-text-secondary">${ENTRY_LINKS_HELP}</p>${hostField('JavDB 地址', ENTRY_LINKS_HINT)}${hostField('MISSAV 地址', ENTRY_LINKS_HINT)}`), button('保存配置'));
case '下载渠道': return section('云下载', stack(`${text('35%')}${input()}${input()}${input()}${input()}`), button('保存配置'))
+ section('PikPak 账号', stack(`${input()}${input()}`), button('登录账号'));
case '网络与访问': return section('本机访问端口', stack(input('128px')), button('保存配置'))
diff --git a/frontend/src/react/follow-manage/credentials.tsx b/frontend/src/react/follow-manage/credentials.tsx
index b749c1f92..ae78c1720 100644
--- a/frontend/src/react/follow-manage/credentials.tsx
+++ b/frontend/src/react/follow-manage/credentials.tsx
@@ -17,7 +17,7 @@ import { Note } from '../components/note';
import { PathLine } from '../components/path-line';
import { queryClient } from '../query';
import { busyProps } from '../settings/use-action';
-import { Disclosure, ErrorText, ExternalLink, Help, Section, Stack } from '../settings/section';
+import { Disclosure, ErrorText, ExternalLink, Help, Section, Stack, useRememberedBody } from '../settings/section';
import {
CREDENTIAL_STATE, credentialDone, FOLLOW_CREDENTIALS_KEY, saveCredential,
type CredentialData, type CredentialRow,
@@ -146,6 +146,8 @@ export function Credentials(
) {
const rows = data.providers || [];
const pending = rows.filter((row) => row.requirement === 'required' && !credentialDone(row));
+ /* 配置页里那一份记下正文高度,配置页首屏的整页骨架与分区骨架按它占位。 */
+ const body = useRememberedBody<HTMLDivElement>('credentials', [data]);
if (!rows.length) {
return <EmptyState size="compact" icon={RiKey2Line} title="没有可配置的来源">已接入的站点及其凭据状态会显示在这里。</EmptyState>;
}
@@ -164,7 +166,9 @@ export function Credentials(
</div>
</section>
))}</>;
- return embedded ? <Section title="来源凭据" aside={pendingLabel || undefined}><Stack>{groups}</Stack></Section> :
+ return embedded ? <Section title="来源凭据" aside={pendingLabel || undefined}>
+ <Stack><div ref={body} className="flex flex-col gap-4">{groups}</div></Stack>
+ </Section> :
<div className={cardClass({ padding: 'none', className: 'flex flex-col gap-4 px-6 py-5 max-sm:px-4' })}>
<div className="flex flex-wrap items-center gap-2"><h3 className="mr-auto text-title-2-medium text-text-primary">来源凭据</h3>{pendingLabel}</div>
{groups}
diff --git a/frontend/src/react/settings/indexer-settings.tsx b/frontend/src/react/settings/indexer-settings.tsx
index bf93b5ed2..a0f059443 100644
--- a/frontend/src/react/settings/indexer-settings.tsx
+++ b/frontend/src/react/settings/indexer-settings.tsx
@@ -7,7 +7,7 @@ import { Checkbox } from '@/components/base/checkbox/checkbox';
import { Input } from '@/components/base/input/input';
import { apiGet, apiSend, errorMessage } from '../../api';
import { randomId } from '../../core/random-id';
-import { Disclosure, ErrorText, ExternalLink, Footer, Help, Section, SectionSkeleton, Stack } from './section';
+import { Disclosure, ErrorText, ExternalLink, Footer, Help, Section, SectionSkeleton, Stack, useRememberedBody } from './section';
import { busyProps, useAction } from './use-action';
const URL = '/api/configuration/indexers';
@@ -20,7 +20,10 @@ interface State { indexers: Indexer[]; max_indexers: number }
export function IndexerSettings({ receipt }: { receipt(message: string): void }) {
const query = useQuery({ queryKey: ['indexers'], queryFn: ({ signal }) => apiGet<State>(URL, signal), refetchOnMount: 'always' });
if (query.error) return <ErrorText>{errorMessage(query.error)}</ErrorText>;
- if (query.isFetching) return <SectionSkeleton title="资源搜索" label="正在读取资源搜索设置" height={68} />;
+ if (query.isFetching) return <SectionSkeleton title="资源搜索" label="正在读取资源搜索设置" body="indexers" actions={<>
+ <Button variant="secondary" type="button" disabled>添加索引器</Button>
+ <Button type="button" disabled>保存配置</Button>
+ </>} />;
return query.data ? <IndexerForm initial={query.data} receipt={receipt} /> : null;
}
@@ -44,6 +47,7 @@ function IndexerSummary({ row, index }: { row: Indexer; index: number }) {
function IndexerForm({ initial, receipt }: { initial: State; receipt(message: string): void }) {
const [rows, setRows] = useState(initial.indexers);
const action = useAction();
+ const body = useRememberedBody<HTMLDivElement>('indexers', [initial]);
const update = (key: string, fields: Partial<Indexer>) =>
setRows((current) => current.map((row) => row.key === key ? { ...row, ...fields } : row));
const save = (event: FormEvent<HTMLFormElement>) => {
@@ -56,6 +60,7 @@ function IndexerForm({ initial, receipt }: { initial: State; receipt(message: st
return (
<Section title="资源搜索" onSubmit={save}>
<Stack>
+ <div ref={body} className="flex min-w-0 flex-col gap-4">
<Disclosure summary="索引器连接帮助"><Help>填写 Prowlarr 或 Jackett 提供的 Torznab 地址和 API key。{' '}
<ExternalLink href="https://github.com/peach-mitao/peach/blob/master/docs/RESOURCE_SEARCH.md">详细配置说明</ExternalLink></Help>
</Disclosure>
@@ -88,6 +93,7 @@ function IndexerForm({ initial, receipt }: { initial: State; receipt(message: st
</Disclosure>
</div>
))}
+ </div>
{action.error ? <ErrorText>{action.error}</ErrorText> : null}
</Stack>
<Footer>
diff --git a/frontend/src/react/settings/jav-browser-settings.tsx b/frontend/src/react/settings/jav-browser-settings.tsx
index de798d591..42742726b 100644
--- a/frontend/src/react/settings/jav-browser-settings.tsx
+++ b/frontend/src/react/settings/jav-browser-settings.tsx
@@ -6,7 +6,7 @@ import { Input } from '@/components/base/input/input';
import { Select, SelectItem } from '@/components/base/select/select';
import { apiGet, apiSend, errorMessage } from '../../api';
import { SourceLabel } from '../components/source-label';
-import { ErrorText, FieldLabel, Footer, Help, Section, SectionSkeleton, Stack } from './section';
+import { ErrorText, FieldLabel, Footer, Help, Section, SectionSkeleton, Stack, useRememberedBody } from './section';
import { busyProps, useAction } from './use-action';
import { UserscriptStatus } from './userscript-status';
@@ -22,7 +22,9 @@ export function JavBrowserSettings({ receipt, refreshKey }: { receipt(message: s
const query = useQuery({ queryKey: ['jav-browser-settings', refreshKey],
queryFn: ({ signal }) => apiGet<State>(URL, signal), refetchOnMount: 'always', refetchOnWindowFocus: 'always' });
if (query.error && !query.data) return <ErrorText>{errorMessage(query.error)}</ErrorText>;
- if (query.isFetching && !query.data) return <SectionSkeleton title="浏览器添加 JAV" label="正在读取浏览器添加设置" height={100} />;
+ /* 底栏键的字随启用与否变,高度不变:等待时先画没启用时的那一颗。 */
+ if (query.isFetching && !query.data) return <SectionSkeleton title="浏览器添加 JAV" label="正在读取浏览器添加设置"
+ body="javBrowser" actions={<Button type="button" disabled>启用并生成令牌</Button>} />;
return query.data ? <BrowserForm initial={query.data} receipt={receipt} /> : null;
}
@@ -31,6 +33,7 @@ function BrowserForm({ initial, receipt }: { initial: State; receipt(message: st
const [provider, setProvider] = useState(initial.provider);
const [token, setToken] = useState('');
const action = useAction();
+ const body = useRememberedBody<HTMLDivElement>('javBrowser', [initial]);
useEffect(() => {
setState(initial);
setProvider(current => initial.providers.some(item => item.key === current) ? current : initial.provider);
@@ -48,6 +51,7 @@ function BrowserForm({ initial, receipt }: { initial: State; receipt(message: st
const ready = state.providers.some(item => item.key === provider && item.configured && item.target);
return <Section title="浏览器添加 JAV">
<Stack>
+ <div ref={body} className="flex min-w-0 flex-col gap-4">
<UserscriptStatus enabled={state.enabled} release={state.userscript} />
<div className="flex flex-col gap-1"><FieldLabel>浏览器添加的下载渠道</FieldLabel>
<Select aria-label="浏览器添加的下载渠道" selectedKey={provider || null} placeholder="暂无可用渠道"
@@ -71,6 +75,7 @@ function BrowserForm({ initial, receipt }: { initial: State; receipt(message: st
}} {...busyProps(action.busy === 'copy')}>复制配对信息</Button></div>
<Help>在用户脚本设置的「Peach 地址」中粘贴配对信息,即可填好地址与令牌。</Help>
</> : null}
+ </div>
{action.error ? <ErrorText>{action.error}</ErrorText> : null}
</Stack>
<Footer>
diff --git a/frontend/src/react/settings/section.tsx b/frontend/src/react/settings/section.tsx
index cb895c3e1..22961d4a2 100644
--- a/frontend/src/react/settings/section.tsx
+++ b/frontend/src/react/settings/section.tsx
@@ -8,6 +8,8 @@ import type { ComponentType, CSSProperties, FormEvent, MouseEvent, ReactNode } f
import { RiArrowRightSLine, RiExternalLinkLine } from '@remixicon/react';
import { setCollapseOpen } from '@peach/legacy/ui';
+import { rememberSectionHeight, SECTION_BODY, sectionBodyHeight, type SectionBody } from '../../configuration-skeleton';
+
import { SettingsCard, SettingsSectionLabel } from '@/components/application/settings/settings-rows';
import { LinkButton } from '@/components/base/buttons/link-button';
import { cx } from '@/utils/cx';
@@ -57,18 +59,32 @@ export function Stack({ divided = false, children }: { divided?: boolean; childr
: <div className="flex flex-col gap-4 py-4 pr-3 empty:hidden">{children}</div>;
}
-/** 分区首次取数:标题与外框照最终样子先画,正文按 `height` 占一块骨架;状态名只给辅助技术。 */
-export function SectionSkeleton({ title, label, height }: { title: string; label: string; height: number }) {
+/** 分区首次取数:标题、外框与底栏照最终样子先画,正文按 `body` 记下的上次高度占一块骨架;
+ * 底栏的按钮由调用方给,等待时一律禁用。状态名只给辅助技术。 */
+export function SectionSkeleton({ title, label, body, actions }: {
+ title: string; label: string; body: SectionBody; actions?: ReactNode;
+}) {
return <Section title={title}>
<Stack>
<div data-skeleton aria-busy="true" aria-label={label}>
<div className="h-(--skeleton-h) w-full rounded-2lg bg-background-tertiary-default"
- style={{ '--skeleton-h': `${height}px` } as CSSProperties} />
+ style={{ '--skeleton-h': `${sectionBodyHeight(body)}px` } as CSSProperties} />
</div>
</Stack>
+ {actions ? <Footer>{actions}</Footer> : null}
</Section>;
}
+/** 分区正文画好后记下高度,下次首屏骨架(整页的与分区的)按它占位。只在 `deps` 变化时量:
+ * 使用者展开、收起之后的高度不算,那不是下一次打开时的样子。 */
+export function useRememberedBody<T extends HTMLElement>(body: SectionBody, deps: readonly unknown[]) {
+ const node = useRef<T>(null);
+ useLayoutEffect(() => {
+ if (node.current) rememberSectionHeight(SECTION_BODY[body].key, node.current.offsetHeight);
+ }, deps);
+ return node;
+}
+
/** 底栏:左边一句说这颗按钮此刻意味着什么,右边是按钮。
*
* 底色比卡面暗一点点,通到卡片左右两沿(旧 `.geist-fieldset-footer` 的 `--board-card-foot`):
diff --git a/frontend/src/react/settings/service-preferences.tsx b/frontend/src/react/settings/service-preferences.tsx
index e0d9348c0..ad4b70c41 100644
--- a/frontend/src/react/settings/service-preferences.tsx
+++ b/frontend/src/react/settings/service-preferences.tsx
@@ -120,7 +120,8 @@ function FollowScheduleRow() {
return (
<>
<SettingsRow label="自动检查更新">
- <div id="followScheduleSetting" className="flex min-w-0 flex-wrap items-center justify-end gap-2">
+ {/* 间隔框只在开着时出现;这一行按有框的高度留位,读回状态时下面几行不跟着动。 */}
+ <div id="followScheduleSetting" className="flex min-h-9 min-w-0 flex-wrap items-center justify-end gap-2">
<Switch aria-label="自动检查更新" isSelected={data?.enabled === true} isDisabled={blocked}
onChange={(on) => {
localStorage.setItem('peach.number.followScheduleSetting', String(remembered.current));
@@ -150,7 +151,13 @@ function FeedScheduleRow() {
const status = useQuery({ queryKey: FEED_SCHEDULE_KEY, queryFn: ({ signal }) => fetchFeedSchedule(signal),
refetchOnMount: 'always', refetchInterval: (query) => schedulePollInterval(query.state.data) });
const data = status.data;
- if (!data) return null;
+ /* 首次读取时先占住这一行:读数回来再填字,下面的行不往下跳。 */
+ if (!data) {
+ return status.isPending ? <SettingsRow label="订阅源拉取">
+ <span data-skeleton aria-busy="true" aria-label="正在读取订阅源拉取间隔"
+ className="block h-4 w-16 rounded-2lg bg-background-tertiary-default" />
+ </SettingsRow> : null;
+ }
const minutes = data.interval_minutes;
const interval = minutes % 60 ? `每 ${minutes} 分钟` : `每 ${minutes / 60} 小时`;
return (
diff --git a/frontend/src/react/settings/source-settings.tsx b/frontend/src/react/settings/source-settings.tsx
index 42baa6881..468f25143 100644
--- a/frontend/src/react/settings/source-settings.tsx
+++ b/frontend/src/react/settings/source-settings.tsx
@@ -22,7 +22,7 @@ export function SourceSettings({ data, receipt, panel }: ConfigurationGroupProps
? <Credentials data={credentials.data} readOnly={Boolean(data.ledger_read_only)} toast={receipt} embedded />
: credentials.error
? <Note tone="error" title="来源凭据未取得">{errorMessage(credentials.error)}</Note>
- : panel?.active !== false ? <SectionSkeleton title="来源凭据" label="正在读取来源凭据" height={100} /> : null}
+ : panel?.active !== false ? <SectionSkeleton title="来源凭据" label="正在读取来源凭据" body="credentials" /> : null}
<FollowPreferenceRows receipt={receipt} />
<IndexerSettings receipt={receipt} />
{data.entry_links ? <EntryLinksForm initial={data.entry_links} receipt={receipt} /> : null}
diff --git a/frontend/test/react/indexer-settings.test.tsx b/frontend/test/react/indexer-settings.test.tsx
index 5b3628c0c..b5f4cb259 100644
--- a/frontend/test/react/indexer-settings.test.tsx
+++ b/frontend/test/react/indexer-settings.test.tsx
@@ -21,3 +21,25 @@ it('进入资源搜索设置时先读取当前值,再创建表单草稿', asyn
expect(host.querySelector<HTMLInputElement>('input')?.value).toBe('当前名称');
expect(host.querySelector('[data-skeleton]')).toBeNull();
});
+
+it('骨架照终态画底栏两颗禁用的键,正文按上次画好的高度占位', async () => {
+ const state = { indexers: [], max_indexers: 4 };
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => state })));
+ const height = vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(86);
+ const first = await mount(<QueryClientProvider client={queryClient}><IndexerSettings receipt={vi.fn()} /></QueryClientProvider>);
+ await settle();
+ expect(first.querySelector('form[aria-label="资源搜索"]')).not.toBeNull();
+ height.mockRestore();
+
+ const hold = pending<unknown>();
+ vi.stubGlobal('fetch', vi.fn(() => hold.answer));
+ const host = await mount(<QueryClientProvider client={queryClient}><IndexerSettings receipt={vi.fn()} /></QueryClientProvider>);
+ const keys = [...host.querySelectorAll<HTMLButtonElement>('section[aria-label="资源搜索"] button')];
+ expect(keys.map((key) => [key.textContent, key.disabled])).toEqual([['添加索引器', true], ['保存配置', true]]);
+ const block = host.querySelector<HTMLElement>('[data-skeleton] > div');
+ expect(block?.style.getPropertyValue('--skeleton-h')).toBe('86px');
+ await hold.release({ ok: true, status: 200, json: async () => state });
+ await settle();
+ expect(host.querySelector('[data-skeleton]')).toBeNull();
+ localStorage.removeItem('peach.configuration.section-heights.v1');
+});
diff --git a/frontend/test/react/service-preferences.test.tsx b/frontend/test/react/service-preferences.test.tsx
index 67edfb8c8..f690d9b70 100644
--- a/frontend/test/react/service-preferences.test.tsx
+++ b/frontend/test/react/service-preferences.test.tsx
@@ -5,7 +5,8 @@ import { afterEach, expect, it, vi } from 'vitest';
import { appSettingsStore } from '../../src/appearance/settings';
import { queryClient } from '../../src/react/query';
import { FollowPreferenceRows, VideoThumbnailRow } from '../../src/react/settings/service-preferences';
-import { buttonNamed, choose, click, mount, mountRoot, settle, type } from './render';
+import { configurationContentSkeleton } from '../../src/configuration-skeleton';
+import { buttonNamed, choose, click, mount, mountRoot, pending, settle, type } from './render';
notifyManager.setScheduler((notify) => notify());
@@ -161,3 +162,20 @@ it('服务设置重新进入时读取最新状态,关闭自动检查后保留
]);
expect(second.querySelector<HTMLInputElement>('input[aria-label="自动检查间隔"]')?.value).toBe('180');
});
+
+it('首次读取时「关注采集」就是五行,与配置页整页骨架同一组行;读回之后行数不变', async () => {
+ const hold = pending<unknown>();
+ vi.stubGlobal('fetch', vi.fn(() => hold.answer));
+ const host = await mount(<QueryClientProvider client={queryClient}><FollowPreferenceRows receipt={vi.fn()} /></QueryClientProvider>);
+ const labels = (root: ParentNode) => [...root.querySelectorAll('section[aria-label="关注采集"] p.text-body-regular')].map((node) => node.textContent);
+ const page = document.createElement('div');
+ page.innerHTML = configurationContentSkeleton('来源与订阅');
+ const waiting = labels(host);
+ expect(waiting).toEqual(['自动检查更新', '订阅源拉取', '首次采集范围', '头像刷新', 'favicon 刷新']);
+ expect(labels(page), '整页骨架画的也是这五行').toEqual(waiting);
+ expect(host.querySelector('[data-skeleton][aria-label="正在读取订阅源拉取间隔"]')).not.toBeNull();
+ server();
+ await hold.release({ ok: true, status: 200, json: async () => ({ available: true, enabled: true, interval_minutes: 360 }) });
+ await settle();
+ expect(labels(host)).toEqual(waiting);
+});