Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(web): 建立 JAV 分区并统一资源查找

longmeidao4960d497ea6e
diff --git a/frontend/e2e/manage-header.test.ts b/frontend/e2e/manage-header.test.ts
index 1ff0f9b9f..de6c748ee 100644
--- a/frontend/e2e/manage-header.test.ts
+++ b/frontend/e2e/manage-header.test.ts
@@ -34,7 +34,7 @@ const HEADS = [
['/trash', '回收站', '回收站', false],
['/follow-manage', '关注管理', '', false],
['/activity', '活动', '', false],
- ['/configuration', '配置', '', true],
+ ['/configuration', '服务配置', '', true],
] as const;
const BLOCKS = '[data-manage-header] > :is([data-manage-bar], [data-manage-crumb], [data-manage-title], [data-manage-lede])';
diff --git a/frontend/e2e/smoke.test.ts b/frontend/e2e/smoke.test.ts
index 5365aae10..ead4d653f 100644
--- a/frontend/e2e/smoke.test.ts
+++ b/frontend/e2e/smoke.test.ts
@@ -41,6 +41,9 @@ const statsInventoryTab = (page: Page): Locator =>
page.locator('#stats').getByRole('tab', { name: /^馆藏视频/ });
const ROUTES: readonly Route[] = [
+ { path: '/jav', body: page => [page.getByRole('tab', { name: '我的馆藏', exact: true, selected: true })] },
+ { path: '/jav?tab=discover', body: page => [page.getByRole('tab', { name: '发现', exact: true, selected: true }), page.getByText('暂无匹配口味的新作', { exact: true })] },
+ { path: '/jav?tab=wants', body: page => [page.getByRole('tab', { name: '想要', exact: true, selected: true }), page.getByText('还没有想要的作品', { exact: true })] },
{ path: '/', body: (page) => [page.locator('#grid [data-media-card]').first()] },
{ path: '/performers', body: (page) => [heading(page, '#index', '艺人'), indexEntries(page)] },
{ path: '/creators', body: (page) => [heading(page, '#index', '卖家'), indexEntries(page)] },
diff --git a/frontend/e2e/want-resources.test.ts b/frontend/e2e/want-resources.test.ts
index 028ddfb13..9fbc531c8 100644
--- a/frontend/e2e/want-resources.test.ts
+++ b/frontend/e2e/want-resources.test.ts
@@ -9,7 +9,7 @@ describe('JAV 入库作品卡', () => {
after(async () => { await browser?.close(); });
for (const viewport of VIEWPORTS) {
it(`资源链接与操作完整可见(${viewport.name})`, { timeout: 60_000 }, async () => {
- const opened = await visit(browser, '/follow-manage', viewport);
+ const opened = await visit(browser, '/jav', viewport);
const page = opened.page;
try {
await settle(page);
@@ -39,7 +39,7 @@ describe('JAV 入库作品卡', () => {
} }); });
await page.route('**/api/downloads?*', route => route.fulfill({ json: { available: true,
providers: [{ key: '115', label: '115', configured: true, target: '/下载' }], tasks: [] } }));
- await page.getByRole('tab', { name: 'JAV 入库', exact: true }).click();
+ await page.getByRole('tab', { name: '想要', exact: true }).click();
await page.locator('[data-want-magnets]').scrollIntoViewIfNeeded();
await page.getByRole('heading', { name: '资源链接 · 8' }).waitFor();
await settle(page);
@@ -69,12 +69,12 @@ describe('JAV 入库作品卡', () => {
await page.waitForFunction(() => document.querySelectorAll('[data-resource-protocol]').length === 8 &&
!document.querySelector('details [inert=""]'));
assert.equal(await card.locator('[data-resource-protocol]:visible').count(), 8);
- await page.getByRole('tab', { name: '关注列表', exact: true }).click();
- await page.getByRole('tab', { name: 'JAV 入库', exact: true }).click();
+ await page.getByRole('tab', { name: '我的馆藏', exact: true }).click();
+ await page.getByRole('tab', { name: '想要', exact: true }).click();
await page.getByRole('heading', { name: '资源链接 · 8' }).waitFor();
assert.equal(resourceRequests, 1, '返回页面重复查询资源');
await page.reload();
- await page.getByRole('tab', { name: 'JAV 入库', exact: true }).click();
+ await page.getByRole('tab', { name: '想要', exact: true }).click();
await page.getByRole('heading', { name: '资源链接 · 8' }).waitFor();
assert.equal(resourceRequests, 1, '刷新页面未复用持久缓存');
assert.deepEqual(opened.problems, []);
diff --git a/frontend/src/application/index.js b/frontend/src/application/index.js
index 1dcd69fc8..36dc17c92 100644
--- a/frontend/src/application/index.js
+++ b/frontend/src/application/index.js
@@ -52,7 +52,7 @@ export function openFollowAuthorFromIndex(key){indexState.controller.openFollowA
export function openFollowTagFromIndex(tag){indexState.controller.openFollowTag(tag)}
export function installIndex16() {
-followState.FOLLOW_MANAGE_TABS = ['list','add','feeds','wants','source'];
+followState.FOLLOW_MANAGE_TABS = ['list','add','feeds'];
applicationEffects.listen(document, 'click', event=>{
if(event.target.closest?.('[data-empty-settings]')){openConfigurationSection('媒体');return}
const link=event.target.closest?.('a[href="/follow-manage?tab=add"]');
diff --git a/frontend/src/application/layout.js b/frontend/src/application/layout.js
index 4a5796a9e..0d191e02b 100644
--- a/frontend/src/application/layout.js
+++ b/frontend/src/application/layout.js
@@ -295,8 +295,8 @@ export function navOn(k){
const current=manageSection();
return !!current&&!preferencesState.appSettings.sidebarOrder.some(key=>layoutState.DIRECT_MANAGE_NAV[key]===current);
}
- // JAV 和竖屏不是路径,是内存里的筛选开关,所以这两条只能问 state。
- if(k==='jav')return javActive();
+ // JAV 分区及馆藏 JAV 筛选共用导航状态;竖屏由内存里的筛选开关判定。
+ if(k==='jav')return path==='/jav'||javActive();
if(k==='shorts')return state.orient==='竖屏';
// 首页只在真的停在首页列表上时亮:管理区、索引页、实体页都不算,
// 否则它会和当前所在的入口同时高亮。
@@ -311,7 +311,7 @@ export function navTo(k){
closeDrawerAfterNav(); // 点了就收起抽屉,且短暂禁止悬停把它立刻弹回
if(layoutState.DIRECT_MANAGE_NAV[k]){openManage(layoutState.DIRECT_MANAGE_NAV[k]);return}
if(k==='manage'){openManage();return}
- if(k==='jav'){toggleJavMode();return}
+ if(k==='jav'){navigationState.navigatePath('/jav');return}
if(k===''){goHome();return}
// 有自己路径的入口(追更、播放列表、沉浸模式、索引页)按路由元数据的 `nav` 找路径进。
const path=STATE_ROUTES[k]?null:navigationState.routePathOf('nav',k);
diff --git a/frontend/src/application/navigation-items.ts b/frontend/src/application/navigation-items.ts
index 472c546b0..02029b68a 100644
--- a/frontend/src/application/navigation-items.ts
+++ b/frontend/src/application/navigation-items.ts
@@ -28,7 +28,7 @@ export const MANAGE_SECTIONS = [
['follow', '关注管理', 'rss'],
['quality', '高清版', 'sparkles'],
['activity', '活动', 'history'],
- ['configuration', '配置', 'folder-cog'],
+ ['configuration', '服务配置', 'folder-cog'],
] as const satisfies readonly NavigationItem<ManagementKey>[];
export const MANAGE_MENU_SECTIONS: readonly ManagementKey[] = ['stats', 'taste', 'cleanup', 'follow', 'activity', 'configuration'];
diff --git a/frontend/src/board-skeleton.ts b/frontend/src/board-skeleton.ts
index 487e354db..07299608b 100644
--- a/frontend/src/board-skeleton.ts
+++ b/frontend/src/board-skeleton.ts
@@ -20,7 +20,7 @@ const block = (width: number, height: number, round = false) =>
const STAT = 'min-w-0 bg-background-secondary-default rounded-2xl shadow-card flex flex-col gap-3 px-6 py-5 max-sm:gap-2 max-sm:p-4';
const followReadings = () => `<div class="inline-grid w-full grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 xl:grid-cols-6">${['关注创作者', '启用来源', '检查失败', '未看更新', 'JAV 订阅', '未看新作'].map(term => `<div class="${STAT}"><span class="text-body-medium text-text-secondary">${term}</span><b class="text-title-1-medium tabular-nums text-text-primary">${text('3em')}</b></div>`).join('')}</div>`;
/** 页签与 React `follow-manage-page.tsx` 的 `TABS` 同名同序;选中的是地址栏 `?tab=` 那一枚,认不出时是第一枚。 */
-const FOLLOW_TABS = [['list', '关注列表'], ['add', '添加关注'], ['feeds', 'JAV 订阅源'], ['wants', 'JAV 入库'], ['source', '来源和凭证']] as const;
+const FOLLOW_TABS = [['list', '关注列表'], ['add', '添加关注'], ['feeds', 'JAV 订阅源']] as const;
const followTabKey = (tab = '') => (FOLLOW_TABS.some(([key]) => key === tab) ? tab : 'list');
const followTabs = (tab: string) => `<div data-section-nav data-section-items class="flex max-w-full flex-nowrap overflow-x-auto">${FOLLOW_TABS.map(([key, name]) => `<span class="whitespace-nowrap" aria-selected="${key === tab}">${name}</span>`).join('')}</div>`;
/** Board UI `Checkbox` 的未勾静止态;给了字就是「全选本页」那种带标签的一枚。 */
@@ -91,6 +91,8 @@ export function boardPageSkeleton(
let body = '';
if (path === '/stats') {
body = statsSkeleton();
+ } else if (path === '/jav') {
+ body = `<div class="peach-react"><div class="mx-auto flex w-full max-w-board flex-col gap-6"><div class="flex items-center justify-between gap-2"><h2 class="text-title-2-semibold text-text-primary">JAV</h2>${islandButton({ label: '查找资源', attrs: WAITING })}</div><div class="flex gap-4">${['我的馆藏', '发现', '想要'].map(label => `<span>${label}</span>`).join('')}</div><div class="ui-skeleton-lines">${line('100%')}</div><div class="inline-grid gap-5 sm:grid-cols-2 lg:grid-cols-3">${repeat(`<span class="skeleton aspect-card-cover rounded-2lg"></span>`, 6)}</div></div></div>`;
} else if (path === '/taste') {
body = tasteSkeleton();
} else if (path === '/follow-manage') {
diff --git a/frontend/src/history/route-meta.ts b/frontend/src/history/route-meta.ts
index b35dc1f6c..596b33cd0 100644
--- a/frontend/src/history/route-meta.ts
+++ b/frontend/src/history/route-meta.ts
@@ -23,6 +23,7 @@ export interface RouteMeta {
}
export const ROUTE_META: Readonly<Record<string, RouteMeta>> = {
+ '/jav': { nav: 'jav', title: 'JAV', refresh: 'reopen' },
'/stats': { section: 'stats', title: '统计' },
'/taste': { section: 'taste', title: '口味', refresh: 'reopen' },
'/review': { section: 'review', title: '人工复核', refresh: 'reopen' },
@@ -31,7 +32,7 @@ export const ROUTE_META: Readonly<Record<string, RouteMeta>> = {
'/quality-goals': { section: 'quality', title: '高清版', refresh: 'reopen' },
'/scraping': { section: 'cleanup', title: '来源和凭证', refresh: 'reopen' },
'/follow-manage': { section: 'follow', title: '关注管理', refresh: 'skip' },
- '/configuration': { section: 'configuration', title: '配置', refresh: 'reopen' },
+ '/configuration': { section: 'configuration', title: '服务配置', refresh: 'reopen' },
'/activity': { section: 'activity', title: '活动', refresh: 'reopen' },
'/diagnostics': { section: 'configuration', title: '系统诊断', refresh: 'reopen' },
// 旧直达地址,改写到数据管理页的锚点,没有自己的管理身份。
diff --git a/frontend/src/react/activity/cloud-download-dialog.tsx b/frontend/src/react/activity/cloud-download-dialog.tsx
index fc935ef98..3af4dc179 100644
--- a/frontend/src/react/activity/cloud-download-dialog.tsx
+++ b/frontend/src/react/activity/cloud-download-dialog.tsx
@@ -1,9 +1,5 @@
-/* 云下载弹层:在点它的那一页原地打开,搜索索引器或贴磁力,交给 115 或 PikPak 离线下载。
- *
- * 入口有两处:JAV 入库页(每条作品与页上那一颗)、高清版目标卡,都带得出番号。它们把番号、
- * 标题和来处(`prefill`)交进来,提交时一并记在任务上;提交过的任务在活动页「云下载」段看。
- *
- * 下载配置(`/api/downloads`)在弹层打开时才取,和活动页、入库页读同一个缓存键。 */
+/* 资源查找弹层:JAV、想要与高清版目标共用搜索、作品资料和下载提交。
+ * 下载配置在弹层打开时读取;已提交的任务在活动页查看。 */
import { useRef, useState, type FormEvent, type ReactNode } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Heading } from 'react-aria-components';
@@ -22,7 +18,8 @@ import { DOWNLOADS_KEY, DOWNLOADS_URL, downloadPollInterval, failureText } from
import { ResourceSearch } from './resource-search';
/** 入口带进来的上下文。`origin` 记在任务上,如 `asset:12`、`wishlist:5`。 */
-export interface DownloadPrefill { code?: string; title?: string; origin?: string; searchReason?: string }
+export interface DownloadPrefill { code?: string; title?: string; origin?: string; searchReason?: string;
+ cover?: string; performers?: string; release_date?: string; duration?: number | null; studio?: string }
const RECEIPTS: Partial<Record<DownloadSubmitResult['outcome'], string>> = {
submitted: '已提交离线下载,进度在活动页',
@@ -54,15 +51,12 @@ function Body({ prefill, close, receipt, provider }: {
refetchInterval: (state) => downloadPollInterval(state.state.data),
});
const data = query.data;
- const configured = data?.providers.filter((row) => row.configured) ?? [];
- const subject = [prefill.code, prefill.title].filter(Boolean).join(' ');
const header = (
<div className="flex flex-col gap-1 px-5 pt-5">
- <Heading slot="title" className="text-title-2-semibold text-text-primary">云下载</Heading>
- {subject ? <p className="min-w-0 truncate text-body-2-regular text-text-secondary">{subject}</p> : null}
+ <Heading slot="title" className="text-title-2-semibold text-text-primary">查找资源</Heading>
</div>
);
- if (data?.available && configured.length) {
+ if (data) {
return <SubmitForm header={header} snapshot={data} prefill={prefill} close={close} receipt={receipt} provider={provider} />;
}
return (
@@ -70,10 +64,6 @@ function Body({ prefill, close, receipt, provider }: {
{header}
<div className="flex min-h-0 flex-col gap-4 overflow-y-auto p-5">
{query.error ? <Note tone="error">{errorMessage(query.error)}</Note> : null}
- {data && !data.available ? <Note tone="neutral">云下载只在账本写入端可用。</Note> : null}
- {data?.available && !configured.length
- ? <Note tone="neutral">先在配置页「下载」分组登录 PikPak,或填好 CloudDrive2 的地址与令牌。</Note>
- : null}
</div>
<div className="flex justify-end p-3">
<Button variant="secondary" onClick={close}>关闭</Button>
@@ -88,12 +78,14 @@ function SubmitForm({ header, snapshot, prefill, close, receipt, provider: prefe
}) {
const client = useQueryClient();
const configured = snapshot.providers.filter((row) => row.configured);
- const first = configured.find((row) => row.key === preferred) ?? configured[0]!;
- const [provider, setProvider] = useState<DownloadProviderKey>(first.key);
+ const first = configured.find((row) => row.key === preferred) ?? configured[0];
+ const [provider, setProvider] = useState<DownloadProviderKey>(first?.key || 'pikpak');
const [magnet, setMagnet] = useState('');
const [code, setCode] = useState(prefill.code ?? '');
- const [target, setTarget] = useState(first.target);
+ const [target, setTarget] = useState(first?.target || '');
+ const [work, setWork] = useState<DownloadPrefill | null>(prefill.code ? prefill : null);
const [failure, setFailure] = useState('');
+ const usable = snapshot.available && configured.some(row => row.key === provider);
const action = useAction();
const input = useRef<HTMLInputElement>(null);
@@ -104,8 +96,8 @@ function SubmitForm({ header, snapshot, prefill, close, receipt, provider: prefe
const submit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
- if (!magnet.trim()) return;
- const body = { magnet, provider, target, code, title: prefill.title, origin: prefill.origin };
+ if (!magnet.trim() || !usable) return;
+ const body = { magnet, provider, target, code, title: work?.title, origin: work?.origin };
setFailure('');
void action.run('submit', (signal) => apiSend<DownloadSubmitResult>(DOWNLOADS_URL, body, 'POST', signal),
(next) => {
@@ -119,32 +111,47 @@ function SubmitForm({ header, snapshot, prefill, close, receipt, provider: prefe
};
return (
- <form aria-label="提交磁力" noValidate onSubmit={submit} className="flex min-h-0 flex-col">
+ <form aria-label="提交下载" noValidate onSubmit={submit} className="flex min-h-0 flex-col">
{header}
<div className="flex min-h-0 flex-col gap-4 overflow-y-auto p-5">
- <ResourceSearch initialCode={prefill.code ?? ''} reason={prefill.searchReason} choose={(uri, selectedCode) => {
+ <ResourceSearch initialCode={prefill.code ?? ''} reason={prefill.searchReason} onSearch={requested => {
+ if (requested !== work?.code) { setWork(requested === prefill.code ? prefill : null); setCode(requested); setMagnet('') }
+ }} onWork={next => setWork(current => next ? { ...current, ...next, origin: current && current.code === next.code ? current.origin : next.origin }
+ : current?.code === prefill.code ? current : null)} choose={(uri, selectedCode) => {
setMagnet(uri); setCode(selectedCode); input.current?.focus();
}} />
+ <div className="flex min-w-0 items-start gap-4" data-resource-work="">
+ {work?.cover ? <img src={work.cover} alt="" referrerPolicy="no-referrer" onError={event => event.currentTarget.remove()}
+ className="w-card-cover shrink-0 rounded-2lg" /> : null}
+ <div className="flex min-w-0 flex-col gap-2">
+ <p className="break-words text-body-medium text-text-primary">{work ? [work.code, work.title].filter(Boolean).join(' · ') : '作品资料未取得'}</p>
+ {work ? <Help>{[work.performers, work.studio, work.release_date, work.duration ? `${Math.round(work.duration / 60)} 分钟` : ''].filter(Boolean).join(' · ')}</Help> : null}
+ </div>
+ </div>
<Input ref={input} label="磁力链接" placeholder="magnet:?xt=urn:btih:…" autoComplete="off" maxLength={4000}
value={magnet} onChange={setMagnet} />
<div className="flex flex-col gap-1">
<FieldLabel>下载到</FieldLabel>
- <Select aria-label="下载到" selectedKey={provider}
+ <Select aria-label="下载到" selectedKey={provider} isDisabled={!configured.length}
onSelectionChange={(key) => { if (key !== null) choose(String(key) as DownloadProviderKey) }}>
{configured.map((row) => <SelectItem key={row.key} id={row.key}>{row.label}</SelectItem>)}
</Select>
{provider === '115' ? <Help>每提交一次扣一条离线配额,重新提交也算。</Help> : null}
</div>
+ {!snapshot.available ? <Note tone="neutral">云下载只在账本写入端可用。</Note> : null}
+ {!configured.length ? <Note tone="neutral">尚未配置下载渠道。<a href={'/configuration?section=' + encodeURIComponent('下载渠道')}>下载渠道设置</a></Note> : null}
<Input label="目标目录" placeholder="/云下载" autoComplete="off" maxLength={300}
value={target} onChange={setTarget} />
{/* 带着番号进来时它和搜索框是同一个值,选中候选也会跟着换,不再单列一格。 */}
{prefill.code ? null
- : <Input label="番号" placeholder="可不填" autoComplete="off" maxLength={60} value={code} onChange={setCode} />}
+ : <Input label="番号" placeholder="可不填" autoComplete="off" maxLength={60} value={code} onChange={value => {
+ setCode(value); if (value !== work?.code) setWork(null);
+ }} />}
{failure || action.error ? <ErrorText>{failure || action.error}</ErrorText> : null}
</div>
<div className="flex justify-between gap-4 p-3">
<Button variant="secondary" onClick={close}>取消</Button>
- <Button type="submit" disabled={!magnet.trim()} {...busyProps(action.busy === 'submit')}>提交离线下载</Button>
+ <Button type="submit" disabled={!magnet.trim() || !usable} {...busyProps(action.busy === 'submit')}>提交下载</Button>
</div>
</form>
);
diff --git a/frontend/src/react/activity/resource-search.tsx b/frontend/src/react/activity/resource-search.tsx
index eccd0c20b..1362700f3 100644
--- a/frontend/src/react/activity/resource-search.tsx
+++ b/frontend/src/react/activity/resource-search.tsx
@@ -1,5 +1,5 @@
/* 搜索只选择候选;真正提交由云下载表单确认。 */
-import { useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { RiSearchLine } from '@remixicon/react';
import { spinnerHtml } from '@peach/legacy/ui';
import { Button } from '@/components/base/buttons/button';
@@ -8,6 +8,9 @@ import { Select, SelectItem } from '@/components/base/select/select';
import { apiGet } from '../../api';
import { ErrorText, FieldLabel, Help } from '../settings/section';
import { useAction } from '../settings/use-action';
+import { coverUrl } from '@peach/card-art';
+import type { MediaPage } from '../catalog-grid/types';
+import type { DownloadPrefill } from './cloud-download-dialog';
interface Candidate {
id: string; uri: string; name: string; size: number; seeders: number; origins: string[];
@@ -25,8 +28,9 @@ function preferredGoal(reason: string | undefined): string {
return 'quality';
}
-export function ResourceSearch({ initialCode, reason, choose }: {
+export function ResourceSearch({ initialCode, reason, choose, onSearch, onWork }: {
initialCode: string; reason?: string; choose(uri: string, code: string): void;
+ onSearch?(code: string): void; onWork?(work: DownloadPrefill | null): void;
}) {
const [code, setCode] = useState(initialCode);
const [goal, setGoal] = useState(() => preferredGoal(reason));
@@ -36,6 +40,8 @@ export function ResourceSearch({ initialCode, reason, choose }: {
const [searched, setSearched] = useState('');
const [selected, setSelected] = useState('');
const action = useAction();
+ const metadataRequest = useRef<AbortController | null>(null);
+ useEffect(() => () => metadataRequest.current?.abort(), []);
const search = () => {
if (!code.trim() || action.busy) return;
const query = new URLSearchParams({ code: code.trim(), goal });
@@ -44,15 +50,29 @@ export function ResourceSearch({ initialCode, reason, choose }: {
setResult(null);
setSelected('');
const requested = code.trim();
+ onSearch?.(requested);
+ metadataRequest.current?.abort();
void action.run('search', (signal) => apiGet<Result>(`/api/resources/search?${query}`, signal), (next) => {
setResult(next);
setSearched(requested);
});
+ if (onWork) {
+ const controller = new AbortController();
+ metadataRequest.current = controller;
+ const key = (value: string) => value.toUpperCase().replace(/[^A-Z0-9]/g, '');
+ void apiGet<MediaPage>(`/api/items?jav=1&q=${encodeURIComponent(requested)}&limit=10`, controller.signal).then(page => {
+ if (controller.signal.aborted) return;
+ const item = (page.items || []).find(row => row.code && key(row.code) === key(requested));
+ onWork(item ? { code: item.code, title: String(item.catalog_title || item.name || ''), performers: item.performers?.join('、'),
+ release_date: String(item.release_date || ''), duration: item.duration, studio: item.studio,
+ cover: item.has_cover ? coverUrl(item, true) : '', origin: `asset:${item.id}` } : null);
+ }, () => { if (!controller.signal.aborted) onWork(null) });
+ }
};
return (
- <section aria-label="资源搜索" aria-busy={Boolean(action.busy)} className="flex min-w-0 flex-col gap-4">
+ <section aria-label="查找资源" aria-busy={Boolean(action.busy)} className="flex min-w-0 flex-col gap-4">
{reason ? <Help>版本目标:{reason}。可在下方调整搜索优先项;完整度与水印需要逐条复核。</Help> : null}
- <Input label="搜索资源" value={code} maxLength={80} placeholder="输入番号,按回车搜索" enterKeyHint="search"
+ <Input label="按番号查找资源" value={code} maxLength={80} placeholder="输入番号,按回车搜索" enterKeyHint="search"
leadingIcon={action.busy ? SearchSpinner : RiSearchLine}
isReadOnly={Boolean(action.busy)} aria-busy={Boolean(action.busy)} onChange={setCode} onKeyDown={(event) => {
if (event.key === 'Enter' && !event.nativeEvent.isComposing) { event.preventDefault(); search() }
@@ -77,7 +97,7 @@ export function ResourceSearch({ initialCode, reason, choose }: {
{result?.items.length ? <ul className="flex min-w-0 flex-col gap-4">
{result.items.map((item) => <li key={item.id} className="flex min-w-0 flex-col gap-2 border-t border-separator-border pt-4">
<p className="break-words text-body-2-medium text-text-primary">{item.name}</p>
- <Help>{[`${(item.size / 1024 ** 3).toFixed(2)} GiB`, `${item.seeders} 个做种`,
+ <Help>{[item.size > 0 ? `${(item.size / 1024 ** 3).toFixed(2)} GiB` : '体积未取得', item.seeders >= 0 ? `${item.seeders} 个做种` : '做种未取得',
item.resolution ? `${item.resolution}p` : '', item.codec, item.chinese ? '中字' : '',
item.uncensored ? '无码' : '', item.origins.join('、')].filter(Boolean).join(' · ')}</Help>
<div><Button type="button" variant="secondary" onClick={() => {
diff --git a/frontend/src/react/bundle.d.ts b/frontend/src/react/bundle.d.ts
index 0c340c4e3..9bb33bb9f 100644
--- a/frontend/src/react/bundle.d.ts
+++ b/frontend/src/react/bundle.d.ts
@@ -237,6 +237,7 @@ export interface ConfigurationFact {
}
export interface ConfigurationData {
+ ledger_read_only?: boolean;
startup?: StartupState;
uninstall?: UninstallState;
peach_proxy?: PeachProxyState;
@@ -282,8 +283,8 @@ export interface ConfigurationPanel {
active: boolean;
}
-/** 配置页的一个分组(「通用」「媒体」「下载」「网络与访问」「维护」)。
- * 重开教程那一半只归「维护」,别的分组不必接它。`panel` 只在配置页里给,单独挂一组时没有。 */
+/** 服务配置的分组:媒体库与入库、来源与订阅、下载渠道、网络与访问、应用与维护。
+ * `panel` 只在配置页里给,单独挂一组时没有。 */
export interface ConfigurationGroupProps extends Pick<ConfigurationProps, 'receipt'> {
data: ConfigurationData;
panel?: ConfigurationPanel;
@@ -339,7 +340,7 @@ export interface ScrapingProps {
* 走;`pageSize`/`layout` 是这台浏览器的习惯,跟着 `appSettings` 走。两组都由壳持有存储、
* React 持有实时状态,各只有一份。 */
export interface FollowManageProps {
- /** 地址栏此刻带着的页签(`list`/`add`/`feeds`/`wants`/`source`)。 */
+ /** 地址栏此刻带着的页签(`list`/`add`/`feeds`)。 */
tab: string;
page: number;
sort: string;
@@ -355,6 +356,7 @@ export interface FollowManageProps {
toast(message: string): void;
/** 去「看更新」那一页(`/follow`)。整页换成哪一屏仍归遗留壳。 */
openFollow(): void;
+ openServiceConfiguration(): void;
/** 账本只读:这台机器只能浏览,写操作全部不给点。 */
readOnly: boolean;
readOnlyMessage: string;
diff --git a/frontend/src/react/follow-manage/follow-manage-page.tsx b/frontend/src/react/follow-manage/follow-manage-page.tsx
index 07ab80721..8bdb00326 100644
--- a/frontend/src/react/follow-manage/follow-manage-page.tsx
+++ b/frontend/src/react/follow-manage/follow-manage-page.tsx
@@ -1,8 +1,6 @@
-/* 关注管理页:加来源、检查更新、移除来源、管订阅源、管想要清单、看凭据状态。
+/* 关注管理页:加来源、检查更新、移除来源与管理 JAV 订阅源。
*
- * 五栏是五件事,所以整块切换而不是一屏铺开:看的那一页(`/follow`)不联网,联网只发生
- * 在这里点「检查更新」的那一刻。「JAV 入库」排在订阅源后面:想要的作品多半是从 Feed 新作和关注
- * 条目上点进来的,两处的来源都在这一页管。
+ * 来源凭据由服务配置管理,想要清单位于 JAV 分区。
*
* 地址栏与个人偏好各管各的(ADR-0031「迁移桥接」):
* - `tab`、`page`、`sort`、`dir` 在地址栏上。判据是「外面链接得过来吗」——把一条关注列表
@@ -28,18 +26,17 @@ import { Page } from '../components/page';
import { STAT_STRIP_SIX } from '../components/stat-card';
import { AddSource } from './add-source';
import { AliasManager } from './alias-manager';
-import { Credentials } from './credentials';
+import { Button } from '@/components/base/buttons/button';
import { FeedSources } from './feed-sources';
import {
credentialDone, DEFAULT_SORT, FEEDS_KEY, fetchCredentials, fetchFeeds, fetchFollow, FOLLOW_CREDENTIALS_KEY,
FOLLOW_MANAGE_KEY, groupByAuthor, isBroken, isLayout, keepSelected, pageSizeOf,
SORT_DEFAULT_DIR, type CredentialData, type FollowData, type Layout, type SortDir, type SortKey,
} from './follow-manage';
-import { WantList } from '../wants/want-list';
import { SourceList } from './source-list';
const TABS = [
- ['list', '关注列表'], ['add', '添加关注'], ['feeds', 'JAV 订阅源'], ['wants', 'JAV 入库'], ['source', '来源和凭证'],
+ ['list', '关注列表'], ['add', '添加关注'], ['feeds', 'JAV 订阅源'],
] as const;
type TabKey = (typeof TABS)[number][0];
@@ -62,7 +59,7 @@ function Reading({ term, figure, unit }: { term: string; figure: number; unit: s
export function FollowManagePage(props: FollowManageProps) {
const {
- route, savePreference, toast, openFollow, readOnly, readOnlyMessage, writerUrl,
+ route, savePreference, toast, openFollow, openServiceConfiguration, readOnly, readOnlyMessage, writerUrl,
} = props;
const [tab, setTab] = useState<TabKey>(isTab(props.tab) ? props.tab : 'list');
const [page, setPage] = useState(Math.max(1, Math.floor(props.page) || 1));
@@ -148,9 +145,7 @@ export function FollowManagePage(props: FollowManageProps) {
<TabList aria-label="关注管理区域" data-section-nav data-section-items
className="flex max-w-full flex-nowrap overflow-x-auto">
{TABS.map(([key, name]) => (
- <Tab key={key} id={key} className="cursor-pointer whitespace-nowrap">
- {key === 'source' && pending ? `${name}(${pending})` : name}
- </Tab>
+ <Tab key={key} id={key} className="cursor-pointer whitespace-nowrap">{name}</Tab>
))}
</TabList>
@@ -182,7 +177,7 @@ export function FollowManagePage(props: FollowManageProps) {
<TabPanel id="add" className="flex flex-col gap-8">
<AddSource data={data} credentials={creds} readOnly={readOnly} toast={toast}
- openCredentials={() => { setTab('source'); go({ tab: 'source' }) }} />
+ openCredentials={openServiceConfiguration} />
<AliasManager groups={data.author_aliases || []} readOnly={readOnly} toast={toast}
suggestions={data.alias_suggestions || []} sources={data.sources} />
</TabPanel>
@@ -191,14 +186,8 @@ export function FollowManagePage(props: FollowManageProps) {
<FeedSources readOnly={readOnly} toast={toast} />
</TabPanel>
- <TabPanel id="wants" className="flex flex-col gap-4">
- <WantList readOnly={readOnly} toast={toast} />
- </TabPanel>
-
- <TabPanel id="source" className="flex flex-col gap-4">
- <Credentials data={creds} readOnly={readOnly} toast={toast} />
- </TabPanel>
</Tabs>
+ <div><Button variant="secondary" onClick={openServiceConfiguration}>来源与订阅设置{pending ? `(${pending})` : ''}</Button></div>
</Page>
);
}
diff --git a/frontend/src/react/follow-manage/manage-route.ts b/frontend/src/react/follow-manage/manage-route.ts
index bf7213f5c..28777d52b 100644
--- a/frontend/src/react/follow-manage/manage-route.ts
+++ b/frontend/src/react/follow-manage/manage-route.ts
@@ -1,4 +1,4 @@
-export const FOLLOW_MANAGE_TABS = ['list', 'add', 'feeds', 'wants', 'source'] as const;
+export const FOLLOW_MANAGE_TABS = ['list', 'add', 'feeds'] as const;
export type FollowManageTab = (typeof FOLLOW_MANAGE_TABS)[number];
export interface FollowManageRoute { tab: FollowManageTab; page: number; sort: string; dir: string }
@@ -19,5 +19,7 @@ export function followManagePath(params: FollowManageRoute): string {
}
export function followManageEntry(search: string, workspace?: FollowManageTab): string {
+ if (!workspace && new URLSearchParams(search).get('tab') === 'wants') return '/jav?tab=wants';
+ if (!workspace && new URLSearchParams(search).get('tab') === 'source') return '/configuration?section=' + encodeURIComponent('来源与订阅');
return followManagePath({ tab: workspace || followManageParams(search).tab, page: 1, sort: '', dir: '' });
}
diff --git a/frontend/src/react/jav/jav-page.tsx b/frontend/src/react/jav/jav-page.tsx
new file mode 100644
index 000000000..1716c5205
--- /dev/null
+++ b/frontend/src/react/jav/jav-page.tsx
@@ -0,0 +1,99 @@
+import { useState, type FormEvent } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import { RiSearchLine, RiCompassLine } from '@remixicon/react';
+import { Tab, TabList, TabPanel, Tabs } from 'react-aria-components';
+import { Button, ButtonLink } from '@/components/base/buttons/button';
+import { Input } from '@/components/base/input/input';
+import { appSettingsStore } from '@peach/appearance';
+import { coverUrl } from '@peach/card-art';
+import { pageSkeletonHtml } from '../../management-placeholder';
+import { emptyStateHtml } from '../../ui-kit';
+import { apiGet, errorMessage } from '../../api';
+import { CatalogGridPage } from '../catalog-grid/catalog-grid-page';
+import type { MediaCardActions, MediaCardHelpers } from '../catalog-grid/types';
+import { CloudDownloadDialog, type DownloadPrefill } from '../activity/cloud-download-dialog';
+import { Page } from '../components/page';
+import { Note } from '../components/note';
+import { EmptyState } from '../components/empty-state';
+import { fetchTaste, tasteKey } from '../taste/taste';
+import { WantList } from '../wants/want-list';
+import { addWant, invalidateWants } from '../wants/wants';
+import { busyProps, useAction } from '../settings/use-action';
+import { JAV_TABS, rankedDiscoveries, type Discovery } from './jav';
+
+export function JavPage({ tab, readOnly, navigate, receipt, grid }: {
+ tab: string; readOnly: boolean; navigate(path: string): void; receipt(message: string): void;
+ grid: { helpers: MediaCardHelpers; actions: MediaCardActions };
+}) {
+ const [download, setDownload] = useState<DownloadPrefill | null>(null);
+ const [text, setText] = useState('');
+ const [query, setQuery] = useState('');
+ const settings = appSettingsStore().value;
+ const search = (event: FormEvent) => { event.preventDefault(); setQuery(text.trim()) };
+ return <Page>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h2 className="text-title-2-semibold text-text-primary">JAV</h2>
+ <Button variant={tab === 'wants' ? 'secondary' : 'primary'} onClick={() => setDownload({})}>查找资源</Button>
+ </div>
+ <Tabs selectedKey={tab} onSelectionChange={key => navigate(`/jav?tab=${key}`)} className="flex flex-col gap-6">
+ <TabList aria-label="JAV 分区" data-section-nav data-section-items className="flex max-w-full overflow-x-auto">
+ {JAV_TABS.map(([key, label]) => <Tab key={key} id={key} className="cursor-pointer whitespace-nowrap">{label}</Tab>)}
+ </TabList>
+ <form aria-label="搜索作品" onSubmit={search}>
+ <Input aria-label="搜索作品" placeholder="搜索番号、女优或标题" leadingIcon={RiSearchLine}
+ value={text} onChange={setText} enterKeyHint="search" />
+ </form>
+ <TabPanel id="library" className="flex min-w-0 flex-col gap-4">
+ <CatalogGridPage mode="catalog" filters={{ jav: '1', q: query, sort: settings.defaultSort, dir: settings.defaultSortDirection || '' }}
+ helpers={grid.helpers} actions={grid.actions} layout={{ active: true, size: settings.javLayout === 'small' ? 'small' : 'big', portrait: false, javImage: settings.javImage }}
+ selectMode={false} selected={new Set()} seekSeconds={0} revision={0}
+ skeletonHtml={() => pageSkeletonHtml('正在读取馆藏', { cards: true, count: 6 })} wireDrag={() => {}}
+ excludeVertical emptyHtml={() => emptyStateHtml('search', '没有符合条件的作品', '试试其他番号、女优或标题。')} />
+ </TabPanel>
+ <TabPanel id="discover" className="flex min-w-0 flex-col gap-4">
+ <Discover readOnly={readOnly} receipt={receipt} resource={setDownload} query={query} />
+ </TabPanel>
+ <TabPanel id="wants"><WantList readOnly={readOnly} toast={receipt} query={query} /></TabPanel>
+ </Tabs>
+ <CloudDownloadDialog prefill={download} close={() => setDownload(null)} receipt={receipt} />
+ </Page>;
+}
+
+function Discover({ readOnly, receipt, resource, query }: { readOnly: boolean; receipt(message: string): void; resource(work: DownloadPrefill): void; query: string }) {
+ const taste = useQuery({ queryKey: tasteKey('all'), queryFn: ({ signal }) => fetchTaste('all', signal) });
+ const discoveries = useQuery({ queryKey: ['jav-discoveries'], queryFn: ({ signal }) => apiGet<{ items: Discovery[] }>('/api/feeds/discoveries?limit=100', signal) });
+ const action = useAction();
+ const items = rankedDiscoveries(discoveries.data?.items || [], taste.data || {}).filter(item =>
+ !query || [item.code, item.title, item.performers].join(' ').toLocaleLowerCase().includes(query.toLocaleLowerCase()));
+ const waiting = taste.isPending || discoveries.isPending;
+ return <section aria-label="为你推荐" aria-busy={waiting} className="flex min-w-0 flex-col gap-4">
+ {waiting ? <div role="status" aria-label="正在读取推荐" dangerouslySetInnerHTML={{ __html: pageSkeletonHtml('正在读取推荐', { cards: true, count: 6 }) }} /> : null}
+ {taste.error || discoveries.error ? <Note tone="error" title="推荐未取得">{errorMessage(taste.error || discoveries.error)}</Note> : null}
+ {!waiting && !taste.error && !discoveries.error && !items.length ? <EmptyState shell="plain" icon={RiCompassLine} title="暂无匹配口味的新作"
+ actions={<><ButtonLink href="/taste" variant="secondary">查看口味</ButtonLink><ButtonLink href="/follow-manage?tab=feeds" variant="secondary">管理订阅</ButtonLink></>}>
+ 先读取浏览记录,或关注女优的新作。
+ </EmptyState> : null}
+ {action.error ? <Note tone="error">{action.error}</Note> : null}
+ <div className="inline-grid min-w-0 gap-5 sm:grid-cols-2 lg:grid-cols-3">
+ {items.map(item => <article key={item.id} className="flex min-w-0 flex-col gap-3">
+ <div className="relative inline-grid aspect-card-cover place-items-center overflow-hidden rounded-2lg bg-background-tertiary-default">
+ <span className="text-text-secondary">无封面</span>
+ {item.has_cover || item.cover_url ? <img alt="" src={item.has_cover ? coverUrl(item, true) : item.cover_url}
+ referrerPolicy="no-referrer" onError={event => event.currentTarget.remove()} className="absolute inset-0 size-full object-cover" /> : null}
+ </div>
+ <h3 className="break-words text-body-medium text-text-primary">{item.code} · {item.title || '标题未取得'}</h3>
+ <p className="break-words text-body-2-regular text-text-secondary">{[item.performers, item.release_date].filter(Boolean).join(' · ')}</p>
+ <p className="text-body-2-regular text-text-secondary">你常看的女优:{item.matches.join('、')}</p>
+ <div className="flex flex-wrap gap-2">
+ <Button variant="secondary" onClick={() => resource({ ...item, cover: item.has_cover ? coverUrl(item, true) : item.cover_url, origin: `feed:${item.id}` })}>查找资源</Button>
+ <Button variant="secondary" disabled={readOnly || item.wanted} {...busyProps(action.busy === String(item.id))} onClick={() => {
+ void action.run(String(item.id), signal => addWant({ code: item.code }, signal), () => {
+ receipt('已加入想要'); void invalidateWants(); void discoveries.refetch();
+ });
+ }}>{item.wanted ? '已加入想要' : '想要'}</Button>
+ {item.link ? <ButtonLink variant="secondary" href={item.link} target="_blank" rel="noopener noreferrer">作品来源</ButtonLink> : null}
+ </div>
+ </article>)}
+ </div>
+ </section>;
+}
diff --git a/frontend/src/react/jav/jav.ts b/frontend/src/react/jav/jav.ts
new file mode 100644
index 000000000..57dca0159
--- /dev/null
+++ b/frontend/src/react/jav/jav.ts
@@ -0,0 +1,41 @@
+import type { TasteData } from '../taste/taste';
+import { fetchTaste, tasteKey } from '../taste/taste';
+import { appSettingsStore } from '@peach/appearance';
+import { apiGet } from '../../api';
+import { queryClient } from '../query';
+import { catalogKey, catalogParams, fetchCatalogPage, nextOffset } from '../catalog-grid/catalog-grid';
+import { fetchWants, WANTS_KEY } from '../wants/wants';
+
+export const JAV_TABS = [['library', '我的馆藏'], ['discover', '发现'], ['wants', '想要']] as const;
+export const javTab = (value: string | null) => JAV_TABS.some(([key]) => key === value) ? value! : 'library';
+export interface Discovery {
+ id: number; code: string; title: string; performers: string; release_date: string;
+ studio: string; link: string; cover_url: string; has_cover: boolean; wanted: boolean;
+}
+
+export async function prefetchJav(tab: string, signal: AbortSignal) {
+ if (tab === 'wants') {
+ await queryClient.fetchQuery({ queryKey: WANTS_KEY, queryFn: () => fetchWants(signal) }); return;
+ }
+ if (tab === 'discover') {
+ await Promise.all([
+ queryClient.fetchQuery({ queryKey: tasteKey('all'), queryFn: () => fetchTaste('all', signal) }),
+ queryClient.fetchQuery({ queryKey: ['jav-discoveries'], queryFn: () => apiGet<{ items: Discovery[] }>('/api/feeds/discoveries?limit=100', signal) }),
+ ]); return;
+ }
+ const settings = appSettingsStore().value;
+ const params = catalogParams({ jav: '1', q: '', sort: settings.defaultSort, dir: settings.defaultSortDirection || '' }, true);
+ await queryClient.fetchInfiniteQuery({ queryKey: catalogKey(params, 0), initialPageParam: 0,
+ queryFn: ({ pageParam }) => fetchCatalogPage(params, pageParam, 60, false, signal), getNextPageParam: nextOffset(60) });
+}
+
+/** 推荐只来自作品的真实出演者与口味榜单中的同名信号。 */
+export function rankedDiscoveries(items: Discovery[], taste: TasteData) {
+ const signals = [...(taste.rankings?.peach_performers || []), ...(taste.rankings?.browser_creators || [])];
+ return items.map(item => {
+ const names = (item.performers || '').split(/[,,、;/]/).map(name => name.trim()).filter(Boolean);
+ const matches = signals.filter(signal => names.includes(signal.name));
+ return { ...item, matches: [...new Set(matches.map(signal => signal.name))],
+ score: matches.reduce((sum, signal) => sum + (signal.score || signal.visits || signal.web_visits || 1), 0) };
+ }).filter(item => item.matches.length).sort((a, b) => b.score - a.score || (b.release_date || '').localeCompare(a.release_date || ''));
+}
diff --git a/frontend/src/react/quality-goals/quality-goals-page.tsx b/frontend/src/react/quality-goals/quality-goals-page.tsx
index dd848eb9d..124ff04be 100644
--- a/frontend/src/react/quality-goals/quality-goals-page.tsx
+++ b/frontend/src/react/quality-goals/quality-goals-page.tsx
@@ -69,7 +69,8 @@ function GoalCard({ item, openItem, searchResources, javTitleHtml, javDisplayNam
<footer className="flex flex-wrap justify-end gap-2">
{item.code ? <Button variant="secondary" size="small" onClick={() => searchResources({
code: item.code!, title: javDisplayName(item), origin: `asset:${item.id}`, searchReason: item.reason || '',
- })}>搜索资源</Button> : null}
+ duration: item.duration, cover: previewUrl(item),
+ })}>查找资源</Button> : null}
<Button variant="secondary" size="small" onClick={open}>查看版本</Button>
</footer>
</li>
diff --git a/frontend/src/react/router/managed-routes.tsx b/frontend/src/react/router/managed-routes.tsx
index 3c8e48415..37b97c08e 100644
--- a/frontend/src/react/router/managed-routes.tsx
+++ b/frontend/src/react/router/managed-routes.tsx
@@ -41,6 +41,8 @@ import { ImmerseSurface } from '../immerse/immerse-island';
import { prefetchIndex } from '../index/index-data';
import { IndexPage } from '../index/index-page';
import { JunkQueuePage } from '../junk-queue/junk-queue-page';
+import { JavPage } from '../jav/jav-page';
+import { prefetchJav } from '../jav/jav';
import { prefetchLibraryProcessing } from '../library-processing/library-processing';
import { LibraryProcessingCard } from '../library-processing/library-processing-card';
import { LibraryProcessingNotice } from '../library-processing/library-processing-notice';
@@ -103,6 +105,11 @@ function openCleanupSection(section: DataCleanupSection, actions: ShellActions,
/* 第一帧在宿主放进 `#stats` 的同一个任务里同步画完(`router.tsx` 的 `ManagedSurface`):壳画完这一页
* 紧接着就读它画出来的结构(配置页按地址里的 `#peachProxy` 滚过去,那一刻选中的页签已经是「网络与访问」)。 */
export const MANAGED_ROUTES: ManagedRouteTable = {
+ '/jav': {
+ element: <ManagedMatch path="/jav" />,
+ prefetch: (open, signal) => prefetchJav(open.tab, signal),
+ page: (open, actions) => <JavPage {...open} navigate={actions.navigate} receipt={message => actions.receipt(message)} grid={actions.grid} />,
+ },
'/stats': {
element: <ManagedMatch path="/stats" />,
prefetch: (_open, signal) => prefetchStats(signal),
@@ -189,7 +196,8 @@ export const MANAGED_ROUTES: ManagedRouteTable = {
prefetch: (open, signal) => prefetchFollowManage(signal, open.tab),
page: (open, actions) => (
<FollowManagePage {...open} route={actions.routeFollowManage} savePreference={actions.saveFollowPreference}
- toast={(message) => actions.receipt(message)} openFollow={actions.openFollow} />
+ toast={(message) => actions.receipt(message)} openFollow={actions.openFollow}
+ openServiceConfiguration={() => actions.navigate('/configuration?section=' + encodeURIComponent('来源与订阅'))} />
),
},
};
diff --git a/frontend/src/react/router/pages/managed.tsx b/frontend/src/react/router/pages/managed.tsx
index 995c91523..60bdd486f 100644
--- a/frontend/src/react/router/pages/managed.tsx
+++ b/frontend/src/react/router/pages/managed.tsx
@@ -25,6 +25,7 @@ import {
import { managementSkeletonHtml, paintManagementPlaceholder } from '../../../management-placeholder';
import { isReviewCategory } from '../../review/review';
+import { javTab } from '../../jav/jav';
import { ShellActionsContext, useOpenEpoch } from '../router';
import type { ManagedOpenProps, ManagedPath, ShellActions } from '../shell-actions';
@@ -44,7 +45,7 @@ interface Runtime {
ledger_writer_origin?: string;
}
-const FOLLOW_MANAGE_TABS = ['list', 'add', 'feeds', 'wants', 'source'];
+const FOLLOW_MANAGE_TABS = ['list', 'add', 'feeds'];
const readStarted = () => pageOpens > 0;
/** 壳开始路由没有(`pageOpens` 大于 0)。 */
@@ -80,6 +81,11 @@ function writerProps(runtime: Runtime | null, path: string) {
/** 这一次打开交给页面的值,从地址、偏好与壳的状态算。等 `/healthz` 期间走开了回 null。 */
async function openProps(path: ManagedPath, run: Run): Promise<object | null> {
+ if (path === '/jav') {
+ const runtime = await readRuntime(run);
+ if (!run.live) return null;
+ return { tab: javTab(search().get('tab')), readOnly: !!runtime?.ledger_read_only } satisfies ManagedOpenProps['/jav'];
+ }
if (path === '/stats') return { configurable: !!runtimeConfigurable } satisfies ManagedOpenProps['/stats'];
if (path === '/taste') {
const onboarding = cameFromSetup;
@@ -88,7 +94,7 @@ async function openProps(path: ManagedPath, run: Run): Promise<object | null> {
}
if (path === '/configuration') {
if (window.location.hash === '#peachProxy') writeShell({ configurationRequestedSection: '网络与访问' });
- const section = configurationRequestedSection;
+ const section = search().get('section') || configurationRequestedSection;
return (section ? { section } : {}) satisfies ManagedOpenProps['/configuration'];
}
if (path === '/review') {
@@ -122,6 +128,12 @@ const SCROLL_ALWAYS = new Set<ManagedPath>(['/stats', '/taste']);
const SCROLL_WHEN_CURRENT = new Set<ManagedPath>(['/review', '/quality-goals', '/activity', '/follow-manage']);
async function openPage(path: ManagedPath, actions: ShellActions, run: Run): Promise<void> {
+ if (path === '/follow-manage' && search().get('tab') === 'wants') {
+ shellNavigate('/jav?tab=wants', { replace: true }); return;
+ }
+ if (path === '/follow-manage' && search().get('tab') === 'source') {
+ shellNavigate('/configuration?section=' + encodeURIComponent('来源与订阅'), { replace: true }); return;
+ }
const stats = document.getElementById('stats');
if (!stats) return;
actions.surfaceChanged('management', path);
diff --git a/frontend/src/react/router/shell-actions.ts b/frontend/src/react/router/shell-actions.ts
index e41bed48e..290408513 100644
--- a/frontend/src/react/router/shell-actions.ts
+++ b/frontend/src/react/router/shell-actions.ts
@@ -161,6 +161,7 @@ export type SurfaceKind = 'management' | 'index' | 'entity' | 'catalog' | 'follo
/** 管理区那几页每次打开时交给页面的值,由页面元素从地址、偏好与壳的状态算(`pages/managed.tsx`),按页面分。
* 管理区那几页画进 `#stats`。 */
export interface ManagedOpenProps {
+ '/jav': { tab: string; readOnly: boolean };
'/stats': { configurable: boolean };
'/taste': { onboarding: boolean };
'/review': { category: string; readOnly: boolean; readOnlyMessage: string; writerUrl: string };
diff --git a/frontend/src/react/wants/want-list.tsx b/frontend/src/react/wants/want-list.tsx
index 1a2a1a1a2..1a5e8cd88 100644
--- a/frontend/src/react/wants/want-list.tsx
+++ b/frontend/src/react/wants/want-list.tsx
@@ -1,7 +1,4 @@
-/* JAV 入库:按状态分组的作品卡,卡片下方查询磁链并提交云下载。
- *
- * 卡片下方的候选来自 JavDB;「搜索资源」打开云下载弹层,查自配索引器或贴磁力。页上那颗
- * 「提交磁力」是不挂在任何作品上的同一个弹层。 */
+/* JAV 想要:按状态分组的作品卡,复用资源链接查询与查找资源弹层。 */
import { useState } from 'react';
import type { KeyboardEvent, ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
@@ -75,7 +72,7 @@ function WantRow({ want, readOnly, busy, onReset, onRemove, onCloudDownload, dow
{source ? <ButtonLink data-button-link="" variant="secondary" size="small" trailingIcon={RiExternalLinkLine} href={source} target="_blank" rel="noopener noreferrer">来源页</ButtonLink> : null}
{/* 还在找的两段才给云下载:未发售的没有资源可下,已入库的已经到手。 */}
{want.phase === 'searching' || want.phase === 'given_up' ? (
- <Button variant="secondary" size="small" disabled={readOnly} onClick={onCloudDownload}>搜索资源</Button>
+ <Button variant="secondary" size="small" onClick={onCloudDownload}>查找资源</Button>
) : null}
{want.phase === 'given_up' ? (
<Button variant="secondary" size="small" disabled={readOnly} {...busyProps(busy === `reset:${want.id}`)}
@@ -120,9 +117,10 @@ function WantPhase({ phase, label, rows, row }: {
export interface WantListProps {
readOnly: boolean;
toast(message: string): void;
+ query?: string;
}
-export function WantList({ readOnly, toast }: WantListProps) {
+export function WantList({ readOnly, toast, query = '' }: WantListProps) {
const [code, setCode] = useState('');
const [download, setDownload] = useState<DownloadPrefill | null>(null);
const [provider, setProvider] = useState('');
@@ -159,7 +157,8 @@ export function WantList({ readOnly, toast }: WantListProps) {
};
const data = wants.data;
- const items = data?.items || [];
+ const items = (data?.items || []).filter(want => !query || [want.code, want.title, want.performers]
+ .join(' ').toLocaleLowerCase().includes(query.toLocaleLowerCase()));
const downloads = useQuery({
queryKey: DOWNLOADS_KEY,
queryFn: ({ signal }) => apiGet<DownloadsSnapshot>(`${DOWNLOADS_URL}?limit=100`, signal),
@@ -191,17 +190,17 @@ export function WantList({ readOnly, toast }: WantListProps) {
<Select aria-label="下载到" selectedKey={selected} onSelectionChange={(key) => setProvider(String(key))}>
{configured.map((row) => <SelectItem key={row.key} id={row.key}>{row.label}</SelectItem>)}
</Select>
- <Button variant="secondary" disabled={readOnly} onClick={() => setDownload({})}>提交磁力</Button>
+ <Button variant="secondary" onClick={() => setDownload({})}>查找资源</Button>
</div>
<Help>{configured.find((row) => row.key === selected)?.target || '使用已配置的目标目录'}</Help>
</div> : null}
{downloads.error ? <Note tone="error" title="下载配置未取得">{errorMessage(downloads.error)}</Note> : null}
- {downloads.data && !configured.length ? <Note tone="neutral">先在配置页「下载」分组登录 PikPak,或填好 CloudDrive2 的地址与令牌。</Note> : null}
+ {downloads.data && !configured.length ? <Note tone="neutral">尚未配置下载渠道。<a href={'/configuration?section=' + encodeURIComponent('下载渠道')}>下载渠道设置</a></Note> : null}
{downloads.data && !downloads.data.available ? <Note tone="neutral">云下载只在账本写入端可用。</Note> : null}
{data && !items.length ? (
- <EmptyState shell="plain" icon={RiStarLine} title="还没有想要的作品">
- 在上面输入番号,或在 Feed 新作卡、关注详情上点「想要」。
+ <EmptyState shell="plain" icon={RiStarLine} title={query ? '没有符合条件的作品' : '还没有想要的作品'}>
+ {query ? '试试其他番号、女优或标题。' : '在上面输入番号,或在 Feed 新作卡、关注详情上点「想要」。'}
</EmptyState>
) : null}
@@ -215,6 +214,7 @@ export function WantList({ readOnly, toast }: WantListProps) {
onReset={() => reset(want)} onRemove={() => remove(want)}
onCloudDownload={() => setDownload({
code: want.code || '', title: want.title || '', origin: `wishlist:${want.id}`,
+ cover: want.cover || '', performers: want.performers || '', release_date: want.release_date || '', studio: want.studio || '',
})} />
)} />
);
diff --git a/frontend/test/board-skeleton.test.ts b/frontend/test/board-skeleton.test.ts
index 302063202..002076708 100644
--- a/frontend/test/board-skeleton.test.ts
+++ b/frontend/test/board-skeleton.test.ts
@@ -56,14 +56,14 @@ describe('Board 页面骨架', () => {
expect(root.querySelector('.board-segment-thumb')).toBeNull();
expect(root.querySelector('[data-section-items] [aria-selected=true]')?.textContent).toBe('关注列表');
const track = root.querySelector('[data-section-items]')!;
- expect([...track.children].map((span) => span.textContent)).toEqual(['关注列表', '添加关注', 'JAV 订阅源', 'JAV 入库', '来源和凭证']);
+ expect([...track.children].map((span) => span.textContent)).toEqual(['关注列表', '添加关注', 'JAV 订阅源']);
});
it('关注骨架选中地址栏 `?tab=` 那一枚页签,列表以外的页签不画关注列表的工具行', () => {
const feeds = follow({ followTab: 'feeds' });
expect(feeds.querySelector('[data-section-items] [aria-selected=true]')?.textContent).toBe('JAV 订阅源');
expect(feeds.querySelector('.ui-follow-skeleton-toolbar')).toBeNull();
expect(feeds.querySelector('.ui-follow-skeleton-surface')).not.toBeNull();
- expect(follow({ followTab: 'wants' }).querySelector('[data-section-items] [aria-selected=true]')?.textContent).toBe('JAV 入库');
+ expect(follow({ followTab: 'wants' }).querySelector('[data-section-items] [aria-selected=true]')?.textContent).toBe('关注列表');
expect(follow({ followTab: 'nope' }).querySelector('[data-section-items] [aria-selected=true]')?.textContent).toBe('关注列表');
});
it('关注骨架的工具行按 Board UI 最终变体画:检查全部是主按钮,视图切换是按版式选中的按钮组', () => {
diff --git a/frontend/test/manage-header.test.ts b/frontend/test/manage-header.test.ts
index 734c60a7a..c91e85061 100644
--- a/frontend/test/manage-header.test.ts
+++ b/frontend/test/manage-header.test.ts
@@ -6,7 +6,7 @@ import { manageHeaderSkeletonHtml, manageHeaderView, type ManageEntry, type Mana
const SECTIONS: ManageEntry[] = [
['stats', '统计', 'chart'], ['cleanup', '数据管理', 'database'], ['trash', '回收站', 'trash'],
- ['configuration', '配置', 'settings'],
+ ['configuration', '服务配置', 'settings'],
];
const MENU = SECTIONS.filter(([key]) => key !== 'trash');
diff --git a/frontend/test/react/cloud-download-dialog.test.tsx b/frontend/test/react/cloud-download-dialog.test.tsx
index e3908a112..634726253 100644
--- a/frontend/test/react/cloud-download-dialog.test.tsx
+++ b/frontend/test/react/cloud-download-dialog.test.tsx
@@ -1,4 +1,5 @@
/* 云下载弹层的行为:提交带什么、成功后回执并关上、失败留在原处、没配置与只读端说什么。 */
+import { act } from 'react';
import { QueryClientProvider } from '@tanstack/react-query';
import { afterEach, expect, it, vi } from 'vitest';
@@ -68,13 +69,13 @@ const MAGNET = 'magnet:?xt=urn:btih:' + 'b'.repeat(40);
it('带着番号与标题打开:标题行写番号与片名,搜索框与番号框已填,提交带上渠道、目录与来处', async () => {
const posts = serve(snapshot(), { ok: true, outcome: 'submitted', task: task() });
const { close, receipt, page } = await open({ code: 'ABC-123', title: '一部作品', origin: 'asset:12', searchReason: '中字' });
- expect(page.querySelector('[role=dialog]')?.textContent).toContain('ABC-123 一部作品');
+ expect(page.querySelector('[role=dialog]')?.textContent).toContain('ABC-123 · 一部作品');
expect(page.textContent).toContain('版本目标:中字');
- expect(field(page, '搜索资源')?.value).toBe('ABC-123');
+ expect(field(page, '按番号查找资源')?.value).toBe('ABC-123');
expect(field(page, '番号')).toBeNull();
expect(field(page, '目标目录')?.value).toBe('/115/云下载');
await type(field(page, '磁力链接'), MAGNET);
- await submit(section(page, '提交磁力'));
+ await submit(section(page, '提交下载'));
await settle();
expect(posts).toEqual([{
magnet: MAGNET, provider: '115', target: '/115/云下载', code: 'ABC-123', title: '一部作品', origin: 'asset:12',
@@ -88,36 +89,61 @@ it('提交没成功时弹层不关,原因留在表单里', async () => {
task: task({ state: 'failed', failure_label: '没有可用的资源', failure_detail: '远端拒收' }) });
const { close, receipt, page } = await open({});
await type(field(page, '磁力链接'), MAGNET);
- await submit(section(page, '提交磁力'));
+ await submit(section(page, '提交下载'));
await settle();
expect(page.textContent).toContain('提交没有成功:没有可用的资源:远端拒收');
expect([close.mock.calls.length, receipt.mock.calls.length]).toEqual([0, 0]);
});
+it('查找另一番号时清空先前的磁力和作品资料,资料未取得时提交不带其他作品的标题', async () => {
+ const posts: unknown[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
+ if (init?.method === 'POST') posts.push(JSON.parse(String(init.body)));
+ return { ok: true, status: 200, json: async () => init?.method === 'POST'
+ ? { ok: true, outcome: 'submitted', task: task() }
+ : url.startsWith('/api/items') ? { items: [{ id: 2, code: 'ABC-9999', name: '其他作品' }] }
+ : url.startsWith('/api/resources') ? { state: 'ready', warnings: [], error: '', items: [] }
+ : snapshot() };
+ }));
+ const { page } = await open({ code: 'ABC-123', title: '原作品', origin: 'asset:12', performers: '甲', duration: 600 });
+ await type(field(page, '磁力链接'), MAGNET);
+ await type(field(page, '按番号查找资源'), 'ABC-999');
+ await act(async () => field(page, '按番号查找资源')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
+ await settle();
+ expect(page.querySelector('[data-resource-work]')?.textContent).toContain('作品资料未取得');
+ expect(page.querySelector('[data-resource-work]')?.textContent).not.toContain('原作品');
+ expect(field(page, '磁力链接')?.value).toBe('');
+ await type(field(page, '磁力链接'), MAGNET);
+ await submit(section(page, '提交下载'));
+ expect(posts).toEqual([{ magnet: MAGNET, provider: '115', target: '/115/云下载', code: 'ABC-999' }]);
+});
+
it('入库页交进来的下载方式先选中;换渠道时目标目录跟着换,115 才提配额', async () => {
serve(snapshot());
const { page } = await open({}, 'pikpak');
expect(field(page, '目标目录')?.value).toBe('/云下载');
expect(page.textContent).not.toContain('扣一条离线配额');
- expect(buttonNamed('提交离线下载', page)?.className).toContain('bg-button-primary');
+ expect(buttonNamed('提交下载', page)?.className).toContain('bg-button-primary');
await choose(page.querySelector('[role=dialog] [aria-label="下载到"]'), '115');
expect(field(page, '目标目录')?.value).toBe('/115/云下载');
expect(page.textContent).toContain('每提交一次扣一条离线配额');
});
-it('一个渠道都没配时说去哪里配,不画表单', async () => {
+it('没有下载渠道时可以查找资源,提交下载禁用', async () => {
serve(snapshot({ providers: [
{ key: '115', label: '115', configured: false, target: '' },
{ key: 'pikpak', label: 'PikPak', configured: false, target: '' },
] }));
const { page } = await open({});
- expect(section(page, '提交磁力')).toBeNull();
- expect(page.textContent).toContain('先在配置页「下载」分组');
+ expect(section(page, '查找资源')).not.toBeNull();
+ expect(buttonNamed('提交下载', page)?.disabled).toBe(true);
+ expect(page.textContent).toContain('下载渠道设置');
});
-it('只读端说明原因,不画表单', async () => {
+it('只读端可查找资源,提交下载禁用', async () => {
serve(snapshot({ available: false }));
const { page } = await open({});
expect(page.textContent).toContain('云下载只在账本写入端可用');
- expect(section(page, '提交磁力')).toBeNull();
+ expect(section(page, '查找资源')).not.toBeNull();
+ expect(buttonNamed('提交下载', page)?.disabled).toBe(true);
});
diff --git a/frontend/test/react/follow-controller.test.ts b/frontend/test/react/follow-controller.test.ts
index 1bd10a7c6..d1a8d5e33 100644
--- a/frontend/test/react/follow-controller.test.ts
+++ b/frontend/test/react/follow-controller.test.ts
@@ -115,7 +115,7 @@ describe('关注域地址与会话控制', () => {
expect(followManageParams('?page=-4&tab=invalid')).toEqual({ tab: 'list', page: 1, sort: '', dir: '' });
expect(followManageParams('?page=3.9&tab=feeds&sort=added&dir=asc')).toEqual({ tab: 'feeds', page: 3, sort: 'added', dir: 'asc' });
expect(followManagePath({ tab: 'list', page: 1, sort: '', dir: '' })).toBe('/follow-manage');
- expect(followManageEntry('?tab=wants&page=4&sort=x')).toBe('/follow-manage?tab=wants');
+ expect(followManageEntry('?tab=wants&page=4&sort=x')).toBe('/jav?tab=wants');
expect(followManageEntry('?tab=wants', 'add')).toBe('/follow-manage?tab=add');
});
diff --git a/frontend/test/react/follow-manage.test.tsx b/frontend/test/react/follow-manage.test.tsx
index de72d200e..b2e0de415 100644
--- a/frontend/test/react/follow-manage.test.tsx
+++ b/frontend/test/react/follow-manage.test.tsx
@@ -20,6 +20,7 @@ import {
type FollowSource, type ResolveJob, type SuggestData,
} from '../../src/react/follow-manage/follow-manage';
import { FollowManagePage } from '../../src/react/follow-manage/follow-manage-page';
+import { Credentials } from '../../src/react/follow-manage/credentials';
import { buttonNamed, choose, click, mountRoot, settle, type } from './render';
@@ -144,6 +145,7 @@ const shellProps = (over: Partial<Props> = {}): Props => ({
savePreference: vi.fn(),
toast: vi.fn(),
openFollow: vi.fn(),
+ openServiceConfiguration: vi.fn(),
readOnly: false, readOnlyMessage: '', writerUrl: '',
...over,
});
@@ -154,7 +156,9 @@ async function open(plan: Plan = {}, over: Partial<Props> = {}) {
const props = shellProps(over);
await prefetchFollowManage(new AbortController().signal, props.tab).catch(() => {});
const mounted = await mountRoot(
- <QueryClientProvider client={queryClient}><FollowManagePage {...props} /></QueryClientProvider>);
+ <QueryClientProvider client={queryClient}>{over.tab === 'source'
+ ? <Credentials data={plan.creds || credentials()} readOnly={props.readOnly} toast={props.toast} />
+ : <FollowManagePage {...props} />}</QueryClientProvider>);
await settle();
return { fetcher, props, ...mounted };
}
@@ -627,7 +631,8 @@ it('一条来源都没有时空态给出添加关注的去处', async () => {
it('各栏按做事的先后排,缺凭据的数挂在最后一栏上', async () => {
const { host } = await open({ creds: { root: 'C:\\creds', providers: [credential({ provider: 'fanbox' })] } });
expect([...host.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent))
- .toEqual(['关注列表', '添加关注', 'JAV 订阅源', 'JAV 入库', '来源和凭证(1)']);
+ .toEqual(['关注列表', '添加关注', 'JAV 订阅源']);
+ expect(buttonNamed('来源与订阅设置(1)', host)).not.toBeNull();
});
const FEEDS: FeedsData = {
@@ -1171,8 +1176,7 @@ it('筛选里撞见缺凭据的站,一步跳到凭据那一栏', async () => {
const { host, props } = await open({ creds }, { tab: 'add' });
await click(buttonLabelled(host, '全部来源'));
await click(buttonNamed('需要配置凭据'));
- expect(props.route).toHaveBeenLastCalledWith(expect.objectContaining({ tab: 'source' }));
- expect([...host.querySelectorAll('h3')].map((h) => h.textContent)).toContain('来源和凭证');
+ expect(props.openServiceConfiguration).toHaveBeenCalledOnce();
});
it('「猜你喜欢」点一下就拿那个名字去查', async () => {
diff --git a/frontend/test/react/jav.test.ts b/frontend/test/react/jav.test.ts
new file mode 100644
index 000000000..5705b2c48
--- /dev/null
+++ b/frontend/test/react/jav.test.ts
@@ -0,0 +1,19 @@
+import { expect, it } from 'vitest';
+import { javTab, rankedDiscoveries, type Discovery } from '../../src/react/jav/jav';
+
+const work = (id: number, performers: string) => ({ id, performers, code: `ABC-${id}`, release_date: '2026-10-01' }) as Discovery;
+it('发现只推荐新作中出演者与真实口味信号一致的作品', () => {
+ const ranked = rankedDiscoveries([work(1, '甲、乙'), work(2, '乙'), work(3, '甲的朋友'), work(4, '')], {
+ rankings: { peach_performers: [{ name: '甲', score: 10 }], browser_creators: [{ name: '乙', visits: 2 }] },
+ });
+ expect(ranked.map(item => item.id)).toEqual([1, 2]);
+ expect(ranked[0]?.matches).toEqual(['甲', '乙']);
+ expect(rankedDiscoveries([work(1, '甲')], {})).toEqual([]);
+});
+it('JAV 分区从深链恢复,未知分区落在馆藏', () => {
+ expect(javTab('discover')).toBe('discover'); expect(javTab('wants')).toBe('wants'); expect(javTab('other')).toBe('library');
+});
+it('未取得发行日的真实新作可以参与口味排序', () => {
+ const items = [{ ...work(1, '甲'), release_date: '' }, work(2, '甲')];
+ expect(rankedDiscoveries(items, { rankings: { peach_performers: [{ name: '甲', score: 1 }] } }).map(item => item.id)).toEqual([2, 1]);
+});
diff --git a/frontend/test/react/quality-goals.test.tsx b/frontend/test/react/quality-goals.test.tsx
index facc7640b..f8daf34bc 100644
--- a/frontend/test/react/quality-goals.test.tsx
+++ b/frontend/test/react/quality-goals.test.tsx
@@ -140,12 +140,12 @@ it('封面、标题和页脚三处都打开同一部作品,无障碍名称用
it('搜索资源原地打开云下载弹层,带入番号与原版本目标;无番号只提供查看版本', async () => {
const { host } = await open(payload([goal({ id: 42, code: 'ABC-123', reason: '中字' }), goal({ id: 43 })]));
- const buttons = [...host.querySelectorAll('button')].filter((node) => node.textContent === '搜索资源');
+ const buttons = [...host.querySelectorAll('button')].filter((node) => node.textContent === '查找资源');
expect(buttons).toHaveLength(1);
await click(buttons[0]);
await settle();
const dialog = document.querySelector('[role=dialog]');
- expect(dialog?.textContent).toContain('ABC-123 名称 one.mp4');
+ expect(dialog?.textContent).toContain('ABC-123 · 名称 one.mp4');
});
it('一条目标都没有时给空态,不是一片白', async () => {
diff --git a/frontend/test/react/resource-search.test.tsx b/frontend/test/react/resource-search.test.tsx
index 8e9c05745..325f0238a 100644
--- a/frontend/test/react/resource-search.test.tsx
+++ b/frontend/test/react/resource-search.test.tsx
@@ -25,7 +25,7 @@ it('回车按番号查询,选择候选只填表单', async () => {
size: 1024 ** 3, seeders: 2, origins: ['测试源'], resolution: 2160, codec: 'HEVC' }] }) }));
vi.stubGlobal('fetch', fetch);
const host = await mount(<ResourceSearch initialCode="ABC-123" choose={choose} />);
- await act(async () => field(host, '搜索资源')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
+ await act(async () => field(host, '按番号查找资源')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
await settle();
expect(fetch.mock.calls[0]?.[0]).toContain('/api/resources/search?code=ABC-123&goal=quality');
expect(host.textContent).toContain('一处来源未响应');
@@ -36,26 +36,48 @@ it('回车按番号查询,选择候选只填表单', async () => {
expect(host.textContent).toContain('已填入磁力');
});
+it('资料查询只接收相同番号,其他作品的字段不会进入资源弹层', async () => {
+ const onWork = vi.fn();
+ vi.stubGlobal('fetch', vi.fn(async (url: string) => ({ ok: true, json: async () => url.startsWith('/api/items')
+ ? { items: [{ id: 2, code: 'ABC-1234', name: '另一部作品', duration: 600 }] }
+ : { state: 'ready', warnings: [], error: '', items: [] } })));
+ const host = await mount(<ResourceSearch initialCode="ABC-123" choose={vi.fn()} onWork={onWork} />);
+ await act(async () => field(host, '按番号查找资源')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
+ await settle();
+ expect(onWork).toHaveBeenCalledWith(null);
+});
+
+it('相同番号的资料保留真实出演者、发行日和时长', async () => {
+ const onWork = vi.fn();
+ vi.stubGlobal('fetch', vi.fn(async (url: string) => ({ ok: true, json: async () => url.startsWith('/api/items')
+ ? { items: [{ id: 3, code: 'ABC-123', catalog_title: '作品标题', performers: ['甲'], release_date: '2026-09-01', duration: 600, has_cover: true }] }
+ : { state: 'ready', warnings: [], error: '', items: [] } })));
+ const host = await mount(<ResourceSearch initialCode="ABC-123" choose={vi.fn()} onWork={onWork} />);
+ await act(async () => field(host, '按番号查找资源')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
+ await settle();
+ expect(onWork).toHaveBeenCalledWith(expect.objectContaining({ code: 'ABC-123', title: '作品标题', performers: '甲', release_date: '2026-09-01', duration: 600, cover: '/cover?code=ABC-123&thumb=1' }));
+});
+
it('查询等待期间保持输入焦点并拦截重复回车,完成后恢复编辑', async () => {
let finish!: (value: unknown) => void;
const fetch = vi.fn(() => new Promise((resolve) => { finish = resolve }));
vi.stubGlobal('fetch', fetch);
const host = await mount(<ResourceSearch initialCode="ABC-123" choose={vi.fn()} />);
- const input = field(host, '搜索资源')!;
+ const input = field(host, '按番号查找资源')!;
input.focus();
const enter = () => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
await act(async () => { enter() });
expect(input.disabled).toBe(false);
expect(input.readOnly).toBe(true);
expect(document.activeElement).toBe(input);
- expect(section(host, '资源搜索')?.getAttribute('aria-busy')).toBe('true');
+ expect(section(host, '查找资源')?.getAttribute('aria-busy')).toBe('true');
expect(host.textContent).toContain('正在搜索资源');
await act(async () => { enter() });
expect(fetch).toHaveBeenCalledTimes(1);
await act(async () => finish({ ok: true, json: async () => ({ state: 'ready', items: [], warnings: [], error: '' }) }));
await settle();
expect(input.readOnly).toBe(false);
- expect(section(host, '资源搜索')?.getAttribute('aria-busy')).toBe('false');
+ expect(section(host, '查找资源')?.getAttribute('aria-busy')).toBe('false');
expect(host.textContent).not.toContain('正在搜索资源');
});
@@ -67,7 +89,7 @@ it.each([['中字', 'chinese'], ['无码', 'uncensored'], ['不需要无码,
const host = await mount(<ResourceSearch initialCode="ABC-123" reason={reason} choose={vi.fn()} />);
expect(host.textContent).toContain(`版本目标:${reason}`);
expect(fetch).not.toHaveBeenCalled();
- await act(async () => field(host, '搜索资源')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
+ await act(async () => field(host, '按番号查找资源')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
await settle();
expect(fetch.mock.calls[0]?.[0]).toContain(`goal=${goal}`);
});
diff --git a/frontend/test/react/want-list.test.tsx b/frontend/test/react/want-list.test.tsx
index dce5673d5..c3f00845a 100644
--- a/frontend/test/react/want-list.test.tsx
+++ b/frontend/test/react/want-list.test.tsx
@@ -76,19 +76,19 @@ it('按待找、未发售、暂时放弃、已入库分段,段名带条数;
expect(buttonNamed('重新查找', host.querySelector('[data-want-id="2"]')!)).toBeNull();
});
-it('待找与暂时放弃两段每行有搜索资源,原地打开带番号与标题的云下载弹层;未发售与已入库没有', async () => {
+it('待找与暂时放弃两段每行有查找资源,原地打开带番号与标题的云下载弹层;未发售与已入库没有', async () => {
serve(listed([
want(2, { title: '雨の日' }), want(3, { phase: 'given_up', search_count: 3 }),
want(4, { phase: 'unreleased', release_date: '2026-12-01' }), want(1, { phase: 'acquired' }),
want(6, { code: null, origin: 'follow', title: '关注里的一条', follow_item_id: 9 }),
]));
const { host } = await open();
- const key = (id: number) => buttonNamed('搜索资源', host.querySelector(`[data-want-id="${id}"]`)!);
+ const key = (id: number) => buttonNamed('查找资源', host.querySelector(`[data-want-id="${id}"]`)!);
expect([2, 3, 4, 1, 6].map((id) => !!key(id))).toEqual([true, true, false, false, true]);
expect(key(2)!.className).toContain('bg-background-primary-default');
await click(key(2));
await settle();
- expect(document.querySelector('[role=dialog]')?.textContent).toContain('ABC-2 雨の日');
+ expect(document.querySelector('[role=dialog]')?.textContent).toContain('ABC-2 · 雨の日');
});
it('一条都没有就是空态,不画空的分段', async () => {
@@ -145,7 +145,7 @@ it('只读的机器:输入框、添加与每行的键都禁用', async () => {
expect(host.querySelector<HTMLInputElement>('input[aria-label="番号"]')!.disabled).toBe(true);
expect(buttonNamed('添加', host)!.disabled).toBe(true);
expect(buttonNamed('移除', host)!.disabled).toBe(true);
- expect(buttonNamed('搜索资源', host)!.disabled).toBe(true);
+ expect(buttonNamed('查找资源', host)!.disabled).toBe(false);
});
it(`一段多于 ${WANT_PAGE_SIZE} 条时分页,页码各段各记各的;报错只露一行`, async () => {