Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(web): 支持实体收藏与命名馆藏筛选

longmeidao1df96d891a8f
diff --git a/frontend/e2e/library-shortcuts.test.ts b/frontend/e2e/library-shortcuts.test.ts
new file mode 100644
index 000000000..db0fe790b
--- /dev/null
+++ b/frontend/e2e/library-shortcuts.test.ts
@@ -0,0 +1,57 @@
+import assert from 'node:assert/strict';
+import { after, before, describe, it } from 'node:test';
+import type { Browser } from 'playwright-core';
+import { launch, layout, VIEWPORTS } from './harness.ts';
+import { openItemPage } from './item-fixture.ts';
+
+describe('收藏与筛选弹层', () => {
+ let browser: Browser;
+ before(async () => { browser = await launch() });
+ after(async () => { await browser.close() });
+ for (const viewport of VIEWPORTS) {
+ it(`${viewport.name} 保存、应用、删除筛选及收藏分类`, { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, '/watch-later?loc=&tag=VR&jav=1', viewport, { ready: '[data-catalog-frame]' });
+ const page = opened.page;
+ let favorites = [{ key: 'entity:7', entity_id: 7, kind: 'studio', name: '厂牌长名称'.repeat(12) }];
+ let filters: { id: string; name: string; href: string }[] = [];
+ await page.route(url => url.pathname === '/api/library-shortcuts', async route => {
+ if (route.request().method() === 'POST') {
+ const body = route.request().postDataJSON();
+ if (body.action === 'save_filter') filters.push({ id: 'test', name: body.name, href: body.href });
+ if (body.action === 'delete_filter') filters = [];
+ if (body.action === 'favorite') favorites = [];
+ }
+ await route.fulfill({ json: { favorites, filters } });
+ });
+ try {
+ await page.getByRole('button', { name: '收藏与筛选', exact: true }).click();
+ const dialog = page.getByRole('dialog', { name: '收藏与筛选', exact: true });
+ await dialog.getByRole('button', { name: '厂牌', exact: true }).click();
+ await dialog.getByRole('link', { name: favorites[0].name, exact: true }).waitFor();
+ const size = await layout(page);
+ assert(size.scrollWidth <= size.viewportWidth + 1, JSON.stringify(size));
+ assert.deepEqual(size.offenders, []);
+ await dialog.getByRole('textbox', { name: '筛选名称' }).fill('VR 待看');
+ await dialog.getByRole('button', { name: '保存当前筛选', exact: true }).click();
+ const link = dialog.getByRole('link', { name: 'VR 待看', exact: true });
+ await link.waitFor();
+ const href = await link.getAttribute('href');
+ const address = new URL(href!, page.url());
+ assert.equal(address.pathname, '/watch-later');
+ assert.equal(address.searchParams.get('loc'), '');
+ assert.equal(address.searchParams.get('tag'), 'VR');
+ assert.equal(address.searchParams.get('jav'), '1');
+ await link.click();
+ await page.waitForURL(url => url.pathname === '/watch-later' && url.searchParams.get('tag') === 'VR');
+ await page.getByRole('button', { name: '收藏与筛选', exact: true }).click();
+ await dialog.getByRole('button', { name: '删除筛选VR 待看', exact: true }).click();
+ await link.waitFor({ state: 'detached' });
+ await dialog.getByRole('button', { name: /^取消收藏/ }).click();
+ await dialog.getByRole('heading', { name: '还没有收藏', exact: true }).waitFor();
+ await dialog.getByRole('button', { name: '关闭', exact: true }).click();
+ await dialog.waitFor({ state: 'hidden' });
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close() }
+ });
+ }
+});
diff --git a/frontend/src/application/catalog.js b/frontend/src/application/catalog.js
index 00ec00be1..79ae28515 100644
--- a/frontend/src/application/catalog.js
+++ b/frontend/src/application/catalog.js
@@ -203,6 +203,14 @@ export function paintCatalogFilter(patch){
export function catalogFilterActions(){
return {
+ currentHref:()=>{
+ const href=new URL(homePath(),location.origin);
+ href.searchParams.set('loc',state.loc||'');
+ href.searchParams.set('thumb',state.thumb||'0');
+ href.searchParams.set('sort',state.sort||'');
+ href.searchParams.set('dir',state.dir||'');
+ return href.pathname+href.search;
+ },
openEntity:(kind,name)=>openEntity(kind,name),
/* 按下去当场就推新的按下态,滑动玻璃跟着走,不等这一趟取数。 */
setView:view=>{
diff --git a/frontend/src/react/catalog-filter/catalog-filter-page.tsx b/frontend/src/react/catalog-filter/catalog-filter-page.tsx
index 8cc1a682a..bf95b032f 100644
--- a/frontend/src/react/catalog-filter/catalog-filter-page.tsx
+++ b/frontend/src/react/catalog-filter/catalog-filter-page.tsx
@@ -13,6 +13,7 @@ import { fitSkeleton, popBadges, popCount } from '@peach/legacy/ui';
import { FilterGlassRows, FilterPill } from '../components/filter-glass';
import { useViewGlide } from '../components/use-view-glide';
+import { LibraryShortcuts } from '../library-shortcuts/shortcut-controls';
import { Combo, Segments, Shuffle, SortKeys } from '../entity-filter/entity-filter-page';
import {
EMPTY_SLOTS, ROW_AHEAD, ROW_BATCH, ROW_FIRST, type CatalogFilterProps, type CatalogTag, type TierKind,
@@ -185,6 +186,7 @@ function Head({ count, refreshing, layout, sorts, actions }: CatalogFilterProps)
<>
<Readout count={count} />
<span data-entity-sorts="">
+ <LibraryShortcuts currentHref={actions.currentHref} />
<Shuffle onPress={shuffle} busy={shuffling || refreshing} />
{/* 按名字换键:JAV 与首页各一组,React Aria 的单选组挂上之后不改 `name`。 */}
{layout ? <Segments key={layout.name} name={layout.name} label={layout.label} value={layout.value} options={layout.options}
diff --git a/frontend/src/react/catalog-filter/catalog-filter.ts b/frontend/src/react/catalog-filter/catalog-filter.ts
index dd044f408..1761dff84 100644
--- a/frontend/src/react/catalog-filter/catalog-filter.ts
+++ b/frontend/src/react/catalog-filter/catalog-filter.ts
@@ -60,6 +60,7 @@ export interface CatalogLayout {
}
export interface CatalogFilterActions {
+ currentHref?(): string;
/** 头像条上的一格:打开那一位的资料页。 */
openEntity(kind: 'performer' | 'studio', name: string): void;
/** 四枚视图里的一枚。 */
diff --git a/frontend/src/react/entity-hero/entity-hero-page.tsx b/frontend/src/react/entity-hero/entity-hero-page.tsx
index a7afdd030..2b64c4fe7 100644
--- a/frontend/src/react/entity-hero/entity-hero-page.tsx
+++ b/frontend/src/react/entity-hero/entity-hero-page.tsx
@@ -17,6 +17,7 @@ import { Button } from '@/components/base/buttons/button';
import { AvatarPicker } from '../avatar-picker/avatar-picker-page';
import { Note } from '../components/note';
+import { FavoriteButton, LibraryShortcuts } from '../library-shortcuts/shortcut-controls';
import { busyProps } from '../settings/busy-props';
import { FeedNewRow } from '../feed-new/feed-new-row';
import { Glyph } from './glyph';
@@ -70,6 +71,10 @@ export function EntityHeroPage({ kind, name, entity, feedNew, feedHost, actions,
onChoose={actions.chooseName} onAddAlias={actions.addAlias} />
</div>
<AliasLine kind={kind} entity={entity} actions={actions} />
+ {entity.id ? <div className="flex flex-wrap gap-2">
+ <FavoriteButton item={{ entity_id: Number(entity.id), kind, name: entity.canonical_name || name, favorite: entity.favorite }} />
+ <LibraryShortcuts kind={kind} />
+ </div> : null}
{entity.related_identities?.length ? (
<div className="flex min-w-0 flex-wrap gap-2 text-caption-1-regular text-text-secondary">
{/* 账号名常是一长串无空格的英文,窄屏下得能在任意处折行。 */}
diff --git a/frontend/src/react/entity-hero/entity-hero.ts b/frontend/src/react/entity-hero/entity-hero.ts
index 8e8273e97..c42921838 100644
--- a/frontend/src/react/entity-hero/entity-hero.ts
+++ b/frontend/src/react/entity-hero/entity-hero.ts
@@ -76,6 +76,7 @@ export interface HeroFollow {
/** `/api/entity` 里资料卡读到的那些字段。 */
export interface EntityHeroData {
+ favorite?: boolean;
company_profile?: Partial<Record<'legal_name' | 'founded' | 'launched' | 'country' | 'location' | 'operator' | 'parent' | 'group' | 'distributor', { value: string; source_url: string; evidence?: string }>>;
identity_labels?: string[];
external_refs?: { provider: string; external_kind: string; external_id: string }[];
diff --git a/frontend/src/react/index/index-data.ts b/frontend/src/react/index/index-data.ts
index 794d25e9e..0f56e1d9d 100644
--- a/frontend/src/react/index/index-data.ts
+++ b/frontend/src/react/index/index-data.ts
@@ -77,6 +77,8 @@ export interface IndexPerson {
}
export interface IndexTag {
+ entity_id?: number;
+ favorite?: boolean;
k: string;
n: number;
cat?: string;
diff --git a/frontend/src/react/index/index-page.tsx b/frontend/src/react/index/index-page.tsx
index 3ff468c19..eabd0c4f8 100644
--- a/frontend/src/react/index/index-page.tsx
+++ b/frontend/src/react/index/index-page.tsx
@@ -21,6 +21,7 @@ import { IDENTITY_ROW_CLASS } from '../../identity-filter';
import { BoardTabs, type BoardTab } from '../components/board-tabs';
import { EmptyState } from '../components/empty-state';
+import { LibraryShortcuts } from '../library-shortcuts/shortcut-controls';
import { LoadingDots } from '../components/loading-dots';
import { SEGMENTED_TRACK, SEGMENT_ICON, SegmentedRadioGroup as RadioGroup } from '../components/segmented';
import { spriteGlyph } from '../components/sprite-glyph';
@@ -237,6 +238,7 @@ export function IndexPage(props: IndexProps) {
</span>
) : null}
{isPeople(kind) ? <LayoutSwitch kind={kind} layout={layout} onChange={changeLayout} /> : null}
+ <LibraryShortcuts kind={kind === 'tags' ? 'tag' : kind === 'studios' ? 'studio' : kind === 'agencies' ? 'agency' : kind === 'creators' ? 'creator' : 'performer'} />
{/* 窄屏一行放不下四样东西:标题与过滤框一行,开关另起一行。 */}
<span aria-hidden className="hidden h-0 basis-full max-board-narrow:order-2 max-board-narrow:block" />
<IndexSearch label={`过滤${title}`} value={q} onQuery={(next) => { if (next !== q) go({ q: next }, !!next) }} />
diff --git a/frontend/src/react/index/index-tags.tsx b/frontend/src/react/index/index-tags.tsx
index d2c660095..a70f9d1ec 100644
--- a/frontend/src/react/index/index-tags.tsx
+++ b/frontend/src/react/index/index-tags.tsx
@@ -15,6 +15,7 @@ import { FilterGlassRows, FilterPill } from '../components/filter-glass';
import { SEGMENTED_GLASS_TRACK, SEGMENT_GLASS } from '../components/segmented';
import { SelectionDock } from '../components/selection-dock';
import { spriteGlyph } from '../components/sprite-glyph';
+import { FavoriteButton } from '../library-shortcuts/shortcut-controls';
import { tagColorKey, type IndexTag, type TagView } from './index-data';
export interface TagEntry extends IndexTag {
@@ -35,13 +36,16 @@ const Dot = () => <span aria-hidden data-tag-dot="" className="size-1.75 flex-no
function AlphaTag({ tag, actions }: { tag: TagEntry; actions: TagActions }) {
const pressed = actions.picked.has(tag.k);
return (
+ <div className="flex min-w-0 items-center gap-1">
<button type="button" data-alpha-tag="" data-k={tag.k} data-tag-cat={tagColorKey(actions.online, tag.cat)}
aria-pressed={pressed} title={tag.label} onClick={() => actions.press(tag.k)}
- className="flex h-9 min-w-0 cursor-pointer items-center gap-2.25 rounded-lg px-2.5 text-left text-body-regular text-text-secondary outline-none hover:text-text-primary focus-visible:ring-2 focus-visible:ring-border-focus-ring">
+ className="flex h-9 min-w-0 flex-1 cursor-pointer items-center gap-2.25 rounded-lg px-2.5 text-left text-body-regular text-text-secondary outline-none hover:text-text-primary focus-visible:ring-2 focus-visible:ring-border-focus-ring">
<Dot />
<span className="min-w-0 flex-1 truncate">{tag.label}</span>
<span className="flex-none text-caption-1-regular text-text-secondary">{tag.n.toLocaleString()}</span>
</button>
+ {!actions.online ? <FavoriteButton item={{ kind: 'tag', name: tag.k, entity_id: tag.entity_id, favorite: tag.favorite }} /> : null}
+ </div>
);
}
@@ -74,13 +78,16 @@ export function TagCloud({ tags, actions }: { tags: TagEntry[]; actions: TagActi
return (
<div data-tag-cloud="" className="flex flex-wrap gap-1.75">
{tags.map((tag) => (
- <button key={tag.k} type="button" data-tag-chip="" data-k={tag.k}
+ <span key={tag.k} className="inline-flex min-w-0 items-center gap-1">
+ <button type="button" data-tag-chip="" data-k={tag.k}
data-tag-cat={tagColorKey(actions.online, tag.cat)} aria-pressed={actions.picked.has(tag.k)}
onClick={() => actions.press(tag.k)}
className="inline-flex cursor-pointer items-center rounded-lg border px-3 py-1.25 text-body-2-regular text-text-secondary outline-none focus-visible:ring-2 focus-visible:ring-border-focus-ring">
{tag.label + NBSP}
<span data-tag-n="" className="text-caption-1-regular opacity-60">{tag.n.toLocaleString()}</span>
</button>
+ {!actions.online ? <FavoriteButton item={{ kind: 'tag', name: tag.k, entity_id: tag.entity_id, favorite: tag.favorite }} /> : null}
+ </span>
))}
</div>
);
diff --git a/frontend/src/react/library-shortcuts/library-shortcuts.ts b/frontend/src/react/library-shortcuts/library-shortcuts.ts
new file mode 100644
index 000000000..aa4936659
--- /dev/null
+++ b/frontend/src/react/library-shortcuts/library-shortcuts.ts
@@ -0,0 +1,27 @@
+import { useMutation, useQuery } from '@tanstack/react-query';
+import { apiGet, apiSend } from '../../api';
+import { queryClient } from '../query';
+import { entityPath } from '@peach/legacy/core';
+
+export interface Favorite { key?: string; entity_id?: number; kind: string; name: string; favorite?: boolean }
+export interface SavedFilter { id: string; name: string; href: string }
+export interface Shortcuts { favorites: Favorite[]; filters: SavedFilter[] }
+export const SHORTCUTS_KEY = ['library-shortcuts'] as const;
+const URL = '/api/library-shortcuts';
+
+export function useShortcuts(enabled = true) {
+ return useQuery({ queryKey: SHORTCUTS_KEY, queryFn: ({ signal }) => apiGet<Shortcuts>(URL, signal), enabled });
+}
+export function useShortcutWrite() {
+ return useMutation({ mutationKey: SHORTCUTS_KEY,
+ mutationFn: (body: Record<string, unknown>) => apiSend<Shortcuts>(URL, body),
+ onSuccess: (data) => { queryClient.setQueryData(SHORTCUTS_KEY, data) },
+ });
+}
+export function isFavorite(rows: Favorite[], item: Favorite): boolean {
+ return rows.some((row) => item.entity_id ? row.entity_id === item.entity_id : row.kind === item.kind && row.name === item.name);
+}
+export function favoriteHref(item: Favorite): string {
+ return item.kind === 'tag' ? '/?tag=' + encodeURIComponent(item.name)
+ : entityPath(item.kind, item.name);
+}
diff --git a/frontend/src/react/library-shortcuts/shortcut-controls.tsx b/frontend/src/react/library-shortcuts/shortcut-controls.tsx
new file mode 100644
index 000000000..9c51442af
--- /dev/null
+++ b/frontend/src/react/library-shortcuts/shortcut-controls.tsx
@@ -0,0 +1,93 @@
+import { useState, type FormEvent } from 'react';
+import { Button, ButtonLink } from '@/components/base/buttons/button';
+import { Input } from '@/components/base/input/input';
+import { errorMessage } from '../../api';
+import { ModalFrame } from '../components/modal-frame';
+import { Note } from '../components/note';
+import { EmptyState } from '../components/empty-state';
+import { spriteGlyph } from '../components/sprite-glyph';
+import { busyProps } from '../settings/busy-props';
+import { favoriteHref, isFavorite, useShortcuts, useShortcutWrite, type Favorite } from './library-shortcuts';
+
+const Star = spriteGlyph('star');
+const LABELS: Record<string, string> = { performer: '艺人', creator: '创作者', studio: '厂牌', series: '系列', agency: '事务所', tag: '标签' };
+
+export function FavoriteButton({ item }: { item: Favorite }) {
+ const query = useShortcuts(false);
+ const write = useShortcutWrite();
+ const selected = query.data ? isFavorite(query.data.favorites || [], item) : !!item.favorite;
+ return <span className="inline-flex min-w-0 flex-col gap-1">
+ <Button variant="secondary" size="small" leadingIcon={Star} aria-pressed={selected}
+ aria-label={`${selected ? '取消收藏' : '收藏'}${item.name}`}
+ {...busyProps(write.isPending)} onClick={() => {
+ if (!write.isPending) write.mutate({ action: 'favorite', ...item, on: !selected });
+ }}>{selected ? '已收藏' : '收藏'}</Button>
+ {write.isError ? <Note tone="error">{errorMessage(write.error)}</Note> : null}
+ {query.isError ? <Button variant="secondary" size="small" onClick={() => void query.refetch()}>重试读取收藏</Button> : null}
+ </span>;
+}
+
+/** 收藏名册与保存的馆藏筛选共用入口;只有打开时才读取完整列表。 */
+export function LibraryShortcuts({ currentHref, kind }: { currentHref?: () => string; kind?: string }) {
+ const [open, setOpen] = useState(false);
+ return <>
+ <Button variant="secondary" size="small" leadingIcon={Star} onClick={() => setOpen(true)}>收藏与筛选</Button>
+ <ModalFrame isOpen={open} onOpenChange={setOpen} width="form" label="收藏与筛选">
+ {open ? <ShortcutContents currentHref={currentHref} kind={kind} close={() => setOpen(false)} /> : null}
+ </ModalFrame>
+ </>;
+}
+
+function ShortcutContents({ currentHref, kind, close }: { currentHref?: () => string; kind?: string; close(): void }) {
+ const query = useShortcuts();
+ const write = useShortcutWrite();
+ const [name, setName] = useState('');
+ const [scope, setScope] = useState(kind || 'all');
+ const [message, setMessage] = useState('');
+ const submit = (event: FormEvent) => {
+ event.preventDefault();
+ if (!currentHref || !name.trim() || write.isPending) return;
+ write.mutate({ action: 'save_filter', name: name.trim(), href: currentHref() }, {
+ onSuccess: () => { setName(''); setMessage('筛选已保存') },
+ });
+ };
+ const data = query.data;
+ const rows = (data?.favorites || []).filter((row) => scope === 'all' || row.kind === scope);
+ return <div className="flex min-h-0 min-w-0 flex-col">
+ <div className="flex shrink-0 items-center justify-between gap-3 border-b border-separator-border p-5">
+ <h2 className="text-title-2-semibold text-text-primary">收藏与筛选</h2>
+ <Button variant="secondary" size="small" onClick={close}>关闭</Button>
+ </div>
+ <div className="flex min-h-0 flex-col gap-4 overflow-y-auto overscroll-contain p-5">
+ {query.isPending ? <div aria-busy="true" data-skeleton="" className="h-12 animate-pulse rounded-lg bg-background-secondary-default" /> : null}
+ {query.isError ? <Note tone="error" action={<Button variant="secondary" onClick={() => void query.refetch()}>重试</Button>}>{errorMessage(query.error)}</Note> : null}
+ {write.isError ? <Note tone="error">{errorMessage(write.error)}</Note> : null}
+ {data ? <>
+ <h3 className="text-body-medium text-text-primary">收藏</h3>
+ <div className="flex flex-wrap gap-2" role="group" aria-label="收藏类型">
+ {[['all', '全部'], ...Object.entries(LABELS)].map(([value, label]) =>
+ <Button key={value} variant="secondary" size="small" aria-pressed={scope === value}
+ onClick={() => setScope(value)}>{label}</Button>)}
+ </div>
+ {!rows.length ? <EmptyState shell="plain" icon={Star} title="还没有收藏">在资料页或标签页收藏常用内容。</EmptyState> : null}
+ {rows.map((row) => <div key={row.key} className="flex min-w-0 items-center justify-between gap-2">
+ <a href={favoriteHref(row)} className="min-w-0 flex-1 break-all text-body-regular text-text-primary underline">{row.name}</a>
+ <Button variant="secondary" size="small" aria-label={`取消收藏${row.name}`} {...busyProps(write.isPending)}
+ onClick={() => { if (!write.isPending) write.mutate({ action: 'favorite', ...row, on: false }) }}>取消收藏</Button>
+ </div>)}
+ <h3 className="text-body-medium text-text-primary">保存的筛选</h3>
+ {!data.filters.length ? <EmptyState shell="plain" icon={spriteGlyph('filter')} title="还没有保存的筛选">在馆藏页保存当前条件,随时打开。</EmptyState> : null}
+ {data.filters.map((row) => <div key={row.id} className="flex min-w-0 items-center justify-between gap-2">
+ <span className="min-w-0 flex-1 overflow-hidden"><ButtonLink variant="secondary" href={row.href} title={row.name}>{row.name}</ButtonLink></span>
+ <Button variant="secondary" size="small" aria-label={`删除筛选${row.name}`} {...busyProps(write.isPending)}
+ onClick={() => { if (!write.isPending) write.mutate({ action: 'delete_filter', id: row.id }) }}>删除</Button>
+ </div>)}
+ {currentHref ? <form onSubmit={submit} className="flex flex-col gap-3" aria-label="保存当前筛选">
+ <Input label="筛选名称" value={name} onChange={setName} maxLength={80} />
+ <Button type="submit" disabled={!name.trim()} {...busyProps(write.isPending)}>保存当前筛选</Button>
+ {message ? <span role="status" className="text-body-2-regular text-text-secondary">{message}</span> : null}
+ </form> : null}
+ </> : null}
+ </div>
+ </div>;
+}
diff --git a/frontend/test/react/library-shortcuts.test.tsx b/frontend/test/react/library-shortcuts.test.tsx
new file mode 100644
index 000000000..a88f58809
--- /dev/null
+++ b/frontend/test/react/library-shortcuts.test.tsx
@@ -0,0 +1,69 @@
+import { notifyManager, QueryClientProvider } from '@tanstack/react-query';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { queryClient } from '../../src/react/query';
+import { FavoriteButton, LibraryShortcuts } from '../../src/react/library-shortcuts/shortcut-controls';
+import { favoriteHref, SHORTCUTS_KEY, type Shortcuts } from '../../src/react/library-shortcuts/library-shortcuts';
+import { buttonNamed, click, mount, pending, settle, submit, type } from './render';
+
+notifyManager.setScheduler((notify) => notify());
+afterEach(() => { queryClient.clear() });
+const empty: Shortcuts = { favorites: [], filters: [] };
+
+describe('收藏与筛选', () => {
+ it('等待收藏回执时保持可聚焦,回读后允许取消', async () => {
+ queryClient.setQueryData(SHORTCUTS_KEY, empty);
+ const answer = pending<unknown>();
+ const calls: unknown[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url, init) => {
+ if (!init?.body) return { ok: true, json: async () => empty };
+ calls.push(JSON.parse(init.body));
+ return { ok: true, json: async () => calls.length === 1 ? answer.answer : empty };
+ }));
+ const host = await mount(<QueryClientProvider client={queryClient}>
+ <FavoriteButton item={{ entity_id: 1, kind: 'studio', name: '厂牌' }} />
+ </QueryClientProvider>);
+ await click(buttonNamed('收藏', host));
+ const button = host.querySelector('button')!;
+ expect(button.disabled).toBe(false);
+ expect(button.getAttribute('aria-busy')).toBe('true');
+ await click(button);
+ expect(calls).toHaveLength(1);
+ await answer.release({ favorites: [{ key: 'entity:1', entity_id: 1, kind: 'studio', name: '厂牌' }], filters: [] });
+ await settle();
+ expect(button.getAttribute('aria-pressed')).toBe('true');
+ await click(buttonNamed('已收藏', host));
+ await settle();
+ expect(calls[1]).toMatchObject({ action: 'favorite', entity_id: 1, on: false });
+ expect(button.getAttribute('aria-pressed')).toBe('false');
+ });
+
+ it('保存当前条件后显示可应用链接并可删除', async () => {
+ let data = empty;
+ const writes: Record<string, unknown>[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url, init) => {
+ if (init?.body) {
+ const body = JSON.parse(init.body); writes.push(body);
+ data = body.action === 'save_filter' ? { favorites: [], filters: [{ id: 'one', name: body.name, href: body.href }] } : empty;
+ }
+ return { ok: true, json: async () => data };
+ }));
+ await mount(<QueryClientProvider client={queryClient}>
+ <LibraryShortcuts currentHref={() => '/watch-later?loc=&tag=VR&jav=1'} />
+ </QueryClientProvider>);
+ await click(buttonNamed('收藏与筛选'));
+ await settle();
+ await type(document.querySelector('input'), 'VR 待看');
+ await submit(document.querySelector('form'));
+ await settle();
+ expect(writes[0]).toEqual({ action: 'save_filter', name: 'VR 待看', href: '/watch-later?loc=&tag=VR&jav=1' });
+ expect(document.querySelector('a')?.getAttribute('href')).toBe('/watch-later?loc=&tag=VR&jav=1');
+ await click(document.querySelector('[aria-label="删除筛选VR 待看"]'));
+ await settle();
+ expect(document.querySelector('a')).toBeNull();
+ });
+
+ it('收藏链接使用现有实体路由和编码后的标签', () => {
+ expect(favoriteHref({ kind: 'studio', name: 'A/B' })).toBe('/studios/A%2FB');
+ expect(favoriteHref({ kind: 'tag', name: 'A&B' })).toBe('/?tag=A%26B');
+ });
+});
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index ab07f46fb..8e8888ee6 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -135,7 +135,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_agency_entity.py", "test_label_maker.py", "test_dependency_policy.py",
"test_desktop_settings.py", "test_dev_copy.py",
"test_fastapi_api.py", "test_follow_assets.py", "test_follow_web.py",
- "test_metadata_library.py", "test_studio_icon_variants.py", "test_web_settings.py", "test_company_profiles.py"),
+ "test_metadata_library.py", "test_studio_icon_variants.py", "test_web_settings.py", "test_web_library_shortcuts.py", "test_company_profiles.py"),
"core": ("test_access.py", "test_auth.py", "test_config.py", "test_field_owners.py",
"test_entity_classification.py",
"test_migrations.py", "test_ledger_revision.py",
@@ -227,6 +227,7 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
"src/peach/personal_records.py": ("catalog", "tooling"),
"src/peach/record_rehome.py": ("catalog", "tooling"),
"src/peach/web_orphan_records.py": ("catalog", "web"),
+ "src/peach/web_library_shortcuts.py": ("catalog", "web"),
# 入口页共用件的测试住在首启与配置来源那两份 tooling 测试里。
"src/peach/web_entry.py": ("catalog", "tooling", "web"),
# 这几份文档有测试在读它们的正文:改文档也要跑到那条测试。
diff --git a/src/peach/web_entity.py b/src/peach/web_entity.py
index 37241b6bf..78708892e 100644
--- a/src/peach/web_entity.py
+++ b/src/peach/web_entity.py
@@ -169,6 +169,8 @@ def q_entity(contract: WebContract, args):
return {'redirect': {'kind': merged[0]['kind'], 'name': merged[0]['canonical_name']}}
return {"error": "not found"}
d = dict(row)
+ from .web_library_shortcuts import favorite_ids
+ d["favorite"] = d["id"] in favorite_ids(c)
try:
metadata = json.loads(d.pop("metadata_json") or "{}")
except (TypeError, ValueError):
@@ -607,7 +609,7 @@ def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category="")
_attach_index_following(c, rows)
category_counts = entity_classification.counts(c,entity_kind,q,COUNTED_VIDEO)
else:
- sql = ("SELECT e.canonical_name k, count(DISTINCT " + video_work_key(contract, c) + ") n "
+ sql = ("SELECT e.id entity_id,e.canonical_name k, count(DISTINCT " + video_work_key(contract, c) + ") n "
"FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
"JOIN asset a ON a.id=ae.asset_id WHERE " + COUNTED_VIDEO + " AND e.kind='tag' "
f"AND e.canonical_name NOT IN ({','.join('?' for _ in LENGTH_TAGS)}) "
@@ -624,6 +626,10 @@ def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category="")
all_rows = [row for row in all_rows if row["cat"] == category]
rows = all_rows[offset:offset + limit]
has_more = offset + limit < len(all_rows)
+ from .web_library_shortcuts import favorite_ids
+ favorites = favorite_ids(c)
+ for row in rows:
+ row["favorite"] = row.get("entity_id") in favorites
if kind in INDEX_ENTITY_KINDS:
entity_kind = INDEX_ENTITY_KINDS[kind]
# 索引页一屏几十个圆头像,走的是和顶栏那排同一条两级链:规范实体图优先,
diff --git a/src/peach/web_library_shortcuts.py b/src/peach/web_library_shortcuts.py
new file mode 100644
index 000000000..7e6220827
--- /dev/null
+++ b/src/peach/web_library_shortcuts.py
@@ -0,0 +1,124 @@
+"""收藏与命名筛选;偏好保存在当前 profile,同一事务内按动作修改。"""
+from __future__ import annotations
+
+import json
+import time
+import uuid
+from urllib.parse import parse_qsl, urlencode, urlsplit
+
+from .entities import resolve_entity, resolve_entity_id
+from .web_settings import DEFAULT_PROFILE_ID
+
+KEY = "libraryShortcuts"
+KINDS = frozenset({"performer", "creator", "studio", "series", "agency", "tag"})
+QUERY_KEYS = frozenset({"loc", "creator", "studio", "owner", "tag", "tag_match", "len",
+ "dur_min", "dur_max", "orient", "region", "sort", "dir", "q", "jav", "thumb", "state"})
+PATHS = frozenset({"/", "/unseen", "/watch-later", "/flagged"})
+
+
+def _profile(c):
+ row = c.execute("SELECT settings_json FROM profile WHERE id=?", (DEFAULT_PROFILE_ID,)).fetchone()
+ if row is None:
+ return {}
+ try:
+ value = json.loads(row[0] or "{}")
+ except (ValueError, TypeError):
+ value = {}
+ return value if isinstance(value, dict) else {}
+
+
+def _favorite(c, entry):
+ if not isinstance(entry, dict):
+ return None
+ if entry.get("kind") == "tag" and not entry.get("entity_id"):
+ tag = entry.get("name")
+ if isinstance(tag, str) and 0 < len(tag.strip()) <= 120:
+ entity = resolve_entity(c, "tag", tag.strip())
+ if entity:
+ return _favorite(c, {"entity_id": entity["id"]})
+ return None
+ value = entry.get("entity_id")
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ return None
+ resolved = resolve_entity_id(c, value)
+ row = c.execute("SELECT id,kind,canonical_name FROM entity WHERE id=?", (resolved,)).fetchone() if resolved else None
+ if row is None or row[1] not in KINDS:
+ return None
+ return {"key": "entity:" + str(row[0]), "entity_id": row[0], "kind": row[1], "name": row[2]}
+
+
+def _snapshot(c, settings):
+ stored = settings.get(KEY)
+ stored = stored if isinstance(stored, dict) else {}
+ favorites = {}
+ raw_favorites = stored.get("favorites", [])
+ for item in (raw_favorites if isinstance(raw_favorites, list) else [])[:1000]:
+ current = _favorite(c, item)
+ if current:
+ favorites[current["key"]] = current
+ raw_filters = stored.get("filters", [])
+ filters = []
+ for item in (raw_filters if isinstance(raw_filters, list) else [])[:100]:
+ if not isinstance(item, dict) or not all(isinstance(item.get(key), str) for key in ("id", "name", "href")):
+ continue
+ try:
+ href = clean_href(item["href"])
+ except ValueError:
+ continue
+ filters.append({"id": item["id"][:80], "name": item["name"][:80], "href": href})
+ return {"favorites": list(favorites.values()), "filters": filters}
+
+
+def clean_href(raw):
+ if not isinstance(raw, str) or len(raw) > 4096:
+ raise ValueError("筛选地址过长或格式不正确")
+ parsed = urlsplit(raw)
+ if parsed.scheme or parsed.netloc or parsed.fragment or parsed.path not in PATHS:
+ raise ValueError("只能保存馆藏筛选")
+ pairs = parse_qsl(parsed.query, keep_blank_values=True, max_num_fields=40)
+ if any(key not in QUERY_KEYS or len(value) > 1000 for key, value in pairs):
+ raise ValueError("筛选包含不支持的条件")
+ query = urlencode(dict(pairs))
+ return parsed.path + ("?" + query if query else "")
+
+
+def q_library_shortcuts(contract, _args=None):
+ with contract.read_connection() as c:
+ return _snapshot(c, _profile(c))
+
+
+def favorite_ids(connection):
+ return {row["entity_id"] for row in _snapshot(connection, _profile(connection))["favorites"]}
+
+
+def w_library_shortcuts(contract, body):
+ action = body.get("action")
+ with contract.write_transaction() as c:
+ settings = _profile(c)
+ data = _snapshot(c, settings)
+ if action == "favorite":
+ item = _favorite(c, body)
+ if item is None or not isinstance(body.get("on"), bool):
+ raise ValueError("收藏对象不存在或状态不正确")
+ data["favorites"] = [row for row in data["favorites"] if row["key"] != item["key"]]
+ if body["on"]:
+ if len(data["favorites"]) >= 1000:
+ raise ValueError("最多收藏 1000 项")
+ data["favorites"].append(item)
+ elif action == "save_filter":
+ name = body.get("name")
+ if not isinstance(name, str) or not 0 < len(name.strip()) <= 80:
+ raise ValueError("筛选名称须为 1 到 80 个字符")
+ if len(data["filters"]) >= 100:
+ raise ValueError("最多保存 100 个筛选")
+ data["filters"].append({"id": uuid.uuid4().hex, "name": name.strip(), "href": clean_href(body.get("href"))})
+ elif action == "delete_filter":
+ data["filters"] = [row for row in data["filters"] if row["id"] != body.get("id")]
+ else:
+ raise ValueError("不支持的收藏操作")
+ settings[KEY] = data
+ updated = c.execute("UPDATE profile SET settings_json=?,updated_at=? WHERE id=?",
+ (json.dumps(settings, ensure_ascii=False), time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), DEFAULT_PROFILE_ID)).rowcount
+ if not updated:
+ raise ValueError("当前用户设置不存在")
+ return {"ok": True, **data}
diff --git a/src/peach/web_router.py b/src/peach/web_router.py
index 223e93efd..6d374e421 100644
--- a/src/peach/web_router.py
+++ b/src/peach/web_router.py
@@ -93,6 +93,7 @@ from .web_playlists import q_playlist, q_playlists, w_playlist
from .web_resource_sync import w_purge_missing, w_resource_sync_apply, w_resource_sync_scan
from .web_review import q_review, w_review_decision, w_review_genre
from .web_settings import q_settings, w_settings
+from .web_library_shortcuts import q_library_shortcuts, w_library_shortcuts
from .web_scraping import (
q_scraping, q_scraping_amane_bridge, w_scraping_amane_check, w_scraping_amane_rebuild,
w_scraping_check, w_scraping_cover, w_scraping_settings,
@@ -327,6 +328,7 @@ GET_HANDLERS = {
"/api/scraping/cover": lambda contract, args: contract.scraping_cover_job.snapshot() or {"status": "idle"},
"/api/scraping/amane-bridge": q_scraping_amane_bridge,
"/api/settings": q_settings,
+ "/api/library-shortcuts": q_library_shortcuts,
"/api/feeds": q_feeds,
"/api/feeds/check": q_feed_check,
"/api/feeds/discoveries": q_feed_discoveries,
@@ -427,6 +429,7 @@ POST_HANDLERS = {
"/api/review/decision": w_review_decision,
"/api/review/genre": w_review_genre,
"/api/settings": w_settings,
+ "/api/library-shortcuts": w_library_shortcuts,
"/api/entity-name": w_entity_name,
"/api/entity-alias": w_entity_alias,
}
diff --git a/src/peach/web_settings.py b/src/peach/web_settings.py
index 4f5dec723..703dc5ea7 100644
--- a/src/peach/web_settings.py
+++ b/src/peach/web_settings.py
@@ -225,9 +225,16 @@ def w_settings(contract: SettingsContract, body) -> dict:
merged[key] = body[key]
stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
with contract.write_transaction() as connection:
+ row = connection.execute("SELECT settings_json FROM profile WHERE id=?", (DEFAULT_PROFILE_ID,)).fetchone()
+ try:
+ current = json.loads(row[0] or "{}") if row else {}
+ except (TypeError, ValueError):
+ current = {}
+ current = current if isinstance(current, dict) else {}
+ current.update({key: merged[key] for key in body})
updated = connection.execute(
"UPDATE profile SET settings_json=?, updated_at=? WHERE id=?",
- (json.dumps(merged, ensure_ascii=False), stamp, DEFAULT_PROFILE_ID),
+ (json.dumps(current, ensure_ascii=False), stamp, DEFAULT_PROFILE_ID),
).rowcount
if not updated:
raise ValueError(f"profile {DEFAULT_PROFILE_ID} 不存在")
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 15b306147..946d2e076 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -1130,6 +1130,7 @@ class WebDataTests(unittest.TestCase):
"/api/suggest",
"/api/search-history", "/api/review", "/api/playlists", "/api/playlist",
"/api/post-setup-tutorial",
+ "/api/library-shortcuts",
"/api/follow", "/api/follow/credentials", "/api/follow/schedule",
"/api/follow/check", "/api/follow/resolve", "/api/follow/suggest",
"/api/taste/refresh",
@@ -1148,6 +1149,7 @@ class WebDataTests(unittest.TestCase):
"/api/scraping/amane-bridge/check", "/api/scraping/amane-bridge/rebuild",
"/api/activity", "/api/play", "/api/feedback", "/api/watch-later",
"/api/playlist",
+ "/api/library-shortcuts",
"/api/preference", "/api/quality-goal", "/api/item-tag", "/api/batch",
"/api/search-history", "/api/trash/empty",
"/api/review/decision", "/api/review/genre",
diff --git a/tests/test_web_library_shortcuts.py b/tests/test_web_library_shortcuts.py
new file mode 100644
index 000000000..2ecc60003
--- /dev/null
+++ b/tests/test_web_library_shortcuts.py
@@ -0,0 +1,91 @@
+"""收藏身份重定向、命名筛选与用户设置事务。"""
+import json
+import sqlite3
+import tempfile
+import unittest
+from contextlib import closing
+from pathlib import Path
+from unittest import mock
+
+from peach.web_contract import WebContract, dispatch_api_get, dispatch_api_post
+from peach.web_library_shortcuts import clean_href
+from peach import web_settings
+
+
+class LibraryShortcutsTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.path = Path(self.tmp.name).resolve() / "ledger.db"
+ with closing(sqlite3.connect(self.path)) as c, c:
+ c.executescript("""
+ CREATE TABLE profile(id TEXT PRIMARY KEY,settings_json TEXT,updated_at TEXT);
+ INSERT INTO profile VALUES('local-default','{"sidebarOrder":["tags"]}','');
+ CREATE TABLE entity(id INTEGER PRIMARY KEY,kind TEXT,canonical_name TEXT);
+ INSERT INTO entity VALUES(1,'studio','厂牌'),(2,'series','系列'),(3,'tag','剧情');
+ CREATE TABLE entity_redirect(old_id INTEGER,target_id INTEGER);
+ CREATE TABLE entity_alias(entity_id INTEGER,alias TEXT);
+ INSERT INTO entity_alias VALUES(3,'故事');
+ """)
+ self.contract = WebContract(self.path)
+
+ def read(self):
+ return dispatch_api_get(self.contract, "/api/library-shortcuts", {})
+
+ def write(self, **body):
+ return dispatch_api_post(self.contract, "/api/library-shortcuts", body)
+
+ def test_favorite_is_idempotent_and_reads_canonical_name(self):
+ for _ in range(2):
+ self.write(action="favorite", entity_id=1, on=True)
+ with closing(sqlite3.connect(self.path)) as c, c:
+ c.execute("UPDATE entity SET canonical_name='规范厂牌' WHERE id=1")
+ self.assertEqual([row['name'] for row in self.read()['favorites']], ['规范厂牌'])
+ self.assertEqual(self.write(action="favorite", entity_id=1, on=False)['favorites'], [])
+
+ def test_merge_collapses_favorites_and_cancel_accepts_old_id(self):
+ self.write(action="favorite", entity_id=1, on=True)
+ self.write(action="favorite", entity_id=2, on=True)
+ with closing(sqlite3.connect(self.path)) as c, c:
+ c.execute("DELETE FROM entity WHERE id=1")
+ c.execute("INSERT INTO entity_redirect VALUES(1,2)")
+ self.assertEqual([row['entity_id'] for row in self.read()['favorites']], [2])
+ self.assertEqual(self.write(action="favorite", entity_id=1, on=False)['favorites'], [])
+
+ def test_tag_alias_resolves_to_entity_and_can_be_cancelled(self):
+ result = self.write(action="favorite", kind="tag", name="故事", on=True)
+ self.assertEqual(result['favorites'][0]['entity_id'], 3)
+ self.assertEqual(result['favorites'][0]['name'], '剧情')
+ self.assertEqual(self.write(action="favorite", kind="tag", name="剧情", on=False)['favorites'], [])
+
+ def test_filters_roundtrip_preserves_empty_source_and_removal(self):
+ href = '/watch-later?loc=&q=ABW&tag=%E5%89%A7%E6%83%85&jav=1&sort=name&dir=asc&thumb=0'
+ result = self.write(action="save_filter", name="筛选", href=href)
+ saved = result['filters'][0]
+ self.assertEqual(saved['href'], href)
+ self.write(action="favorite", entity_id=1, on=True)
+ self.assertEqual(self.read()['filters'], [saved])
+ self.write(action="delete_filter", id=saved['id'])
+ self.assertEqual(self.read()['filters'], [])
+ with closing(sqlite3.connect(self.path)) as c, c:
+ settings = json.loads(c.execute("SELECT settings_json FROM profile").fetchone()[0])
+ self.assertEqual(settings['sidebarOrder'], ['tags'])
+
+ def test_bad_targets_are_rejected_without_writes(self):
+ for href in ('https://evil.example/', '//evil.example/', '/configuration', '/?token=x', '/?seed=123'):
+ with self.subTest(href=href), self.assertRaises(ValueError):
+ clean_href(href)
+ for entity_id in (True, -1, 99, '1'):
+ with self.subTest(entity_id=entity_id), self.assertRaises(ValueError):
+ self.write(action="favorite", entity_id=entity_id, on=True)
+ self.assertEqual(self.read(), {'favorites': [], 'filters': []})
+
+ def test_other_settings_keep_favorites_written_during_validation(self):
+ stored = web_settings._stored
+ def interleaved(contract):
+ value = stored(contract)
+ self.write(action="favorite", entity_id=1, on=True)
+ return value
+ with mock.patch.object(web_settings, '_stored', side_effect=interleaved):
+ web_settings.w_settings(self.contract, {'searchHistoryLimit': 10})
+ self.assertEqual([row['entity_id'] for row in self.read()['favorites']], [1])