Peach: Local-first video metadata scraper and media manager.
feat(settings): 按使用场景组织偏好与服务配置入口
longmeidaodc46ffda45a3
diff --git a/frontend/e2e/design-settings.test.ts b/frontend/e2e/design-settings.test.tsindex 0437c18ab..cddf9252e 100644--- a/frontend/e2e/design-settings.test.ts+++ b/frontend/e2e/design-settings.test.ts@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';import { describe, it } from 'node:test';import type { Browser, Page } from 'playwright-core';import { openFollowFeed } from './follow-fixture.ts';-import { configurationBody, expectBody, requiredEnv, settle, visit, VIEWPORTS } from './harness.ts';+import { requiredEnv, settle, visit, VIEWPORTS } from './harness.ts';import { openHome, openPanel, ORDER, PANEL, stubServer } from './settings-fixture.ts';import {DESKTOP, MOBILE, tokenColor, settledRun, openActivity, TASTE_CATEGORIES, TASTE_FACE, openTaste, openIndexPage,@@ -276,42 +276,6 @@ describe('设计决定:设置、口味、统计与筛选玻璃', () => {/* ADR-0050:设置弹层只放一行一个值、改完就生效的控件;带「保存配置」的表单在配置页,要确认、要看进度的长任务在数据管理页,订阅源在关注管理页。 */- it('设置弹层「这台电脑」只有摘要卡,按钮直达配置页;媒体修复与订阅源都不在设置和配置页里', { timeout: 60_000 }, async () => {- const opened = await visit(browser, '/', DESKTOP);- try {- const { page } = opened;- await settle(page);- await page.locator('#settingsBtn').click();- const panel = page.locator('#settingsPanel');- await panel.getByRole('tab', { name: '这台电脑' }).click({ timeout: 10_000 });- const machine = panel.locator('#machineSettings');- const go = machine.getByRole('button', { name: '打开配置页', exact: true });- await go.waitFor({ state: 'visible', timeout: 10_000 });- assert.deepEqual(await machine.locator('dt').allTextContents(), ['媒体库', '端口', '更新']);- assert.equal(await machine.locator('input, textarea, select, form, [role="switch"], [aria-haspopup="listbox"]').count(), 0,- '摘要卡里出现了可编辑的控件');- assert.equal(await panel.locator('.ui-configpage').count(), 0, '设置弹层里又挂了一份配置页');- for (const text of ['媒体修复', '订阅源', '保持登录时间']) {- assert.equal(await panel.getByText(text, { exact: true }).count(), 0, `设置弹层里还有「${text}」`);- }-- await go.click();- await expectBody(page, '/configuration', configurationBody(page));- assert.equal(new URL(page.url()).pathname, '/configuration');- assert.equal(await panel.isHidden(), true, '去配置页之后设置弹层没有关');- await settle(page);- for (const text of ['媒体修复', '订阅源']) {- assert.equal(await page.locator('#stats').getByText(text, { exact: true }).count(), 0, `配置页上还有「${text}」`);- }- const entry = page.locator('[data-manage-bar] [data-manage="configuration"]');- await entry.waitFor({ state: 'attached', timeout: 10_000 });- assert.equal(await entry.getAttribute('aria-pressed'), 'true', '管理菜单里的「配置」没有标成当前页');- assert.deepEqual(opened.problems, []);- } finally {- await opened.close();- }- });-/* 设置面板:盖住整页的弹层与作品详情浮窗同一档遮罩、同一组进出场;遮罩不带模糊,值只来自 `--scrim`。动效要真跑起来才读得到关键帧名,这一条自建不减动态的上下文。 */it('设置面板的遮罩取 --scrim、不带模糊、压在最顶层,卡片用弹层那一组关键帧进出', { timeout: 60_000 }, async () => {@@ -413,7 +377,7 @@ describe('设计决定:设置、口味、统计与筛选玻璃', () => {const glide = () => nav.locator('[data-settings-glide]').evaluate((node) => Math.round(node.getBoundingClientRect().top));const top = (name: string) => nav.getByRole('tab', { name, exact: true }).evaluate((node) => Math.round(node.getBoundingClientRect().top));- const selected = await nav.getByRole('tab', { name: '界面', exact: true }).evaluate((node) => {+ const selected = await nav.getByRole('tab', { name: '外观与导航', exact: true }).evaluate((node) => {const style = getComputedStyle(node), icon = getComputedStyle(node.querySelector('svg')!);return { face: style.backgroundColor, ring: style.boxShadow, icon: [icon.width, icon.height, icon.fill === style.color, icon.stroke] };});@@ -421,16 +385,16 @@ describe('设计决定:设置、口味、统计与筛选玻璃', () => {assert.equal(selected.ring, 'none');// Remix 的线条是 `fill` 画出的轮廓,全站默认的 `stroke:currentColor;fill:none` 会让它整枚消失。assert.deepEqual(selected.icon, ['20px', '20px', true, 'none']);- assert.equal(await glide(), await top('界面'), '玻璃没有落在当前项上');+ assert.equal(await glide(), await top('外观与导航'), '玻璃没有落在当前项上');- await nav.getByRole('tab', { name: '播放', exact: true }).hover();- const target = await top('播放');+ await nav.getByRole('tab', { name: '浏览与播放', exact: true }).hover();+ const target = await top('浏览与播放');await page.waitForFunction(([want]) => Math.round(document.querySelector('#settingsPanel [data-settings-glide]')!.getBoundingClientRect().top) === want, [target]);- assert.equal(await nav.getByRole('tab', { name: '界面', exact: true }).getAttribute('aria-selected'), 'true',+ assert.equal(await nav.getByRole('tab', { name: '外观与导航', exact: true }).getAttribute('aria-selected'), 'true','指针移上去就换了分区');await page.locator(`${PANEL} [data-settings-scroll]`).hover();- const home = await top('界面');+ const home = await top('外观与导航');await page.waitForFunction(([want]) => Math.round(document.querySelector('#settingsPanel [data-settings-glide]')!.getBoundingClientRect().top) === want, [home]);assert.deepEqual(opened.problems, []);diff --git a/frontend/e2e/settings-fixture.ts b/frontend/e2e/settings-fixture.tsindex 158fed1c0..2174a5bb3 100644--- a/frontend/e2e/settings-fixture.ts+++ b/frontend/e2e/settings-fixture.ts@@ -52,10 +52,10 @@ export async function stubServer(page: Page): Promise<Server> {}/** 齿轮打开面板并停在 `section` 那一格。窄屏下齿轮收在抽屉底部,直接派发点击,两种宽度走同一条入口。 */-export async function openPanel(page: Page, section = '界面'): Promise<void> {+export async function openPanel(page: Page, section = '外观与导航'): Promise<void> {await page.locator('#settingsBtn').evaluate((button: HTMLElement) => button.click());await page.locator(`${PANEL}:not([hidden])`).waitFor({ timeout: 10_000 });- if (section !== '界面') await page.locator(PANEL).getByRole('tab', { name: section, exact: true }).click();+ if (section !== '外观与导航') await page.locator(PANEL).getByRole('tab', { name: section, exact: true }).click();await page.locator(PANEL).getByRole('tab', { name: section, exact: true }).and(page.locator('[aria-selected="true"]')).waitFor({ timeout: 5_000 });}diff --git a/frontend/e2e/settings-panel.test.ts b/frontend/e2e/settings-panel.test.tsindex 4d33a5f71..784ab8a97 100644--- a/frontend/e2e/settings-panel.test.ts+++ b/frontend/e2e/settings-panel.test.ts@@ -49,6 +49,30 @@ describe('设置面板', () => {before(async () => { browser = await launch() });after(async () => { await browser?.close() });+ it('五个偏好分区各自显示对应设置,服务配置单独直达配置页', { timeout: 60_000 }, async () => {+ const opened = await openHome(browser);+ const { page } = opened;+ try {+ await openPanel(page);+ assert.deepEqual(await page.locator(PANEL).getByRole('tab').allTextContents(),+ ['外观与导航', '浏览与播放', 'JAV 与新作', '搜索与推荐', '内容显示']);+ for (const [name, field] of [+ ['外观与导航', '#themeSetting'], ['浏览与播放', '#detailAutoplaySetting'],+ ['JAV 与新作', '#javImageSetting'], ['搜索与推荐', '#relatedLimitSetting'], ['内容显示', '#censorSetting'],+ ]) {+ await page.locator(PANEL).getByRole('tab', { name, exact: true }).click();+ await page.locator(field!).waitFor({ state: 'visible' });+ assert.deepEqual((await layout(page)).offenders, []);+ }+ assert.equal(await page.locator(`${PANEL} #videoThumbnailSetting, ${PANEL} #followScheduleSetting`).count(), 0);+ const configuration = page.locator(PANEL).getByRole('button', { name: '服务配置', exact: true });+ await configuration.click();+ await page.waitForURL((url) => url.pathname === '/configuration');+ await page.locator(PANEL).waitFor({ state: 'hidden' });+ assert.deepEqual(opened.problems, []);+ } finally { await opened.close() }+ });+it('齿轮打开、关闭键与 Escape 关上;焦点进来落在关闭键、Tab 在面板里转圈、关上后回到齿轮', { timeout: 60_000 }, async () => {const opened = await openHome(browser);const { page } = opened;@@ -132,12 +156,12 @@ describe('设置面板', () => {assert.equal(await box.isChecked(), false);assert.equal((await stored(page)).uiSounds, false);const silent = await tones();- await page.locator(PANEL).getByRole('tab', { name: '浏览', exact: true }).click();- await page.locator(PANEL).getByRole('tab', { name: '界面', exact: true }).click();+ await page.locator(PANEL).getByRole('tab', { name: '浏览与播放', exact: true }).click();+ await page.locator(PANEL).getByRole('tab', { name: '外观与导航', exact: true }).click();assert.equal(await tones(), silent, '关掉界面音效之后点分区还在出声');await box.click();assert.equal((await stored(page)).uiSounds, true);- await page.locator(PANEL).getByRole('tab', { name: '浏览', exact: true }).click();+ await page.locator(PANEL).getByRole('tab', { name: '浏览与播放', exact: true }).click();assert.ok(await tones() > silent, '打开界面音效之后点分区不出声');assert.deepEqual(opened.problems, []);} finally {@@ -187,14 +211,14 @@ describe('设置面板', () => {const opened = await openHome(browser);const { page } = opened;try {- await openPanel(page, '浏览');+ await openPanel(page, 'JAV 与新作');await page.locator('#javImageSetting label:has(input[value="thumbnail"])').click();assert.equal((await stored(page)).javImage, 'thumbnail');assert.equal(await page.locator('#javImageSetting input[value="thumbnail"]').isChecked(), true);+ await page.locator(PANEL).getByRole('tab', { name: '浏览与播放', exact: true }).click();await pick(page, '#defaultSortSetting', 'seed');await page.locator('#defaultSortDirectionSetting').waitFor({ state: 'hidden', timeout: 5_000 });- assert.equal(await page.locator('#sortDirectionHelp').textContent(), '随机排序不使用方向。');await pick(page, '#defaultSortSetting', 'rating');await page.locator('#defaultSortDirectionSetting').waitFor({ state: 'visible', timeout: 5_000 });@@ -210,38 +234,6 @@ describe('设置面板', () => {}});- it('视频缩略图档位与关注自动更新写这台机器的接口,回来的状态当场换上', { timeout: 60_000 }, async () => {- const opened = await openHome(browser);- const { page, server } = opened;- try {- await openPanel(page, '播放');- await page.locator('#videoThumbnailSetting [data-select-trigger]:not([disabled])').waitFor({ timeout: 10_000 });- await pick(page, '#videoThumbnailSetting', 'coarse');- assert.deepEqual(await posted(page, server, '/api/thumbnail-jobs', 'mode'), { mode: 'coarse' });- await page.waitForFunction(() =>- document.querySelector('#videoThumbnailSetting [data-select-label]')?.textContent?.includes('粗略'));- assert.match(await page.locator('#videoThumbnailState').textContent() || '', /选定档位后/);-- await page.locator(PANEL).getByRole('tab', { name: '关注', exact: true }).click();- const minutes = page.locator('#followScheduleSetting input[type="number"]');- await minutes.waitFor({ state: 'visible', timeout: 10_000 });- await page.waitForFunction(() => {- const input = document.querySelector<HTMLInputElement>('#followScheduleSetting input[type="number"]');- return input && !input.disabled && input.value === '180';- });- await minutes.fill('240');- await minutes.press('Enter');- assert.deepEqual(await posted(page, server, '/api/follow/schedule', 'interval_minutes'),- { enabled: true, interval_minutes: 240 });- await page.waitForFunction(() =>- document.querySelector('#followScheduleState')?.textContent?.includes('新增 3'));- assert.equal(await minutes.inputValue(), '240');- assert.deepEqual(opened.problems, []);- } finally {- await opened.close();- }- });-it('侧栏排序拖动一行:侧栏当场按新顺序重排,再写进账本', { timeout: 60_000 }, async () => {const opened = await openHome(browser);const { page, server } = opened;@@ -275,42 +267,6 @@ describe('设置面板', () => {}});- /* 面板与配置页没有重复的控件;两边共用的是配置快照那一个 Query 键:摘要卡读它,配置页- 「刷新挂载状态」把重取回来的整份写回它。 */- it('配置页刷新回来的配置,面板「这台电脑」那一格当场看到,不再自己重取', { timeout: 60_000 }, async () => {- const opened = await openHome(browser);- const { page } = opened;- let libraries = 1;- let reads = 0;- try {- await page.route((url) => url.pathname === '/api/configuration', async (route) => {- reads += 1;- const response = await route.fetch();- return route.fulfill({ response, json: { ...(await response.json()), library_count: libraries } });- });- await openPanel(page, '这台电脑');- const machine = page.locator('#machineSettings');- await machine.getByText('1 个', { exact: true }).waitFor({ timeout: 10_000 });- await machine.getByRole('button', { name: '打开配置页', exact: true }).click();- await page.locator(PANEL).waitFor({ state: 'hidden', timeout: 5_000 });- await page.waitForURL((url) => url.pathname === '/configuration');- await page.getByRole('tablist', { name: '配置分区' }).getByRole('tab', { name: '媒体', exact: true }).click();- const refresh = page.getByRole('button', { name: '刷新挂载状态', exact: true });- await refresh.waitFor({ timeout: 15_000 });- libraries = 2;- const before = reads;- await refresh.click();- await until(page, () => reads === before + 1, '刷新挂载状态没有重取配置');- await page.waitForFunction(() => !document.querySelector('[aria-busy="true"]'));- await openPanel(page, '这台电脑');- await machine.getByText('2 个', { exact: true }).waitFor({ timeout: 5_000 });- assert.equal(reads, before + 1, '面板为「这台电脑」又取了一遍配置,没用配置页刚写回的那一份');- assert.deepEqual(opened.problems, []);- } finally {- await opened.close();- }- });-it(`手机 ${MOBILE.width} 宽:面板铺满不横向溢出,分区横排可切换`, { timeout: 60_000 }, async () => {const opened = await openHome(browser, MOBILE);const { page } = opened;@@ -324,7 +280,7 @@ describe('设置面板', () => {const tops = await page.locator(PANEL).getByRole('tab').evaluateAll((nodes) =>nodes.slice(0, 3).map((node) => Math.round(node.getBoundingClientRect().top)));assert.equal(new Set(tops).size, 1, '窄屏下分区没有横排');- await page.locator(PANEL).getByRole('tab', { name: '浏览', exact: true }).click();+ await page.locator(PANEL).getByRole('tab', { name: 'JAV 与新作', exact: true }).click();await page.locator('#javImageSetting').waitFor({ state: 'visible', timeout: 5_000 });assert.deepEqual((await layout(page)).offenders, []);assert.deepEqual(opened.problems, []);diff --git a/frontend/src/react/settings-panel/settings-data.ts b/frontend/src/react/settings-panel/settings-data.tsindex 04f7cdbef..20df3f653 100644--- a/frontend/src/react/settings-panel/settings-data.ts+++ b/frontend/src/react/settings-panel/settings-data.ts@@ -1,4 +1,4 @@-/* 设置面板的三份服务端数据,各一个 Query 键。+/* 设置偏好与服务配置的三份服务端数据,各一个 Query 键。** - `['settings']`:跟账本走、所有访问端同一份的那几项(`/api/settings`,`src/peach/web_settings.py`)。* 面板每次打开都重取一次,取回来交给壳对账(`host.syncRemote`):界面偏好的真相仍是壳里那一份@@ -6,13 +6,11 @@* - `['follow-schedule']`:这台机器上关注自动更新的档位与上次运行状态。* - `['thumbnail-jobs']`:视频缩略图采集的档位与状态。档位跟着机器走,不存在浏览器里。*- * 面板常驻不卸载,缓存默认挂载不重取(`../query.ts`),所以每次打开面板都由它自己重取一遍。 */+ * 面板常驻不卸载,每次打开重取设置;服务配置在挂载时重取各自的数据。 */import { useMutation, type QueryClient } from '@tanstack/react-query';import { apiGet, apiSend } from '../../api';-import { errorHeadline } from '../activity/tasks';import { queryClient } from '../query';-import { localTime } from '../time';export const SETTINGS_URL = '/api/settings';export const FOLLOW_SCHEDULE_URL = '/api/follow/schedule';@@ -58,15 +56,8 @@ export const fetchFollowSchedule = (signal?: AbortSignal) =>export const fetchThumbnailJobs = (signal?: AbortSignal) =>apiGet<ThumbnailJobStatus>(THUMBNAIL_JOBS_URL, signal);-/** 打开面板那一下:三份都按服务端此刻的值重取,在途的那一趟直接复用。返回账本那一份,- * 取不到时是 null——失败由两行机器状态各自显示,账本那份取不到就不对账。 */+/** 打开偏好弹窗时重取共享设置;采集状态由服务配置中的控件读取。 */export function refreshPanelData(client: QueryClient = queryClient): Promise<SyncedSettings | null> {- void client.fetchQuery({- queryKey: FOLLOW_SCHEDULE_KEY, queryFn: ({ signal }) => fetchFollowSchedule(signal), staleTime: 0,- }).catch(() => null);- void client.fetchQuery({- queryKey: THUMBNAIL_JOBS_KEY, queryFn: ({ signal }) => fetchThumbnailJobs(signal), staleTime: 0,- }).catch(() => null);return client.fetchQuery({queryKey: SETTINGS_KEY, queryFn: ({ signal }) => fetchSettings(signal), staleTime: 0,}).catch(() => null);@@ -94,22 +85,3 @@ export function useSaveThumbnailMode() {onSuccess: (status) => queryClient.setQueryData(THUMBNAIL_JOBS_KEY, status),});}--export function followScheduleCopy(status: FollowScheduleStatus): string {- if (!status.available) return '只在账本写入端运行';- if (status.running) return '正在检查全部来源…';- // 面板里一行说明放不下整段堆栈,只说异常那一行;全文在活动页这一轮的卡片里。- if (status.last_error) return `上次失败:${errorHeadline(status.last_error)}`;- if (status.last_finished_at) return `上次完成 ${localTime(status.last_finished_at)} · 新增 ${(status.last_added || 0).toLocaleString()}`;- if (status.next_run_at) return `下次 ${localTime(status.next_run_at)}`;- return status.enabled ? '等待首次运行' : '已关闭';-}--export function videoThumbnailCopy(status: ThumbnailJobStatus): string {- if (status.status === 'running') return '正在采集,进度在活动页查看。';- if (status.status === 'failed') return `上一轮采集停下了:${errorHeadline(status.stopped) || '原因未取得'}`;- if (status.status === 'complete') return status.stopped ? '上一轮采集已按停。' : '上一轮采集已完成。';- return status.mode === 'off'- ? '关闭时不采集;已经生成的图留在盘上,清理走数据管理页。'- : '选定档位后从最近看过的片子开始采集。';-}diff --git a/frontend/src/react/settings-panel/settings-panel-api.ts b/frontend/src/react/settings-panel/settings-panel-api.tsindex 92225121d..cd5a22e83 100644--- a/frontend/src/react/settings-panel/settings-panel-api.ts+++ b/frontend/src/react/settings-panel/settings-panel-api.ts@@ -80,7 +80,7 @@ export interface SettingsPanelHost {}export interface SettingsPanelApi {- /** 打开面板;`section` 给分区名(「界面」「浏览」…)时直接落到那一页。 */+ /** 打开面板;`section` 给分区名(「外观与导航」「浏览与播放」…)时直接落到那一页。 */open(section?: string): void;close(): void;isOpen(): boolean;diff --git a/frontend/src/react/settings-panel/settings-panel.css b/frontend/src/react/settings-panel/settings-panel.cssindex 680082be1..5f74940a0 100644--- a/frontend/src/react/settings-panel/settings-panel.css+++ b/frontend/src/react/settings-panel/settings-panel.css@@ -408,6 +408,13 @@ html[class~=board-high-contrast] [data-settings-panel] [data-settings-card][data/* ── 分区切换与开合 ──* 分区切换靠 `hidden`:分组上写了 `display`,这一条要压过它们。 */[data-settings-panel] [data-setting-group][hidden]{display:none!important}+[data-settings-panel] [data-settings-service]{position:relative;z-index:1;margin-top:auto;padding-top:16px;border-top:1px solid var(--line-soft)}+[data-settings-panel] [data-settings-service] button{width:100%}+[data-settings-panel] [data-settings-service] button>svg:last-child{margin-left:auto}+[data-settings-panel] [data-settings-service] button:disabled{color:var(--muted);cursor:not-allowed}+[data-settings-panel] [data-settings-subheading]{margin:0;padding:16px 0 6px;color:var(--muted);font:var(--board-compact)}+[data-settings-panel] [data-settings-scroll] [data-settings-subheading]+[data-setting-row]{border-top:0}+@media(max-width:760px){[data-settings-panel] [data-settings-service]{margin-top:0;padding:0 0 0 12px;border-top:0;border-left:1px solid var(--line-soft);flex-shrink:0}}@keyframes settings-backdrop-in{from{opacity:0}to{opacity:1}}@keyframes settings-backdrop-out{from{opacity:1}to{opacity:0}}@keyframes settings-dialog-in{from{transform:translate3d(0,-40px,0);opacity:0}to{transform:translate3d(0,0,0);opacity:1}}diff --git a/frontend/src/react/settings-panel/settings-panel.tsx b/frontend/src/react/settings-panel/settings-panel.tsxindex 8e35a4170..9766e7eac 100644--- a/frontend/src/react/settings-panel/settings-panel.tsx+++ b/frontend/src/react/settings-panel/settings-panel.tsx@@ -8,44 +8,35 @@* 那几项经 `/api/settings` 写(`settings-data.ts`)。** 宿主不在 `.peach-react` 里:行、开关、下拉、拉条与色块都是全站共用的遗留控件,外观由- * `settings-panel.css` 与遗留样式表给。只有「这台电脑」那一格的摘要卡是 BoardUI,单独套一层。+ * `settings-panel.css` 与遗留样式表给。*- * 每次打开都像重新进一次这一屏:共用控件重画、数值框回到当前值、两份机器状态重取。+ * 每次打开时共用控件重画、数值框回到当前值,并重取共享设置。* 焦点先交给关闭钮,Tab 在面板里转圈,关掉后还给打开前那一枚。 */import {- useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore,+ useLayoutEffect, useRef, useState, useSyncExternalStore,type KeyboardEvent, type ReactNode,} from 'react';import { flushSync } from 'react-dom';-import { useQuery } from '@tanstack/react-query';--import { METADATA_REFRESH_DAYS } from '@peach/appearance';import {- attachOverlayScrollbar, closeAnchoredMenu, iconSwapHtml, loadingDotsHtml, moveGlidePane, noteHtml, revealTexts,- setActionBusy, setIconSwap, spinnerHtml, wireHorizontalScroller,+ attachOverlayScrollbar, closeAnchoredMenu, iconSwapHtml, moveGlidePane, revealTexts,+ setActionBusy, setIconSwap, wireHorizontalScroller,} from '@peach/legacy/ui';import { normalizeJavImage } from '../../jav-artwork';import { boundedPreference } from '../../number-setting';-import { prefetchConfiguration } from '../settings/configuration';-import { ConfigurationSummary } from '../settings/configuration-summary';import { GlowSettings } from './glow-settings';import { RemixIcon } from './icon';import { IconSwitch, SelectField } from './legacy-controls';import { NumberSetting } from './number-setting';import type { Choice, PanelSettings, SettingsPanelApi, SettingsPanelHost } from './settings-panel-api';-import {- FOLLOW_SCHEDULE_KEY, THUMBNAIL_JOBS_KEY, fetchFollowSchedule, fetchThumbnailJobs, followScheduleCopy,- refreshPanelData, useSaveFollowSchedule, useSaveSettings, useSaveThumbnailMode, videoThumbnailCopy,-} from './settings-data';+import { refreshPanelData, useSaveSettings } from './settings-data';import { SidebarOrder } from './sidebar-order';/* 左栏的分区,顺序即右边各组的顺序。字形按条目自己的名字取:整列取自 Remix,一家画的笔画才一样粗。 */const SECTIONS = [- ['界面', 'ri-palette-line'], ['浏览', 'ri-layout-grid-line'], ['播放', 'ri-play-circle-line'],- ['搜索', 'ri-search-line'], ['关注', 'ri-rss-line'], ['安全', 'ri-shield-check-line'],- ['这台电脑', 'ri-macbook-line'],+ ['外观与导航', 'ri-palette-line'], ['浏览与播放', 'ri-play-circle-line'],+ ['JAV 与新作', 'ri-film-line'], ['搜索与推荐', 'ri-search-line'], ['内容显示', 'ri-shield-check-line'],] as const;const SORT_OPTIONS: readonly Choice[] = [@@ -53,27 +44,21 @@ const SORT_OPTIONS: readonly Choice[] = [['dur', '时长'], ['size', '体积'], ['new', '入库时间'], ['played', '观看时间'],];const DIRECTION_OPTIONS: readonly Choice[] = [['desc', '降序'], ['asc', '升序']];-const THUMBNAIL_OPTIONS: readonly Choice[] = [['off', '关闭'], ['precise', '精准'], ['coarse', '粗略']];-const METADATA_OPTIONS: readonly Choice[] = [['7', '每周'], ['30', '每月'], ['90', '每季'], ['0', '从不']];const JAV_IMAGE_OPTIONS: readonly Choice[] = [['cover', '官方封面', ''], ['thumbnail', '预览图', '']];/* 新作那一行收不收合集由服务端按账本里的设置筛,这里的开关只是镜像:真相在 `/api/settings`。 */const FEED_COMPILATIONS = [- ['feedHideGroupSetting', 'feedHideGroupCompilations', '大合集', '新作收起大合集', 'feedHideGroupDescription',- '多人片段拼成的精选、总集和连发不进新作那一行,也不替它们补封面。'],- ['feedHideSoloSetting', 'feedHideSoloCompilations', '单人合集', '新作收起单人合集', 'feedHideSoloDescription',- '只有一位女优的精选与长时间合集,比如「8時間 BEST」。'],- ['feedHideExcerptSetting', 'feedHideExcerpts', '切片', '新作收起切片', 'feedHideExcerptDescription',- '把出过的正片剪成十几分钟单卖的,比如ハイライト厂牌。'],+ ['feedHideGroupSetting', 'feedHideGroupCompilations', '大合集', '隐藏大合集'],+ ['feedHideSoloSetting', 'feedHideSoloCompilations', '单人合集', '隐藏单人合集'],+ ['feedHideExcerptSetting', 'feedHideExcerpts', '切片', '隐藏切片'],] as const;type CompilationKey = typeof FEED_COMPILATIONS[number][1];const FOCUSABLE = 'button:not([disabled]),input:not([disabled]),textarea:not([disabled]),a[href]';-type Machine = 'none' | 'note' | 'summary';-interface View { open: boolean; closing: boolean; epoch: number; tab: number; machine: Machine }+interface View { open: boolean; closing: boolean; epoch: number; tab: number; configurable: boolean | null }let host: SettingsPanelHost | null = null;-let view: View = { open: false, closing: false, epoch: 0, tab: 0, machine: 'none' };+let view: View = { open: false, closing: false, epoch: 0, tab: 0, configurable: null };let transition = 0;let returnFocus: Element | null = null;const listeners = new Set<() => void>();@@ -94,15 +79,12 @@ function update(patch: Partial<View>): void {flushSync(notify);}-/* 「这台电脑」:能在这台设备上改配置时放摘要卡,否则一句话说清去哪儿改。摘要卡一旦挂上就留着;- 判据取回来之前面板已经关了,就退回未挂状态,下次打开重来。 */+/* 服务配置入口按当前设备的配置权限放行。 */async function checkMachine(current: SettingsPanelHost): Promise<void> {- if (view.machine === 'summary') return;+ const epoch = view.epoch;const configurable = await current.configurable();- if (!view.open) return;- if (!configurable) { update({ machine: 'note' }); return }- try { await prefetchConfiguration(new AbortController().signal) } catch { /* 摘要卡自己报读取失败 */ }- if (view.open) update({ machine: 'summary' });+ if (!view.open || view.epoch !== epoch) return;+ update({ configurable });}function open(section = ''): void {@@ -120,7 +102,7 @@ function open(section = ''): void {/* 先发取数再画:第一次打开时查询还不存在,这一趟由 `fetchQuery` 建起来,组件画出来读到的就是在途的这一份,不会再发第二趟。 */const remote = refreshPanelData();- update({ open: true, closing: false, epoch: view.epoch + 1, tab: requested >= 0 ? requested : view.tab });+ update({ open: true, closing: false, configurable: null, epoch: view.epoch + 1, tab: requested >= 0 ? requested : view.tab });void remote.then((settings) => { if (settings) current.syncRemote(settings) });void checkMachine(current);queueMicrotask(() => document.getElementById('settingsClose')?.focus());@@ -175,12 +157,14 @@ function trapTab(event: KeyboardEvent<HTMLElement>): void {}const tabId = (index: number) => `settings-tab-${index}`;-const groupId = (index: number) => index === SECTIONS.length - 1 ? 'machineGroup' : `settings-group-${index}`;+const groupId = (index: number) => `settings-group-${index}`;/* 左栏当前项由一块滑过去的玻璃标出来,和左侧抽屉是同一件事的两种形态。坐标取 `offsetTop`不取屏幕坐标:面板开合自带一段缩放动画,量屏幕坐标会把正在走的那一下吃进来。玻璃跟着指针走,指针离开这一列就滑回当前那格;触点没有悬停,碰一下就滑过去等于替用户点了一次,所以挡在外面。 */-function SettingsNav({ tab, epoch, onSelect }: { tab: number; epoch: number; onSelect(index: number): void }) {+function SettingsNav({ tab, epoch, configurable, openConfiguration, onSelect }: {+ tab: number; epoch: number; configurable: boolean | null; openConfiguration(): void; onSelect(index: number): void;+}) {const nav = useRef<HTMLDivElement | null>(null);const glide = useRef<HTMLSpanElement | null>(null);const box = useRef<{ x: number; y: number; w: number; h: number } | null>(null);@@ -243,6 +227,12 @@ function SettingsNav({ tab, epoch, onSelect }: { tab: number; epoch: number; onS<RemixIcon name={icon} />{title}</button>))}+ <div data-settings-service="" role="presentation">+ <button type="button" disabled={configurable !== true} onClick={openConfiguration}+ title={configurable === false ? '请在运行 Peach 的设备上打开服务配置' : undefined}>+ <RemixIcon name="ri-settings-3-line" />服务配置<RemixIcon name="ri-arrow-right-line" />+ </button>+ </div></div>);}@@ -258,12 +248,12 @@ function Group({ index, tab, children }: { index: number; tab: number; children:/** 一行开关:整行是 label,点哪儿都切。说明那一句的 id 默认取开关 id 去掉 `Setting` 再接 `Description`。 */function ToggleRow({ id, title, description, describedBy = `${id.replace(/Setting$/, '')}Description`, checked, onToggle }: {- id: string; title: string; description: string; describedBy?: string; checked: boolean; onToggle(on: boolean): void;+ id: string; title: string; description?: string; describedBy?: string; checked: boolean; onToggle(on: boolean): void;}) {return (<label data-setting-row="">- <span><b>{title}</b><small id={describedBy}>{description}</small></span>- <input data-toggle="" type="checkbox" id={id} role="switch" aria-describedby={describedBy}+ <span><b>{title}</b>{description ? <small id={describedBy}>{description}</small> : null}</span>+ <input data-toggle="" type="checkbox" id={id} role="switch" aria-describedby={description ? describedBy : undefined}checked={checked} onChange={(event) => onToggle(event.target.checked)} /></label>);@@ -281,11 +271,6 @@ function Row({ title, description, kind, children }: {);}-const Html = ({ html, ...props }: { html: string; id?: string; 'aria-live'?: 'polite' }) =>- <small {...props} dangerouslySetInnerHTML={{ __html: html }} />;-const savingHtml = () => `${spinnerHtml('保存中')}<span>正在保存…</span>`;-const errorText = (error: unknown, fallback: string) => (error instanceof Error && error.message) || fallback;-function SettingsPanel({ host: current, view: shown }: { host: SettingsPanelHost; view: View }) {/* 订阅只为重画:读的是活对象 `store.value`,版本号本身不用。 */useSyncExternalStore(current.store.subscribe, current.store.version);@@ -344,47 +329,47 @@ function SettingsPanel({ host: current, view: shown }: { host: SettingsPanelHost<svg viewBox="0 0 24 24"><use href="#i-x" /></svg></button></div>- <SettingsNav tab={shown.tab} epoch={epoch} onSelect={select} />+ <SettingsNav tab={shown.tab} epoch={epoch} configurable={shown.configurable} onSelect={select}+ openConfiguration={() => { close(); current.openConfiguration() }} /><div data-settings-scroll="" ref={scroll}><Group index={0} tab={shown.tab}>- <Row title="主题" description="跟随系统,或固定用浅色、深色。">+ <Row title="主题"><IconSwitch id="themeSetting" name="theme" legend="主题" options={current.themeOptions} value={settings.theme}attr="data-theme-choice" variant="themeswitch" epoch={epoch}onChoose={(choice) => { settings.theme = choice; save(); current.changed('theme') }} /></Row><div data-setting-row="">- <label htmlFor="glassContrastSetting"><b>增加对比度</b>- <small>关闭玻璃折射与透明效果,使用实色背景。</small></label>+ <label htmlFor="glassContrastSetting"><b>增加对比度</b></label><input type="checkbox" id="glassContrastSetting" data-toggle="" role="switch" checked={current.highContrast()}onChange={(event) => current.setHighContrast(event.target.checked)} /></div><ToggleRow id="uiSoundsSetting" title="界面音效" checked={settings.uiSounds}- description="按钮、开关、菜单、弹层和操作回执各配一声轻响。"onToggle={(on) => { settings.uiSounds = on; save(); current.changed('uiSounds') }} /><ToggleRow id="homeGlowSetting" title="侧栏光晕" checked={settings.homeGlow.on}- description="左栏玻璃面上那三枚慢慢漂动的光,其余玻璃面跟着取前两枚的颜色。配色在下面或左栏底部那枚配色钮上挑,强调色在配色钮上挑;这里还调强度、颗粒、漂移速度、柔化、大小和每一枚光晕的颜色。浅色主题按同一组颜色淡一档显示。"onToggle={(on) => { settings.homeGlow.on = on; save(); current.changed('glow') }} /><GlowSettings host={current} /><section data-sidebar-setting="" aria-labelledby="sidebarOrderTitle">- <span><b id="sidebarOrderTitle">左侧导航</b>- <small>直接拖动排序;可隐藏入口,也可从具体页面列表重新添加。窄栏和筛选抽屉会保持一致。</small></span>+ <span><b id="sidebarOrderTitle">导航入口与顺序</b></span><SidebarOrder host={current} /></section></Group><BrowseGroup host={current} tab={shown.tab} epoch={epoch} />- <PlaybackGroup host={current} tab={shown.tab} epoch={epoch} />+ <JavGroup host={current} tab={shown.tab} epoch={epoch} /><Group index={3} tab={shown.tab}><SearchHistoryRow host={current} epoch={epoch} />+ <Row title="相关推荐数量">+ <div id="relatedLimitSetting">+ <NumberSetting key={epoch} id="relatedLimitSetting" label="相关推荐数量" value={settings.relatedLimit}+ onApply={(value) => { settings.relatedLimit = value; save() }} />+ </div>+ </Row>+ <Row title="口味与记录"><a href="/taste" onClick={close}>打开口味与记录</a></Row></Group>- <FollowGroup host={current} tab={shown.tab} epoch={epoch} />- <Group index={5} tab={shown.tab}>+ <Group index={4} tab={shown.tab}><ToggleRow id="censorSetting" title="SFW 模式" describedBy="sfwDescription" checked={current.censored()}- description="模糊、降低饱和度并压暗全站图片和视频,包括封面、头像与详情预览;停止悬停预览。文字、品牌标识和来源图标保持可见。"+ description="隐藏敏感画面,停止悬停预览。"onToggle={(on) => current.setCensored(on)} /></Group>- <Group index={6} tab={shown.tab}>- <MachineSettings host={current} machine={shown.machine} />- </Group></div></div></section>@@ -414,53 +399,60 @@ function BrowseGroup({ host: current, tab, epoch }: GroupProps) {const ascending = settings.defaultSortDirection === 'asc';return (<Group index={1} tab={tab}>- <Row title="每批作品" description="首页每次加载的作品数量。">+ <Row title="每批加载作品"><div id="batchSizeSetting"><NumberSetting key={epoch} id="batchSizeSetting" label="每批作品" value={settings.batchSize}onApply={(value) => { settings.batchSize = value || 60; save(); current.changed('batchSize') }} /></div></Row>- <Row title="默认排序" kind="sort"- description={<small id="sortDirectionHelp">{random ? '随机排序不使用方向。' : '打开首页时使用的排序与方向。'}</small>}>+ <Row title="默认排序" kind="sort"><div data-setting-sort-controls=""><SelectField id="defaultSortSetting" label="默认排序" options={SORT_OPTIONS} value={settings.defaultSort} epoch={epoch}onPick={(value) => { settings.defaultSort = value; save(); current.changed('defaultSort') }} /><SelectField id="defaultSortDirectionSetting" label="默认排序方向" options={DIRECTION_OPTIONS}- value={ascending ? 'asc' : 'desc'} hidden={random} disabled={random} describedBy="sortDirectionHelp" epoch={epoch}+ value={ascending ? 'asc' : 'desc'} hidden={random} disabled={random} epoch={epoch}onPick={(value) => { settings.defaultSortDirection = value; save(); current.changed('sortDirection') }}decorate={(field) => decorateDirection(field, ascending)} /></div></Row>- <label data-setting-row=""><span><b>合并分卷与版本</b><small>同一番号的多个分卷或版次只占一张卡,展示第一个。</small></span>- <input type="checkbox" id="groupCollapseSetting" data-toggle="" role="switch" checked={settings.groupCollapse}- onChange={(event) => { settings.groupCollapse = event.target.checked; save(); current.changed('groupCollapse') }} />- </label>- <Row title="JAV 默认封面" description="首页、接着看和 Mix 等位置共用;缺图时使用另一种封面。">- <IconSwitch id="javImageSetting" name="jav-image" legend="JAV 默认封面" options={JAV_IMAGE_OPTIONS}- value={settings.javImage} attr="data-jav-image-choice" variant="javimageswitch" text epoch={epoch}- onChoose={(choice) => { settings.javImage = normalizeJavImage(choice); save(); current.changed('javImage') }} />- </Row>- <Row title="视频封面默认大小" kind="related" description="首页和 JAV 等视频列表共用;小图展示完整封套,大图展示完整正封。">- <IconSwitch id="javSizeSetting" name="video-size" legend="视频封面默认大小" options={current.videoLayouts}+ <Row title="视频卡片大小">+ <IconSwitch id="javSizeSetting" name="video-size" legend="视频卡片大小" options={current.videoLayouts}value={current.videoLayout()} attr="data-video-layout" variant="javimageswitch" text epoch={epoch}onChoose={(layout) => current.setVideoLayout(layout)} /></Row>+ <PlaybackRows host={current} epoch={epoch} />+ </Group>+ );+}++function JavGroup({ host: current, tab, epoch }: GroupProps) {+ const settings = current.store.value;+ const save = () => current.store.save();+ return (+ <Group index={2} tab={tab}>+ <h4 data-settings-subheading="">作品显示</h4>+ <Row title="默认图片">+ <IconSwitch id="javImageSetting" name="jav-image" legend="默认图片" options={JAV_IMAGE_OPTIONS}+ value={settings.javImage} attr="data-jav-image-choice" variant="javimageswitch" text epoch={epoch}+ onChoose={(choice) => { settings.javImage = normalizeJavImage(choice); save(); current.changed('javImage') }} />+ </Row>+ <label data-setting-row=""><span><b>合并分卷与版本</b></span>+ <input type="checkbox" id="groupCollapseSetting" data-toggle="" role="switch" checked={settings.groupCollapse}+ onChange={(event) => { settings.groupCollapse = event.target.checked; save(); current.changed('groupCollapse') }} />+ </label>+ <h4 data-settings-subheading="">新作显示</h4><ToggleRow id="feedAutoScrollSetting" title="新作自动滚动" checked={settings.feedAutoScroll}- description="首页和人物页那一行未入库的新作缓缓向前滚,到头停一下再往回;指针移上去或手动滚过时停下。"onToggle={(on) => { settings.feedAutoScroll = on; save(); current.changed('feedAutoScroll') }} />- {FEED_COMPILATIONS.map(([id, key, label, title, describedBy, description]) => (- <CompilationToggle key={id} host={current} id={id} settingKey={key} label={label} title={title}- describedBy={describedBy} description={description} />+ {FEED_COMPILATIONS.map(([id, key, label, title]) => (+ <CompilationToggle key={id} host={current} id={id} settingKey={key} label={label} title={title} />))}</Group>);}-/* 合集开关由服务端判,列表、未读数和补封面排队都跟着它,所以先存到服务端再重画;往返期间开关停在新位置、挂忙态,失败退回原位。 */-function CompilationToggle({ host: current, id, settingKey, label, title, describedBy, description }: {+function CompilationToggle({ host: current, id, settingKey, label, title }: {host: SettingsPanelHost; id: string; settingKey: CompilationKey; label: string; title: string;- describedBy: string; description: string;}) {const save = useSaveSettings();const [pending, setPending] = useState<boolean | null>(null);@@ -482,72 +474,37 @@ function CompilationToggle({ host: current, id, settingKey, label, title, descri};return (<label data-setting-row="">- <span><b>{title}</b><small id={describedBy}>{description}</small></span>- <input data-toggle="" type="checkbox" id={id} role="switch" aria-describedby={describedBy} ref={box}+ <span><b>{title}</b></span>+ <input data-toggle="" type="checkbox" id={id} role="switch" ref={box}checked={pending ?? settings[settingKey]} onChange={(event) => toggle(event.target.checked)} /></label>);}-function PlaybackGroup({ host: current, tab, epoch }: GroupProps) {+function PlaybackRows({ host: current, epoch }: Omit<GroupProps, 'tab'>) {const settings = current.store.value;const save = () => current.store.save();return (- <Group index={2} tab={tab}>- <Row title="悬停放大" description="转圈完成后进入放大预览。">+ <>+ <Row title="悬停预览延迟"><div id="hoverDelaySetting">- <NumberSetting key={epoch} id="hoverDelaySetting" label="悬停放大" value={settings.hoverDelaySeconds}+ <NumberSetting key={epoch} id="hoverDelaySetting" label="悬停预览延迟" value={settings.hoverDelaySeconds}onApply={(value) => {settings.hoverDelaySeconds = boundedPreference(value, 0, 60, 5); save(); current.changed('hoverDelay');}} /></div></Row><ToggleRow id="detailAutoplaySetting" title="打开详情自动播放" checked={settings.detailAutoplay}- description="打开本地作品或关注视频详情时开始播放;关闭后点击播放按钮开始。"onToggle={(on) => { settings.detailAutoplay = on; save() }} />- <ToggleRow id="miniplayerSetting" title="小窗播放" checked={settings.miniplayer}- description="离开详情时正在播放的视频缩到角落继续播放;小窗开着时点击其他视频直接在小窗里换片。"+ <ToggleRow id="miniplayerSetting" title="离开详情后小窗播放" checked={settings.miniplayer}onToggle={(on) => { settings.miniplayer = on; save(); current.changed('miniplayer') }} />- <Row title="快进 / 快退" description="卡片预览和详情播放器共用。">+ <Row title="快进 / 快退步长"><div id="seekSecondsSetting"><NumberSetting key={epoch} id="seekSecondsSetting" label="快进 / 快退" value={settings.seekSeconds}onApply={(value) => { settings.seekSeconds = value || 10; save(); current.changed('seekSeconds') }} /></div></Row>- <VideoThumbnailRow epoch={epoch} />- <Row title="相关推荐" description="详情下方一次显示的相似作品数量。">- <div id="relatedLimitSetting">- <NumberSetting key={epoch} id="relatedLimitSetting" label="相关推荐" value={settings.relatedLimit}- onApply={(value) => { settings.relatedLimit = value; save() }} />- </div>- </Row>- </Group>- );-}--/* 视频缩略图采集的档位跟着这台机器走(`/api/thumbnail-jobs`),不存在本地:跑的是这台机器上的- 一条长任务,从另一台设备打开设置要看到的是它正在按什么密度采。采集进度在活动页,这里不轮询。 */-function VideoThumbnailRow({ epoch }: { epoch: number }) {- const status = useQuery({ queryKey: THUMBNAIL_JOBS_KEY, queryFn: ({ signal }) => fetchThumbnailJobs(signal) });- const save = useSaveThumbnailMode();- const reset = save.reset;- useEffect(() => { reset() }, [epoch, reset]);- const mode = status.data?.mode || 'off';- const html = save.isPending ? savingHtml()- : status.isFetching ? loadingDotsHtml('正在读取状态')- : save.isError ? escapeHtml(errorText(save.error, '保存失败'))- : status.isError ? escapeHtml(`状态未取得:${errorText(status.error, String(status.error))}`)- : status.data ? escapeHtml(videoThumbnailCopy(status.data)) : '读取运行状态…';- return (- <Row title="视频缩略图采集" description={<>- <small>拖动进度条时按时间点看画面。精准每 10 秒一张,粗略每 30 秒一张;两小时的片子约 720 / 240 张,占 20–100 / 7–35 MB。只采集本机磁盘上的片子,网盘上的每张都要回源拉一次。</small>- <Html id="videoThumbnailState" aria-live="polite" html={html} />- </>}>- <SelectField id="videoThumbnailSetting" label="视频缩略图采集" options={THUMBNAIL_OPTIONS}- value={save.isPending || save.isError ? (save.variables ?? mode) : mode}- disabled={save.isPending || status.isFetching} epoch={epoch}- onPick={(value) => save.mutate(value)} />- </Row>+ </>);}@@ -556,7 +513,7 @@ function SearchHistoryRow({ host: current, epoch }: { host: SettingsPanelHost; econst save = useSaveSettings();/* 条数跟着账本走(`/api/settings`),所有访问端看到同一个数;本地那份只是镜像。 */return (- <Row title="搜索记录" description="保存在 Peach 账本,所有访问端同步。">+ <Row title="搜索记录数量"><div id="searchHistoryLimitSetting"><NumberSetting key={epoch} id="searchHistoryLimitSetting" label="搜索记录" value={settings.searchHistoryLimit}onApply={(value) => {@@ -569,103 +526,3 @@ function SearchHistoryRow({ host: current, epoch }: { host: SettingsPanelHost; e</Row>);}--function FollowGroup({ host: current, tab, epoch }: GroupProps) {- const settings = current.store.value;- const save = useSaveSettings();- const initial = useSaveSettings();- const [initialState, setInitialState] = useState('');- useEffect(() => { setInitialState('') }, [epoch]);- /* 服务端按这个数决定要不要重取,所以它跟着账本走;保存期间下拉挂忙态,失败退回原值。 */- const saveInitialDays = (value: number) => {- if (initial.isPending) return;- setInitialState('正在保存…');- initial.mutate({ followInitialDays: value }, {- onSuccess: (saved) => {- if (typeof saved.followInitialDays === 'number') settings.followInitialDays = saved.followInitialDays;- current.store.save();- setInitialState('已保存,适用于尚未开始采集的来源。');- current.receipt('已保存首次采集历史范围');- },- onError: (error) => {- setInitialState(errorText(error, ''));- current.failure('保存首次采集历史范围', error);- },- });- };- return (- <Group index={4} tab={tab}>- <Row title="首次采集历史范围" description={<>- <small>按发布时间限制新来源首次导入的内容;范围内不足 30 条时补到 30 条。没有日期的条目仍会导入;已有内容不受影响,支持历史分页的来源可手动加载更早。</small>- <small id="followInitialDaysState" aria-live="polite">{initialState}</small>- </>}>- <SelectField id="followInitialDaysSetting" label="首次采集历史范围" options={current.followInitialRanges}- value={initial.isPending ? String(initial.variables?.followInitialDays ?? settings.followInitialDays)- : String(settings.followInitialDays)}- busy={initial.isPending} epoch={epoch} onPick={(value) => saveInitialDays(Number(value))} />- </Row>- <FollowScheduleRow epoch={epoch} />- <Row title="头像与站点图标刷新" description="创作者头像、来源图标和外链圆标保存在本机,到期后下次显示时重新取一次;视频与图片不保存。">- <SelectField id="metadataRefreshSetting" label="头像与站点图标刷新" options={METADATA_OPTIONS}- value={String(settings.metadataRefreshDays)} epoch={epoch}- onPick={(value) => {- const days = Number(value);- settings.metadataRefreshDays = METADATA_REFRESH_DAYS.includes(days) ? days : 30;- current.store.save();- save.mutate({ metadataRefreshDays: settings.metadataRefreshDays }, { onError: () => {} });- }} />- </Row>- </Group>- );-}--/* 关注自动更新的档位与上次运行状态跟着这台机器走(`/api/follow/schedule`);读取与保存期间整块禁用。 */-function FollowScheduleRow({ epoch }: { epoch: number }) {- const status = useQuery({ queryKey: FOLLOW_SCHEDULE_KEY, queryFn: ({ signal }) => fetchFollowSchedule(signal) });- const save = useSaveFollowSchedule();- const reset = save.reset;- useEffect(() => { reset() }, [epoch, reset]);- const data = status.data;- /* 读取失败时整块停在禁用;保存失败时回到上一次读到的那一档,还能再改。 */- const busy = save.isPending || status.isFetching || (status.isError && !save.isError);- const html = save.isPending ? savingHtml()- : status.isFetching ? loadingDotsHtml('正在读取状态')- : save.isError ? escapeHtml(errorText(save.error, '保存失败'))- : status.isError ? escapeHtml(`状态未取得:${errorText(status.error, String(status.error))}`)- : data ? escapeHtml(followScheduleCopy(data)) : '读取运行状态…';- return (- <Row title="关注自动更新" description={<Html id="followScheduleState" aria-live="polite" html={html} />}>- <div id="followScheduleSetting">- <NumberSetting key={epoch} id="followScheduleSetting" label="关注自动更新"- value={data && !busy ? (data.enabled ? data.interval_minutes : 0) : null}- disabled={data ? !data.available : false}- onApply={(minutes) => save.mutate(minutes)} />- </div>- </Row>- );-}--function MachineSettings({ host: current, machine }: { host: SettingsPanelHost; machine: Machine }) {- if (machine === 'summary') {- return (- <div id="machineSettings" key="summary">- <div className="peach-react">- <ConfigurationSummary openConfiguration={() => { close(); current.openConfiguration() }} />- </div>- </div>- );- }- if (machine === 'note') {- return (- <div id="machineSettings" key="note" dangerouslySetInnerHTML={{- __html: noteHtml('媒体文件夹、端口、代理与更新只能在运行 Peach 服务的那台设备上改:在它的浏览器里打开配置页。',- { label: '在服务端设备修改' }),- }} />- );- }- return <div id="machineSettings" key="none" />;-}--function escapeHtml(text: string): string {- return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);-}diff --git a/frontend/src/react/settings/configuration-summary.tsx b/frontend/src/react/settings/configuration-summary.tsxdeleted file mode 100644index 0eed9cd45..000000000--- a/frontend/src/react/settings/configuration-summary.tsx+++ /dev/null@@ -1,50 +0,0 @@-/* 设置弹层「这台电脑」那一格的摘要卡:媒体库数、端口、更新状态,加一颗「打开配置页」。- *- * 设置弹层只放一行一个值、改完就生效的控件;要「保存配置」的多字段表单都在- * `/configuration`(ADR-0050),这里只读同一份配置快照(`CONFIGURATION_KEY`)。- * 灰卡由设置面板那一格 `[data-setting-group]` 画(`../settings-panel/`),这里只画卡里的读数与页脚。 */-import { useQuery } from '@tanstack/react-query';--import { Button } from '@/components/base/buttons/button';--import { errorMessage } from '../../api';-import type { ConfigurationData } from '../bundle';-import { Note } from '../components/note';-import { CONFIGURATION_KEY, fetchConfiguration } from './configuration';-import { Fact, FactList, Footer, Stack } from './section';--export interface ConfigurationSummaryProps {- /** 关掉设置面板、换到 `/configuration`。整页换成哪一屏归壳。 */- openConfiguration(): void;-}--const updateLine = (data: ConfigurationData) => {- const updates = data.updates;- if (!updates) return '未取得';- return updates.message ? `${updates.current_version} · ${updates.message}` : updates.current_version;-};--export function ConfigurationSummary({ openConfiguration }: ConfigurationSummaryProps) {- const config = useQuery({- queryKey: CONFIGURATION_KEY, queryFn: ({ signal }) => fetchConfiguration(signal),- });- const data = config.data;- return (- <div className="flex flex-col">- {data- ? <FactList>- <Fact term="媒体库">{`${data.library_count} 个`}</Fact>- <Fact term="端口">{String(data.port)}</Fact>- <Fact term="更新">{updateLine(data)}</Fact>- </FactList>- : <Stack>- <Note tone="error" title="配置读取失败">- {config.error ? errorMessage(config.error) : '未取得配置,请刷新页面重试。'}- </Note>- </Stack>}- <Footer status="媒体文件夹、端口、代理与更新在配置页上改。">- <Button onClick={openConfiguration}>打开配置页</Button>- </Footer>- </div>- );-}diff --git a/frontend/src/react/settings/service-preferences.tsx b/frontend/src/react/settings/service-preferences.tsxnew file mode 100644index 000000000..88da372c2--- /dev/null+++ b/frontend/src/react/settings/service-preferences.tsx@@ -0,0 +1,151 @@+/* 服务配置中的采集档位与来源更新偏好,读写复用设置接口和查询缓存。 */+import { useEffect, useRef, useState, useSyncExternalStore } from 'react';+import { useQuery } from '@tanstack/react-query';++import { appSettingsStore, METADATA_REFRESH_DAYS } from '@peach/appearance';+import { SettingsRow } from '@/components/application/settings/settings-rows';+import { Select, SelectItem } from '@/components/base/select/select';+import { Switch } from '@/components/base/switch/switch';+import { Input } from '@/components/base/input/input';++import { FOLLOW_INITIAL_RANGE_OPTIONS } from '../../application/initial-follow-ranges';+import { errorMessage } from '../../api';+import { boundedPreference } from '../../number-setting';+import {+ FOLLOW_SCHEDULE_KEY, SETTINGS_KEY, THUMBNAIL_JOBS_KEY, fetchFollowSchedule, fetchSettings, fetchThumbnailJobs,+ useSaveFollowSchedule, useSaveSettings, useSaveThumbnailMode,+} from '../settings-panel/settings-data';+import { ErrorText, Help, Rows, Section, Stack } from './section';++const THUMBNAIL_OPTIONS = [['off', '关闭'], ['precise', '每 10 秒一张'], ['coarse', '每 30 秒一张']] as const;+const METADATA_OPTIONS = [['7', '每周'], ['30', '每月'], ['90', '每季'], ['0', '从不']] as const;++export function VideoThumbnailRow({ epoch = 0 }: { epoch?: number }) {+ const status = useQuery({ queryKey: THUMBNAIL_JOBS_KEY, queryFn: ({ signal }) => fetchThumbnailJobs(signal), refetchOnMount: 'always' });+ const save = useSaveThumbnailMode();+ const reset = save.reset;+ useEffect(() => { reset() }, [epoch, reset]);+ const data = status.data;+ const error = save.error || status.error;+ return (+ <Section title="时间轴缩略图">+ <Rows>+ <SettingsRow label="采集间隔" description="仅采集本机磁盘上的视频。">+ <div id="videoThumbnailSetting">+ <Select aria-label="缩略图采集间隔" selectedKey={data?.mode || 'off'}+ isDisabled={!data || status.isFetching || save.isPending}+ onSelectionChange={(key) => { if (key !== null) save.mutate(String(key)) }}>+ {THUMBNAIL_OPTIONS.map(([key, label]) => <SelectItem key={key} id={key}>{label}</SelectItem>)}+ </Select>+ </div>+ </SettingsRow>+ </Rows>+ {save.isPending || data?.status === 'running'+ ? <Stack divided><Help role="status">{save.isPending ? '正在保存…' : '正在采集,进度在活动页查看。'}</Help></Stack>+ : null}+ {error ? <Stack divided><ErrorText>{errorMessage(error)}</ErrorText></Stack> : null}+ </Section>+ );+}++export function FollowPreferenceRows({ receipt }: { receipt(message: string): void }) {+ const store = appSettingsStore();+ useSyncExternalStore(store.subscribe, store.version);+ const settings = useQuery({ queryKey: SETTINGS_KEY, queryFn: ({ signal }) => fetchSettings(signal), refetchOnMount: 'always' });+ const initial = useSaveSettings();+ const metadata = useSaveSettings();+ const initialDays = settings.data?.followInitialDays ?? store.value.followInitialDays;+ const refreshDays = settings.data?.metadataRefreshDays ?? store.value.metadataRefreshDays;+ const error = initial.error || metadata.error || settings.error;+ return (+ <Section title="关注采集">+ <Rows>+ <FollowScheduleRow />+ <SettingsRow label="首次采集范围">+ <div id="followInitialDaysSetting">+ <Select aria-label="首次采集范围" selectedKey={String(initialDays)}+ isDisabled={settings.isFetching || initial.isPending}+ onSelectionChange={(key) => {+ if (key === null) return;+ initial.mutate({ followInitialDays: Number(key) }, { onSuccess: (saved) => {+ if (typeof saved.followInitialDays === 'number') store.value.followInitialDays = saved.followInitialDays;+ store.save();+ receipt('已保存首次采集范围');+ } });+ }}>+ {FOLLOW_INITIAL_RANGE_OPTIONS.map(([key, label]) => <SelectItem key={key} id={key}>{label}</SelectItem>)}+ </Select>+ </div>+ </SettingsRow>+ <SettingsRow label="头像与图标刷新">+ <div id="metadataRefreshSetting">+ <Select aria-label="头像与图标刷新" selectedKey={String(refreshDays)}+ isDisabled={settings.isFetching || metadata.isPending}+ onSelectionChange={(key) => {+ if (key === null || !METADATA_REFRESH_DAYS.includes(Number(key))) return;+ metadata.mutate({ metadataRefreshDays: Number(key) }, { onSuccess: (saved) => {+ if (typeof saved.metadataRefreshDays === 'number') store.value.metadataRefreshDays = saved.metadataRefreshDays;+ store.save();+ receipt('已保存头像与图标刷新频率');+ } });+ }}>+ {METADATA_OPTIONS.map(([key, label]) => <SelectItem key={key} id={key}>{label}</SelectItem>)}+ </Select>+ </div>+ </SettingsRow>+ </Rows>+ {error ? <Stack divided><ErrorText>{errorMessage(error)}</ErrorText></Stack> : null}+ </Section>+ );+}++function FollowScheduleRow() {+ const status = useQuery({ queryKey: FOLLOW_SCHEDULE_KEY, queryFn: ({ signal }) => fetchFollowSchedule(signal), refetchOnMount: 'always' });+ const save = useSaveFollowSchedule();+ const data = status.data;+ const remembered = useRef(boundedPreference(Number(localStorage.getItem('peach.number.followScheduleSetting')), 15, 10080, 60));+ const [draft, setDraft] = useState('60');+ const [invalid, setInvalid] = useState(false);+ useEffect(() => {+ if (data?.enabled) {+ remembered.current = data.interval_minutes;+ setDraft(String(data.interval_minutes));+ }+ }, [data]);+ const blocked = !data?.available || status.isFetching || save.isPending;+ const commit = () => {+ const minutes = Number(draft);+ if (!Number.isInteger(minutes) || minutes < 15 || minutes > 10080) { setInvalid(true); return }+ setInvalid(false);+ if (!data?.enabled || blocked || minutes === data.interval_minutes) return;+ remembered.current = minutes;+ localStorage.setItem('peach.number.followScheduleSetting', String(minutes));+ save.mutate(minutes);+ };+ const error = save.error || status.error;+ return (+ <>+ <SettingsRow label="自动检查更新">+ <div id="followScheduleSetting" className="flex 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));+ save.mutate(on ? remembered.current : 0);+ }} />+ {data?.enabled ? <div className="flex items-center gap-2">+ <Input type="number" inputMode="numeric" name="follow-interval" autoComplete="off"+ aria-label="自动检查间隔" size="small" className="w-24"+ value={draft} onChange={(value) => { setDraft(value); setInvalid(false) }} onBlur={commit}+ onKeyDown={(event) => { if (event.key === 'Enter') { event.preventDefault(); commit() } }}+ isDisabled={blocked} isInvalid={invalid} />+ <span className="text-body-2-regular text-text-secondary">分钟</span>+ </div> : null}+ </div>+ </SettingsRow>+ {invalid ? <Stack><ErrorText>请输入 15–10080 的整数(分钟)。</ErrorText></Stack> : null}+ {save.isPending || data?.running+ ? <Stack><Help role="status">{save.isPending ? '正在保存…' : '正在检查来源更新…'}</Help></Stack> : null}+ {error ? <Stack><ErrorText>{errorMessage(error)}</ErrorText></Stack> : null}+ </>+ );+}diff --git a/frontend/test/react/configuration-summary.test.tsx b/frontend/test/react/configuration-summary.test.tsxdeleted file mode 100644index f3349386d..000000000--- a/frontend/test/react/configuration-summary.test.tsx+++ /dev/null@@ -1,70 +0,0 @@-/* 设置弹层「这台电脑」那一格的摘要卡:只读三项读数,编辑都去配置页。 */-import { notifyManager, QueryClientProvider } from '@tanstack/react-query';-import { afterEach, expect, it, vi } from 'vitest';--import { CONFIGURATION_URL } from '../../src/configuration-endpoints';-import type { ConfigurationData, ReleaseState } from '../../src/react/bundle';-import { queryClient } from '../../src/react/query';-import { prefetchConfiguration } from '../../src/react/settings/configuration';-import { ConfigurationSummary } from '../../src/react/settings/configuration-summary';-import { buttonNamed, click, mount } from './render';--afterEach(() => { queryClient.clear() });-notifyManager.setScheduler((notify) => notify());--const release: ReleaseState = {- current_version: '0.9.0', latest_version: null, channel: '测试版', installation: '独立测试包',- state: 'unchecked', message: '尚未检查', release_url: 'https://github.com/longmeidao/peach/releases',-};--const data = (over: Partial<ConfigurationData> = {}): ConfigurationData => ({- editable: true, notice: '', revision: 'r', media_dirs: [], library_count: 0, port: 9123, facts: [], ...over,-});--async function open(config: ConfigurationData, openConfiguration = vi.fn()) {- const fetcher = vi.fn(async (path: string) => ({ ok: true, status: 200, json: async () => (path === CONFIGURATION_URL ? config : {}) }));- vi.stubGlobal('fetch', fetcher);- await prefetchConfiguration(new AbortController().signal);- const host = await mount(- <QueryClientProvider client={queryClient}><ConfigurationSummary openConfiguration={openConfiguration} /></QueryClientProvider>,- );- return { host, fetcher };-}--const facts = (host: ParentNode) =>- [...host.querySelectorAll('dt')].map((dt) => [dt.textContent, dt.nextElementSibling?.textContent]);--it('三行读数:媒体库数照服务端给的写,端口,当前版本连同检查结果', async () => {- /* 三个文件夹、三个不同的库名,服务端说两个库:摘要卡不按文件夹自己再数一遍。 */- const { host } = await open(data({- updates: release,- library_count: 2,- media_sources: [- { location: 'local', root: 'R:\\Media', path: 'R:\\Media', library: '电影' },- { location: '115', root: 'B:\\Media', path: 'B:\\Media', library: '网盘' },- { location: 'local', root: 'D:\\Local', path: 'D:\\Local', library: 'Local' },- ],- }));- expect(facts(host)).toEqual([['媒体库', '2 个'], ['端口', '9123'], ['更新', '0.9.0 · 尚未检查']]);-});--it('摘要卡里没有可编辑的控件,只有一颗去配置页的按钮', async () => {- const openConfiguration = vi.fn();- const { host, fetcher } = await open(data(), openConfiguration);- expect(host.querySelectorAll('input, textarea, select, [role="switch"], [aria-haspopup="listbox"]')).toHaveLength(0);- expect([...host.querySelectorAll('button')].map((button) => button.textContent)).toEqual(['打开配置页']);- expect(facts(host).at(-1)).toEqual(['更新', '未取得']);- await click(buttonNamed('打开配置页', host));- expect(openConfiguration).toHaveBeenCalledTimes(1);- expect(fetcher).toHaveBeenCalledTimes(1);-});--it('读不到配置时说打不开,按钮照样能去配置页', async () => {- vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 503, json: async () => ({ message: '账本正在迁移' }) })));- await prefetchConfiguration(new AbortController().signal).catch(() => undefined);- const host = await mount(- <QueryClientProvider client={queryClient}><ConfigurationSummary openConfiguration={vi.fn()} /></QueryClientProvider>,- );- expect(host.textContent).toContain('配置读取失败');- expect(buttonNamed('打开配置页', host)).not.toBeNull();-});diff --git a/frontend/test/react/service-preferences.test.tsx b/frontend/test/react/service-preferences.test.tsxnew file mode 100644index 000000000..c7b6dde34--- /dev/null+++ b/frontend/test/react/service-preferences.test.tsx@@ -0,0 +1,101 @@+import { act } from 'react';+import { notifyManager, QueryClientProvider } from '@tanstack/react-query';+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 { choose, click, mount, mountRoot, settle, type } from './render';++notifyManager.setScheduler((notify) => notify());++afterEach(() => { queryClient.clear(); localStorage.removeItem('peach.number.followScheduleSetting') });++function server() {+ const settings = { followInitialDays: 30, metadataRefreshDays: 30 };+ const schedule = { available: true, enabled: true, interval_minutes: 180 };+ const thumbnails = { mode: 'precise', status: 'idle' };+ const posts: { url: string; body: Record<string, unknown> }[] = [];+ vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {+ const data = url === '/api/settings' ? settings : url === '/api/follow/schedule' ? schedule : thumbnails;+ if (init?.method === 'POST') {+ const body = JSON.parse(String(init.body));+ posts.push({ url, body });+ Object.assign(data, body);+ }+ return { ok: true, status: 200, json: async () => ({ ...data }) };+ }));+ return { posts, settings, schedule, thumbnails };+}++it('首次采集范围与头像刷新写入服务端,回执和本地镜像跟随成功值', async () => {+ const { posts } = server();+ const receipt = vi.fn();+ const host = await mount(<QueryClientProvider client={queryClient}><FollowPreferenceRows receipt={receipt} /></QueryClientProvider>);+ await settle();+ await choose(host.querySelector('#followInitialDaysSetting [aria-haspopup="listbox"]'), '最近 7 天');+ await settle();+ await choose(host.querySelector('#metadataRefreshSetting [aria-haspopup="listbox"]'), '每周');+ await settle();+ expect(posts).toEqual([+ { url: '/api/settings', body: { followInitialDays: 7 } },+ { url: '/api/settings', body: { metadataRefreshDays: 7 } },+ ]);+ expect(appSettingsStore().value.followInitialDays).toBe(7);+ expect(appSettingsStore().value.metadataRefreshDays).toBe(7);+ expect(receipt.mock.calls).toEqual([['已保存首次采集范围'], ['已保存头像与图标刷新频率']]);+});++it('缩略图选择提交原档位,保存后的控件显示采集间隔', async () => {+ const { posts } = server();+ const host = await mount(<QueryClientProvider client={queryClient}><VideoThumbnailRow /></QueryClientProvider>);+ await settle();+ await choose(host.querySelector('[aria-haspopup="listbox"]'), '每 30 秒一张');+ await settle();+ expect(posts).toEqual([{ url: '/api/thumbnail-jobs', body: { mode: 'coarse' } }]);+ expect(host.querySelector('[aria-haspopup="listbox"]')?.textContent).toContain('每 30 秒一张');+});++it('自动检查间隔拒绝范围外值,只在有效提交时写入原接口', async () => {+ const { posts } = server();+ const host = await mount(<QueryClientProvider client={queryClient}><FollowPreferenceRows receipt={vi.fn()} /></QueryClientProvider>);+ await settle();+ const input = host.querySelector<HTMLInputElement>('input[aria-label="自动检查间隔"]')!;+ await type(input, '2');+ await act(async () => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));+ expect(posts).toEqual([]);+ expect(host.querySelector('[role="alert"]')?.textContent).toContain('15–10080');+ await type(input, '240');+ await act(async () => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));+ await settle();+ expect(posts).toEqual([{ url: '/api/follow/schedule', body: { enabled: true, interval_minutes: 240 } }]);+});++it('服务设置重新进入时读取最新状态,关闭自动检查后保留间隔', async () => {+ const { posts, settings, thumbnails } = server();+ const view = () => <QueryClientProvider client={queryClient}>+ <FollowPreferenceRows receipt={vi.fn()} /><VideoThumbnailRow />+ </QueryClientProvider>;+ const first = await mountRoot(view());+ await settle();+ await click(first.host.querySelector('input[role="switch"]'));+ await settle();+ expect(localStorage.getItem('peach.number.followScheduleSetting')).toBe('180');+ await first.unmount();+ settings.followInitialDays = 7;+ settings.metadataRefreshDays = 90;+ thumbnails.mode = 'coarse';+ const second = await mount(view());+ await settle();+ expect(second.querySelector('#followInitialDaysSetting [aria-haspopup="listbox"]')?.textContent).toContain('最近 7 天');+ expect(second.querySelector('#metadataRefreshSetting [aria-haspopup="listbox"]')?.textContent).toContain('每季');+ expect(second.querySelector('#videoThumbnailSetting [aria-haspopup="listbox"]')?.textContent).toContain('每 30 秒一张');+ expect(second.querySelector<HTMLInputElement>('input[role="switch"]')?.checked).toBe(false);+ await click(second.querySelector('input[role="switch"]'));+ await settle();+ expect(posts).toEqual([+ { url: '/api/follow/schedule', body: { enabled: false, interval_minutes: 60 } },+ { url: '/api/follow/schedule', body: { enabled: true, interval_minutes: 180 } },+ ]);+ expect(second.querySelector<HTMLInputElement>('input[aria-label="自动检查间隔"]')?.value).toBe('180');+});diff --git a/frontend/test/react/settings-panel.test.tsx b/frontend/test/react/settings-panel.test.tsxindex 9b6615ee0..70d691049 100644--- a/frontend/test/react/settings-panel.test.tsx+++ b/frontend/test/react/settings-panel.test.tsx@@ -171,36 +171,30 @@ function watchReports() {}describe('设置面板与壳的接缝', () => {- it('首次采集范围选择写入设置接口,成功后保存服务端值并给出回执', async () => {- const fetcher = vi.fn(async (_url: unknown, init?: RequestInit) => ({- ok: true, status: 200,- json: async () => init?.method === 'POST' ? { followInitialDays: 7 } : {},- }));- vi.stubGlobal('fetch', fetcher);+ it('五个分区按使用场景组织,服务配置入口遵守设备权限', async () => {const current = await setup();- const receipt = vi.fn();- current.host.receipt = receipt;- const panel = await open(current, '关注');- const field = panel.querySelector<HTMLElement>('#followInitialDaysSetting .ui-gselect')!;- expect([...field.querySelectorAll('[role="option"]')].map((option) => option.textContent))- .toEqual(['不限时间', '最近 7 天', '最近 30 天', '最近 90 天']);- current.save.mockClear();- // happy-dom 不实现浏览器顶层弹出 API;选项与 change 使用正式控件。- const menu = field.querySelector<HTMLElement>('[data-select-menu]')!;- menu.showPopover = vi.fn();- menu.hidePopover = vi.fn();- await click(field.querySelector('[data-select-trigger]'));- await click(field.querySelector('[data-select-option="7"]'));- await settle();- const posts = fetcher.mock.calls.filter(([url, init]) => url === '/api/settings' && init?.method === 'POST');- expect(posts).toHaveLength(1);- expect(JSON.parse(String(posts[0]![1]!.body))).toEqual({ followInitialDays: 7 });- expect(current.value.followInitialDays).toBe(7);- expect(current.save).toHaveBeenCalledTimes(1);- expect(receipt).toHaveBeenCalledWith('已保存首次采集历史范围');- expect(field.querySelector('[data-select-label]')?.textContent).toBe('最近 7 天');- expect(panel.textContent).toContain('已保存,适用于尚未开始采集的来源。');+ const openConfiguration = vi.fn();+ current.host.openConfiguration = openConfiguration;+ const panel = await open(current, 'JAV 与新作');+ expect([...panel.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent))+ .toEqual(['外观与导航', '浏览与播放', 'JAV 与新作', '搜索与推荐', '内容显示']);+ expect(panel.querySelector('#javImageSetting')?.closest('section')?.hidden).toBe(false);+ expect(panel.querySelector('#detailAutoplaySetting')?.closest('section')?.hidden).toBe(true);+ expect(panel.querySelector('#videoThumbnailSetting')).toBeNull();+ expect(panel.querySelector('#followScheduleSetting')).toBeNull();+ const entry = panel.querySelector<HTMLButtonElement>('[data-settings-service] button')!;+ expect(entry.disabled).toBe(true);+ await click(entry);+ expect(openConfiguration).not.toHaveBeenCalled();await close(current);+ current.host.configurable = async () => true;+ await open(current);+ await settle();+ expect(entry.disabled).toBe(false);+ await click(entry);+ await settle();+ expect(openConfiguration).toHaveBeenCalledTimes(1);+ expect(panel.hidden).toBe(true);});it('每一个开关只落一次盘、只报自己那一个效果名', async () => {@@ -270,7 +264,7 @@ describe('设置面板与壳的接缝', () => {const dial = panel.querySelector('[data-glow-dial="speed"]');await close(current);expect(panel.hidden).toBe(true);- const again = await open(current, '浏览');+ const again = await open(current, '浏览与播放');expect(document.querySelectorAll('[data-settings-host]')).toHaveLength(1);expect(again).toBe(panel);expect(again.querySelector('#homeGlowControls')).toBe(glow);@@ -311,10 +305,10 @@ describe('常驻面', () => {trigger.focus();/* 不包 act:act 会把 flushSync 推到它结束时,看不出句柄自己同步没有。 */(globalThis as ActFlag).IS_REACT_ACT_ENVIRONMENT = false;- current.api.open('浏览');+ current.api.open('浏览与播放');const panel = document.querySelector<HTMLElement>('#settingsPanel')!;expect([panel.hidden, panel.querySelector('#settingsTitle')?.textContent, current.api.isOpen()])- .toEqual([false, '浏览', true]);+ .toEqual([false, '浏览与播放', true]);expect([document.documentElement.style.overflow, document.body.classList.contains('settings-open')]).toEqual(['hidden', true]);expect(document.activeElement).toBe(trigger);@@ -355,7 +349,7 @@ describe('常驻面', () => {await act(async () => { expect(() => current.api.close()).not.toThrow() });await settle();glyph.broken = false;- await act(async () => { expect(() => current.api.open('浏览')).not.toThrow() });+ await act(async () => { expect(() => current.api.open('浏览与播放')).not.toThrow() });await settle();expect(reported, '确定性抛错只报那一次').toHaveBeenCalledTimes(1);expect(host.childNodes.length, '空到刷新为止,不自愈').toBe(0);diff --git a/tests/test_source_assertion_ratchet.py b/tests/test_source_assertion_ratchet.pyindex 50c827c05..b45c6775b 100644--- a/tests/test_source_assertion_ratchet.py+++ b/tests/test_source_assertion_ratchet.py@@ -52,7 +52,7 @@ BASELINE: dict[str, int] = {"test_subprocess_encoding.py": 2,"test_tray.py": 3,"test_web_js.py": 1,- "test_web_settings.py": 2,+ "test_web_settings.py": 1,"test_web_ui.py": 14,"test_windows_update.py": 3,}diff --git a/tests/test_web_settings.py b/tests/test_web_settings.pyindex 8fa8d8911..c7d14fe63 100644--- a/tests/test_web_settings.py+++ b/tests/test_web_settings.py@@ -261,15 +261,8 @@ class ContractRegistrationTests(unittest.TestCase):root = Path(__file__).resolve().parents[1]settings = (root / "frontend/src/appearance/settings.ts").read_text(encoding="utf-8")- panel = (root / "frontend/src/react/settings-panel/settings-panel.tsx").read_text(encoding="utf-8")raw = re.search(r"const METADATA_REFRESH_DAYS: readonly number\[\] = \[(.*?)\];", settings).group(1)self.assertEqual(tuple(int(item) for item in raw.split(",")), web_settings.METADATA_REFRESH_DAYS)- # 设置面板那一格(`settings-panel` 岛)列的档位与服务端同一组。- options = re.search(r"const METADATA_OPTIONS: readonly Choice\[\] = \[(.*?)\];", panel).group(1)- self.assertEqual(sorted(int(value) for value in re.findall(r"\['(\d+)',", options)),- sorted(web_settings.METADATA_REFRESH_DAYS))- # 选中的值要写进账本(服务端按它决定要不要出网),启动时再用账本那份纠正本地镜像。- self.assertIn("save.mutate({ metadataRefreshDays: settings.metadataRefreshDays }", panel)self.assertIn("const days = remote && remote.metadataRefreshDays;", settings)def test_initial_history_choices_are_in_settings_and_match_the_server(self):