Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor: 为应用导航与初次采集选项建立类型化契约

longmeidaob55f6bc55d61
diff --git a/frontend/src/application/initial-follow-ranges.ts b/frontend/src/application/initial-follow-ranges.ts
new file mode 100644
index 000000000..19799e24f
--- /dev/null
+++ b/frontend/src/application/initial-follow-ranges.ts
@@ -0,0 +1,9 @@
+/** 首次采集的历史范围;值为提交给设置接口的天数,0 表示不限时间。 */
+export const FOLLOW_INITIAL_RANGE_OPTIONS = [
+ ['0', '不限时间'],
+ ['7', '最近 7 天'],
+ ['30', '最近 30 天'],
+ ['90', '最近 90 天'],
+] as const satisfies readonly (readonly [value: string, label: string])[];
+
+export type InitialFollowRange = typeof FOLLOW_INITIAL_RANGE_OPTIONS[number][0];
diff --git a/frontend/src/application/navigation-items.ts b/frontend/src/application/navigation-items.ts
new file mode 100644
index 000000000..472c546b0
--- /dev/null
+++ b/frontend/src/application/navigation-items.ts
@@ -0,0 +1,45 @@
+/** 应用导航的完整词表;默认可见顺序由 sidebar 的持久偏好决定。 */
+export type SidebarKey = '' | 'performers' | 'studios' | 'tags' | 'jav' | 'flagged' | 'playlists'
+ | 'follow' | 'immerse' | 'manage' | 'stats' | 'taste' | 'review' | 'data-cleanup' | 'trash'
+ | 'follow-manage' | 'quality' | 'activity';
+export type ManagementKey = 'stats' | 'taste' | 'review' | 'cleanup' | 'trash' | 'follow'
+ | 'quality' | 'activity' | 'configuration';
+export type NavigationItem<Key extends string = string> = readonly [key: Key, label: string, glyph: string];
+
+export const SIDEBAR_ITEMS = [
+ ['', '首页', 'home'],
+ ['performers', '艺人', 'user-round'],
+ ['studios', '厂牌', 'clapperboard'],
+ ['tags', '标签', 'tags'],
+ ['jav', 'JAV', 'jav'],
+ ['flagged', '已标记', 'bookmark'],
+ ['playlists', '播放列表', 'playlist'],
+ ['follow', '关注', 'rss'],
+ ['immerse', '沉浸模式', 'gallery-vertical-end'],
+ ['manage', '管理', 'wrench'],
+] as const satisfies readonly NavigationItem<SidebarKey>[];
+
+export const MANAGE_SECTIONS = [
+ ['stats', '统计', 'chart'],
+ ['taste', '口味', 'heart'],
+ ['review', '人工复核', 'square-check-big'],
+ ['cleanup', '数据管理', 'hard-drive'],
+ ['trash', '回收站', 'trash'],
+ ['follow', '关注管理', 'rss'],
+ ['quality', '高清版', 'sparkles'],
+ ['activity', '活动', 'history'],
+ ['configuration', '配置', 'folder-cog'],
+] as const satisfies readonly NavigationItem<ManagementKey>[];
+
+export const MANAGE_MENU_SECTIONS: readonly ManagementKey[] = ['stats', 'taste', 'cleanup', 'follow', 'activity', 'configuration'];
+export const getManageMenuSections = (configurable: boolean): readonly NavigationItem<ManagementKey>[] =>
+ MANAGE_SECTIONS.filter(([key]) => MANAGE_MENU_SECTIONS.includes(key) && (key !== 'configuration' || configurable));
+
+export const OPTIONAL_SIDEBAR_ITEMS: readonly NavigationItem<SidebarKey>[] = MANAGE_SECTIONS
+ .flatMap(([key, label, glyph]): NavigationItem<SidebarKey>[] => key === 'configuration' ? []
+ : [[key === 'follow' ? 'follow-manage' : key === 'cleanup' ? 'data-cleanup' : key, label, glyph]]);
+export const NAV_CATALOG: readonly NavigationItem<SidebarKey>[] = [...SIDEBAR_ITEMS, ...OPTIONAL_SIDEBAR_ITEMS];
+export const DIRECT_MANAGE_NAV: Readonly<Partial<Record<SidebarKey, ManagementKey>>> = {
+ stats: 'stats', review: 'review', 'data-cleanup': 'cleanup', trash: 'trash',
+ 'follow-manage': 'follow', quality: 'quality', activity: 'activity',
+};
diff --git a/frontend/src/application/source-action.ts b/frontend/src/application/source-action.ts
new file mode 100644
index 000000000..e770924e4
--- /dev/null
+++ b/frontend/src/application/source-action.ts
@@ -0,0 +1,33 @@
+import { esc } from '../core';
+import { setActionBusy } from '../ui-kit/controls';
+import { spinnerHtml } from '../ui-kit/markup';
+
+export interface SourceActionPorts {
+ request(id: number): Promise<unknown>;
+ success(): void;
+ failureText(error: unknown): string;
+}
+export interface SourceActionStatus { textContent: string | null }
+export interface SourceActionOptions { button?: HTMLElement | null }
+
+/** 定位请求的忙态、终态提示与按钮恢复;请求只提交资产 id。 */
+export function createRevealSourceAction(ports: SourceActionPorts) {
+ return async (id: number, status: SourceActionStatus, { button = null }: SourceActionOptions = {}): Promise<void> => {
+ if (button?.getAttribute('aria-busy') === 'true') return;
+ const html = button?.innerHTML ?? '', label = button?.textContent?.trim() ?? '';
+ if (button) {
+ setActionBusy(button);
+ button.innerHTML = `${spinnerHtml('正在定位')}${label ? `<span>${esc(label)}</span>` : ''}`;
+ }
+ status.textContent = '';
+ try {
+ await ports.request(id);
+ status.textContent = '';
+ ports.success();
+ } catch (error) {
+ status.textContent = ports.failureText(error);
+ } finally {
+ if (button) { setActionBusy(button, false); button.innerHTML = html }
+ }
+ };
+}
diff --git a/frontend/test/application/navigation-items.test.ts b/frontend/test/application/navigation-items.test.ts
new file mode 100644
index 000000000..87ec9469b
--- /dev/null
+++ b/frontend/test/application/navigation-items.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { getManageMenuSections, NAV_CATALOG, SIDEBAR_ITEMS } from '../../src/application/navigation-items';
+import { DEFAULT_SIDEBAR_ORDER, normalizeSidebarOrder } from '../../src/sidebar';
+
+describe('应用导航词表', () => {
+ it('关注的下一项是沉浸模式,可选入口不挤进默认可见顺序', () => {
+ const keys = SIDEBAR_ITEMS.map(([key]) => key);
+ expect(keys.slice(keys.indexOf('follow'), keys.indexOf('follow') + 2)).toEqual(['follow', 'immerse']);
+ expect(normalizeSidebarOrder([])).toEqual(DEFAULT_SIDEBAR_ORDER);
+ expect(DEFAULT_SIDEBAR_ORDER).not.toContain('immerse');
+ expect(NAV_CATALOG.map(([key]) => key)).toContain('immerse');
+ });
+
+ it('每个导航身份只有一项,关注更新与关注管理有各自可见名称', () => {
+ const keys = NAV_CATALOG.map(([key]) => key);
+ expect(new Set(keys).size).toBe(keys.length);
+ expect(NAV_CATALOG.find(([key]) => key === 'follow')?.[1]).toBe('关注');
+ expect(NAV_CATALOG.find(([key]) => key === 'follow-manage')?.[1]).toBe('关注管理');
+ });
+
+ it('配置入口只在本机可改时出现在管理菜单,其余入口顺序不动', () => {
+ const enabled = getManageMenuSections(true), locked = getManageMenuSections(false);
+ expect(enabled.some(([key]) => key === 'configuration')).toBe(true);
+ expect(locked.some(([key]) => key === 'configuration')).toBe(false);
+ expect(enabled.filter(([key]) => key !== 'configuration')).toEqual(locked);
+ });
+});
diff --git a/frontend/test/application/source-action.test.ts b/frontend/test/application/source-action.test.ts
new file mode 100644
index 000000000..dbb2b2617
--- /dev/null
+++ b/frontend/test/application/source-action.test.ts
@@ -0,0 +1,66 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createRevealSourceAction } from '../../src/application/source-action';
+
+afterEach(() => { document.body.innerHTML = '' });
+
+function surface() {
+ const button = document.createElement('button'), status = document.createElement('p');
+ button.innerHTML = '<span>定位源文件 &amp; 目录</span>';
+ status.textContent = '上一次的错误';
+ document.body.append(button, status);
+ button.focus();
+ return { button, status, html: button.innerHTML };
+}
+
+describe('定位资产动作', () => {
+ it('等待留在可聚焦按钮中,重复触发不重发;成功才回执并恢复原按钮', async () => {
+ let release!: () => void;
+ const request = vi.fn(() => new Promise<void>((done) => { release = done })), success = vi.fn();
+ const reveal = createRevealSourceAction({ request, success, failureText: () => '' });
+ const { button, status, html } = surface();
+ const pending = reveal(41, status, { button });
+ expect(request).toHaveBeenCalledWith(41);
+ expect(status.textContent).toBe('');
+ expect(button.getAttribute('aria-busy')).toBe('true');
+ expect(button.getAttribute('aria-disabled')).toBe('true');
+ expect(button.disabled).toBe(false);
+ expect(document.activeElement).toBe(button);
+ expect(button.querySelector('[role="status"]')?.getAttribute('aria-label')).toBe('正在定位');
+ expect(button.textContent).toContain('定位源文件 & 目录');
+ await reveal(41, status, { button });
+ expect(request).toHaveBeenCalledTimes(1);
+ expect(success).not.toHaveBeenCalled();
+ release(); await pending;
+ expect(success).toHaveBeenCalledTimes(1);
+ expect(status.textContent).toBe('');
+ expect(button.innerHTML).toBe(html);
+ expect(button.hasAttribute('aria-busy')).toBe(false);
+ expect(button.hasAttribute('aria-disabled')).toBe(false);
+ });
+
+ it('失败留在动作旁边,不发成功回执,忙态恢复后可以重试', async () => {
+ const missing = new Error('源文件离线'), request = vi.fn().mockRejectedValueOnce(missing).mockResolvedValueOnce(undefined);
+ const success = vi.fn(), failureText = vi.fn(() => '源文件不在这台机器上');
+ const reveal = createRevealSourceAction({ request, success, failureText });
+ const { button, status, html } = surface();
+ await reveal(41, status, { button });
+ expect(failureText).toHaveBeenCalledWith(missing);
+ expect(status.textContent).toBe('源文件不在这台机器上');
+ expect(success).not.toHaveBeenCalled();
+ expect(button.innerHTML).toBe(html);
+ expect(button.hasAttribute('aria-busy')).toBe(false);
+ await reveal(41, status, { button });
+ expect(request).toHaveBeenCalledTimes(2);
+ expect(status.textContent).toBe('');
+ expect(success).toHaveBeenCalledTimes(1);
+ });
+
+ it('React 调用方接收失败文本并自行画等待态,不需要提供按钮', async () => {
+ const status = { textContent: '' }, success = vi.fn();
+ const reveal = createRevealSourceAction({ request: async () => { throw new Error('offline') },
+ success, failureText: () => '脱盘' });
+ await reveal(42, status);
+ expect(status.textContent).toBe('脱盘');
+ expect(success).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/test/react/settings-panel.test.tsx b/frontend/test/react/settings-panel.test.tsx
index bc0813411..f50d02c80 100644
--- a/frontend/test/react/settings-panel.test.tsx
+++ b/frontend/test/react/settings-panel.test.tsx
@@ -16,6 +16,7 @@ import type {
PanelSettings, SettingsEffect, SettingsPanelApi, SettingsPanelHost,
} from '../../src/react/settings-panel/settings-panel-api';
import { createSettingsStore } from '../../src/settings-store';
+import { FOLLOW_INITIAL_RANGE_OPTIONS } from '../../src/application/initial-follow-ranges';
import { click, settle } from './render';
@@ -125,7 +126,7 @@ function panelHost() {
navCatalog: [['', '首页', 'house']],
themeOptions: [['system', '跟随系统', 'monitor'], ['light', '浅色', 'sun'], ['dark', '深色', 'moon']],
videoLayouts: [['small', '小'], ['large', '大']],
- followInitialRanges: [['30', '30 天']],
+ followInitialRanges: FOLLOW_INITIAL_RANGE_OPTIONS,
videoLayout: () => 'small', setVideoLayout: () => {},
censored: () => false, setCensored: () => {}, highContrast: () => false, setHighContrast,
receipt: () => {}, failure: () => {}, syncRemote: () => {}, openConfiguration: () => {}, attached,
@@ -169,6 +170,34 @@ 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);
+ 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();
+ 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('已保存,适用于尚未开始采集的来源。');
+ await close(current);
+ });
+
it('每一个开关只落一次盘、只报自己那一个效果名', async () => {
const current = await setup();
const panel = await open(current);
diff --git a/frontend/test/react/sidebar.test.tsx b/frontend/test/react/sidebar.test.tsx
index ea1799cbb..d3e97d18b 100644
--- a/frontend/test/react/sidebar.test.tsx
+++ b/frontend/test/react/sidebar.test.tsx
@@ -9,6 +9,8 @@ import { createRoot } from 'react-dom/client';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { createSettingsStore } from '../../src/settings-store';
+import { NAV_CATALOG } from '../../src/application/navigation-items';
+import { DEFAULT_SIDEBAR_ORDER } from '../../src/sidebar';
import { sidebarSkeletonHtml } from '../../src/sidebar-skeleton';
import type { BatchDockApi, BatchDockHost } from '../../src/react/batch-dock/batch-dock-api';
import type { ShellActions } from '../../src/react/router/shell-actions';
@@ -235,6 +237,24 @@ describe('换手', () => {
});
describe('导航', () => {
+ it('完整词表按持久偏好画默认导航,沉浸模式可在关注后启用', async () => {
+ const r = await load();
+ await mountRouter(r);
+ await connect(r);
+ const { scroll, host, store } = sidebarHost([...DEFAULT_SIDEBAR_ORDER]);
+ host.navCatalog = NAV_CATALOG;
+ scroll.innerHTML = sidebarSkeletonHtml(store.value.sidebarOrder, NAV_CATALOG, host.navOn);
+ await act(async () => { await r.islands.loadSidebar(host) });
+ expect(navKeys(scroll)).toEqual(DEFAULT_SIDEBAR_ORDER);
+ expect(scroll.querySelector('[data-nav="immerse"]')).toBeNull();
+ await act(async () => {
+ store.value.sidebarOrder = ['follow', 'immerse', ...DEFAULT_SIDEBAR_ORDER.filter((key) => key !== 'follow')];
+ store.save();
+ });
+ expect(navKeys(scroll).slice(0, 2)).toEqual(['follow', 'immerse']);
+ expect(scroll.querySelector('[data-nav="immerse"]')?.textContent).toContain('沉浸模式');
+ });
+
it('store 里的顺序一变(设置面板或另一台机器同步回来),这一列当场重排', async () => {
const { scroll, store } = await setup();
act(() => { store.value.sidebarOrder = ['follow', '', 'stats']; store.save() });
diff --git a/tests/test_follow_web.py b/tests/test_follow_web.py
index 66906bd70..49b5bb801 100644
--- a/tests/test_follow_web.py
+++ b/tests/test_follow_web.py
@@ -2962,22 +2962,16 @@ class LegacyHistoryEndPayloadTests(unittest.TestCase):
class FollowShellDecisionTests(unittest.TestCase):
- """应用默认导航的关注入口与换一批策略。"""
+ """关注页的换一批策略。"""
- def test_follow_sits_before_immerse_and_neither_follow_page_joins_the_refresh(self):
- """左栏「关注」排在沉浸模式前面;顶栏换一批不重画两个关注页。
+ def test_neither_follow_page_joins_the_refresh(self):
+ """顶栏换一批不重画两个关注页。
关注页重画要联网,联网只在按下「检查全部」时发生;`refreshAll` 认路由元数据上的
`refresh: 'skip'` 跳过它们。两页都登记在 `ROUTE_META`,由
`frontend/test/history/history.test.ts` 钉住。
"""
application = ROOT / 'frontend/src/application'
- page = (application / 'layout.js').read_text(encoding="utf-8")
- rail = re.search(r'\bSIDEBAR_ITEMS\s*=\s*\[(.*?)\];', page, re.S).group(1)
- keys = re.findall(r"\['([a-z]*)'", rail)
- self.assertIn("follow", keys)
- self.assertEqual(keys[keys.index("follow") + 1], "immerse",
- "关注入口应当排在沉浸模式前面")
preferences = (application / 'preferences.js').read_text(encoding='utf-8')
self.assertIn("if(refresh==='skip')return;", preferences)
diff --git a/tests/test_studio_icon_variants.py b/tests/test_studio_icon_variants.py
index c11c24b4e..4655ed425 100644
--- a/tests/test_studio_icon_variants.py
+++ b/tests/test_studio_icon_variants.py
@@ -365,13 +365,6 @@ class PageSourceTests(unittest.TestCase):
def setUpClass(cls):
cls.application = ROOT / 'frontend/src/application'
- def test_the_studio_hero_asks_for_the_wordmark(self):
- """大位和小位共用一条取图链,变体由调用方按位置给:大位默认就是字标。
-
- 取图链本身(默认变体与地址)由 `frontend/test/card-art/markup.test.ts` 验。"""
- source = (self.application / 'entity.js').read_text(encoding='utf-8')
- self.assertIn("logo:company&&d.has_logo?d.canonical_name:'',", source)
-
def test_every_small_surface_asks_for_the_icon(self):
source = (self.application / 'catalog.js').read_text(encoding='utf-8')
for snippet in (
diff --git a/tests/test_web_settings.py b/tests/test_web_settings.py
index 2d1e0ca4d..8fa8d8911 100644
--- a/tests/test_web_settings.py
+++ b/tests/test_web_settings.py
@@ -275,17 +275,10 @@ class ContractRegistrationTests(unittest.TestCase):
def test_initial_history_choices_are_in_settings_and_match_the_server(self):
import re
root = Path(__file__).resolve().parents[1]
- page = (root / 'frontend/src/application/lifecycle.js').read_text(encoding='utf-8')
- options = re.search(r'\bFOLLOW_INITIAL_RANGE_OPTIONS\s*=\s*\[(.*?)\];', page, re.S).group(1)
+ page = (root / 'frontend/src/application/initial-follow-ranges.ts').read_text(encoding='utf-8')
+ options = re.search(r'\bFOLLOW_INITIAL_RANGE_OPTIONS\s*=\s*\[(.*?)\]\s*as const', page, re.S).group(1)
self.assertEqual(tuple(int(value) for value in re.findall(r"\['(\d+)',", options)),
web_settings.FOLLOW_INITIAL_DAYS)
- # 设置面板那一格在 `settings-panel` 岛里,选项由壳递进 `followInitialRanges`,选完写账本。
- panel = (root / 'frontend/src/react/settings-panel/settings-panel.tsx').read_text(encoding='utf-8')
- layout = (root / 'frontend/src/application/layout.js').read_text(encoding='utf-8')
- self.assertIn('followInitialRanges:followState.FOLLOW_INITIAL_RANGE_OPTIONS,', layout)
- self.assertIn('initial.mutate({ followInitialDays: value }', panel)
- for source in (page, layout, panel):
- self.assertNotIn('data-follow-unread-days', source)
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 494cef87e..7d83b29b4 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -284,19 +284,6 @@ class WebUiPolicyTests(unittest.TestCase):
self.assertPageLacks("/link-mark?url=", "外链图标端点不得接受前端给的地址")
self.assertPageLacks("/site-mark?url=", "站点圆标端点同样只认键")
- def test_locating_a_source_file_waits_inside_its_button(self):
- """定位源文件的等待态留在按钮里,不往详情里写一行「正在定位…」撑开内容流;按钮保持
- 可聚焦,重复点击由共享 busy 状态挡住。这枚按钮画在壳的照片详情里,组件与浏览器用例都
- 没碰到它。只收 asset id 由 `test_fastapi_api.py` 的定位接口用例保证。"""
- root = Path(__file__).resolve().parents[1]
- entity = (root / "frontend" / "src" / "application" / "entity.js").read_text(encoding="utf-8")
- reveal = entity.split("async function revealSource", 1)[1].split("async function syncMissing", 1)[0]
- self.assertNotIn("status.textContent='正在定位…'", reveal,
- "请求等待态必须留在按钮内,不能撑开详情内容流")
- self.assertNotIn("button.disabled", reveal,
- "等待按钮应保持可聚焦,并由共享 busy 状态阻止重复请求")
-
-
# void 元素没有结束标签,压进栈里只会制造假报错。
_VOID = frozenset({
"area", "base", "br", "col", "embed", "hr", "img", "input", "link",