Peach: Local-first video metadata scraper and media manager.
feat: 显示后台任务阶段计数并统一状态反馈控件
longmeidao0001382c32d8
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex fe892c07e..55eee88ad 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -86,7 +86,7 @@ React 渲染的规格页、用户截图这类给不出可重抓字节的实测- 相关推荐算法:`openaver-related-ranking`,固定 revision,只参考 Tag IDF 与结构化共同点,MMR 和稳定破同分是 Peach 自加,不复制上游界面或源码。- 网格、控件半径、语义 token 与中间省略:`vercel-geist-grid`、`vercel-geist-controls-measured`、`vercel-geist-middle-truncate`;中间省略只用于路径、URL、ID、SHA 这类首尾都有信息的值,必须显式 `data-middle-truncate`,标题、说明、人名和标签保留末尾省略。-- 统计与口味层级,Note/Progress/Switch/Fieldset/Scroller/Empty State 语义与控件:`vercel-geist-semantics-measured`、`vercel-geist-note-progress-switch-analytics`、`vercel-geist-fieldset-scroller-empty-state`;配置页截图补证:`vercel-geist-controls-measured`。+- 统计与口味层级,Note/Progress/Gauge/Context Card 等控件:`vercel-geist-semantics-measured`、`vercel-geist-note-progress-switch-analytics`、`vercel-geist-fieldset-scroller-empty-state`;配置页截图补证:`vercel-geist-controls-measured`。- 分类切换条属于 Tabs 的 secondary 变体而不是分段器:`vercel-geist-tabs-secondary-measured`。- 表格、排行与面包屑:`vercel-geist-table-ranking`、`vercel-geist-breadcrumbs`;同形可比较数据才用语义 `table` 并保持 tabular numerals,内容标签是固定 Top 排行和直接筛选,不伪装成可排序数据表。- 设置 Dialog 动效、搜索期 Spinner、后台 Loading Dots 与 busy 按钮:`vercel-geist-command-search-loading`;中性说明 Note:`vercel-notifications-note`;具名动作 Toast:`vercel-geist-toast`;写操作前的确认弹层:`vercel-geist-modal-measured`。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex e051c2375..7deb71386 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -278,3 +278,5 @@ Python、npm 与 GitHub Actions 的版本由 `.github/dependabot.yml` 每周检- 作品封面只进入头像候选,单人作品关联不证明画面中的人物身份;`cover_fallback` 显式标记身份未核实,安装闸门独立拒绝这类来源。- 复核页面上下文复用原生 CSS sticky 与主导航 `--topH`,分类及筛选栏合为同一吸附区。卡片以 flex 分开标题、既有 Scroller、当前信息和操作;只有资料滚动,当前信息过长时可聚焦滚动阅读。多选计数共用 `selectiondockcount`,保留首页的文字口径;不新增依赖,不改变候选与提交协议。- 复核分类复用 `selectFieldHtml`、`wireSelectField` 和现有 `list-filter` 图标;图标只在筛选入口显示,选项保留文字与选中标记。按当前候选数据提供字段及来源选项,批量决定复用既有协议。字段次级分类采用具名 Listbox 分区,依据见 `reference-snapshots/vercel-review-actions.md`。人工复核与馆藏、关注、标签、垃圾文件和回收站共用 `selectiondock` 浮窗布局,保留各自操作与提交协议;复核卡片内作品样本选择仍属于单条候选,不混入页面级多选。没有新增依赖。Shift 连选使用原生 `mousedown.preventDefault()` 防止文字选区;实际浏览器验证覆盖亮暗主题、宽屏和 390px。++反馈控件复用:`noteHtml`、`progressHtml`、`gaugeHtml`、`projectBannerHtml` 与 `wireContextCard` 集中在共享 UI 模块;信息卡片复用原生 Popover 和现有锚定菜单定位,不添加浮层依赖。`BackgroundJob.update(job_id)` 报告浏览记录、口味分析和逐行来源解析的阶段与计数,`followJobProgress` 统一读取文字和总量,查询不重新执行任务。浏览记录解析继续使用 browserexport;本地临时浏览器数据库验证计数及隐私字段。证据见 `reference-snapshots/vercel-geist-note-progress-switch-analytics.md`。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex c87ad7e97..aa765fdc2 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -9,6 +9,7 @@## 运行态- 复核取证、吸附栏与多选浮窗见 `REUSE.md`。+- 预览 18976;未部署。- 女优头像 545 张:2026-09-06 经用户批准换上 54 张 Gfriends 正脸照,脸宽中位数 148px → 320px;被顶掉的整套留在 `avatars-superseded/`,挑图与换源判据见 `SOURCING.md`。- 小图显示、资料骨架、官网图标、X 原色及自动播放开关已实现;桌面和手机预览通过,生产浏览器取证受客户端限制。请求共用 Chrome UA。diff --git a/docs/reference-snapshots/vercel-geist-note-progress-switch-analytics.md b/docs/reference-snapshots/vercel-geist-note-progress-switch-analytics.mdindex 53d669e31..dded1868f 100644--- a/docs/reference-snapshots/vercel-geist-note-progress-switch-analytics.md+++ b/docs/reference-snapshots/vercel-geist-note-progress-switch-analytics.md@@ -81,3 +81,19 @@ HTTPX 取得 `https://vercel.com/geist/fieldset` 当前 HTML,SHA-256 为- `/taste` 保留现有真实时间窗;以 radio 切换浏览器/Peach 证据,摘要指标、主详情和排行面板随证据来源切换。宽屏使用一个 1100px 阅读列,窄屏指标带内部横向滚动,页面本身不得横向溢出。- 关注页的可关闭历史失败是页面级 Banner,不是 Note;检查失败明细、资源同步失败和口味加载失败使用持久 error Note。++## 2026-09-06 提示与任务进度复核++官方页面:<https://vercel.com/geist/note>、<https://vercel.com/geist/progress>、<https://vercel.com/geist/gauge>、<https://vercel.com/geist/project-banner>、<https://vercel.com/geist/context-card>、<https://vercel.com/geist/separator>、<https://vercel.com/geist/loading-dots>。通过 HTTPX 严格 TLS 获取页面 HTML/CSS,并用浏览器核验本地组件。++HTML SHA-256:Note `f3471155164c8e0085419ce04e15928463cb526b4a52b51483c214fd84b645dc`;Project Banner `9bcc6478e468ecb48d146b774c36ceed62439ee78cc51e5ecf691c2c728204c8`;Context Card `ab1891a9600b3f019ffc3540ad2ca340b569b4261ced74babe0996f08c5e3210`;Gauge `a7303d848ea4dca4f865d5f7bbff467080015e6a771f4c900eaa7b91b0c3b4ab`。++- Note 使用语义色、12px 图文间距、14px 正文,成功为蓝色。默认无填充,filled 用低饱和色底;small 用于紧凑说明。Note 持续到状态解决,不额外加关闭键;短成功回执仍用 Toast。+- 页面后台任务使用 Project Banner:正文 14px,最小高度 40px,上下 8px、横向 24px;处理链接持续带下划线。按用户要求在横幅内用 32px Gauge 表示任务完成比例,这是 Peach 的用途差异;详情仍用 Progress。+- Gauge 用于实际已用/总容量,无有效总量时显示未取得。没有统一容量告警门槛时不单独创造阈值;文字保留百分比与字节数。+- Progress 按状态使用蓝、黄、红,而非把接近完成误判为危险;stops 仅用于真实阶段并带标签。更新准备使用后端的 65、67、90 阶段边界;浏览记录分阶段计数,不把不同单位拼成虚假的总体百分比。+- 局部未知总量任务使用带边界的 Fieldset 内容区与 Loading Dots,已知计数时添加文字与 Progress;不重复嵌套已有任务容器。+- Separator 用于同一容器内不同内容组时留缩进;卡片正文与页脚之间保持完整边界。相关设置共享一组时不强加分隔线。+- Context Card 用于凭据位置说明与图片元信息,复用原生 Popover 和锚定浮层;150ms 悬停,键盘 Escape 关闭,优先左对齐,空间不足时翻转和限制内部高度。短标签继续使用 Tooltip。++本节为人工取证笔记,不登记为可覆盖的上游快照。diff --git a/frontend/src/api.ts b/frontend/src/api.tsindex 4070b0d78..5c815e1f6 100644--- a/frontend/src/api.ts+++ b/frontend/src/api.ts@@ -6,13 +6,15 @@* 迟到的响应不能再往新页面上写东西。 *//** 服务端明确回了非 2xx。`status` 留给调用方区分 401/409/404 这类需要不同处置的情况。 */+import {requestErrorMessage} from '@peach/legacy/core';+export class ApiError extends Error {readonly status: number;/** 响应体原样。表单校验那种 400 会在 `errors` 里按字段给原因,页面要把它们写回原位。 */readonly body: unknown;constructor(message: string, status: number, body: unknown = null) {- super(message);+ super(requestErrorMessage(message,status));this.name = 'ApiError';this.status = status;this.body = body;@@ -33,8 +35,7 @@ const reasonOf = (payload: unknown): string => {** 一次取数失败会同时落到两处——`mountIsland` 的首屏状态和共享 store 的错误态——* 两边显示的必须是同一句话,否则同一个失败会因为落在哪儿而说法不同。 */-export const errorMessage = (cause: unknown): string =>- cause instanceof Error ? cause.message : String(cause);+export const errorMessage = (cause: unknown): string => requestErrorMessage(cause);/** GET 一个 `/api/...` 契约端点。`signal` 中止时抛出 `AbortError`,调用方据此放弃写 DOM。 */export async function apiGet<T>(path: string, signal?: AbortSignal): Promise<T> {diff --git a/frontend/src/islands/library-processing.tsx b/frontend/src/islands/library-processing.tsxindex 6c10e8471..d5a294c24 100644--- a/frontend/src/islands/library-processing.tsx+++ b/frontend/src/islands/library-processing.tsx@@ -1,6 +1,6 @@import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';import { apiGet, apiSend, errorMessage } from '../api';-import { fieldsetTitle, loadingDotsHtml, noteHtml, progressHtml, setActionBusy } from '@peach/legacy/ui';+import { fieldsetTitle, loadingDotsHtml, noteHtml, progressHtml, projectBannerHtml, setActionBusy } from '@peach/legacy/ui';import { watchJob } from '../jobs';import type { JobState } from '../jobs';import type { IslandState } from '../islands';@@ -57,10 +57,12 @@ export function LibraryProcessing({ data, error, toast, onComplete, mode, monito}if (mode === 'notice') {if (!problem && state.status !== 'running' && state.status !== 'failed') return null;- return <div class="library-processing-banner" role="status">- <span>{problem || (state.status === 'failed' ? '扫描与资料采集未完成' : `${state.stage || '正在整理馆藏'}${state.total ? ` · ${state.checked || 0} / ${state.total}` : ''}`)}</span>- <a class="geist-button" href="/data-cleanup#libraryProcessing">{problem || state.status === 'failed' ? '查看并处理' : '查看进度'}</a>- </div>;+ const message=problem || (state.status === 'failed' ? '扫描与资料采集未完成' : `${state.stage || '正在整理馆藏'}${state.total ? ` · ${state.checked || 0} / ${state.total}` : ''}`);+ return <div dangerouslySetInnerHTML={{__html:projectBannerHtml(message,{+ variant:problem || state.status === 'failed' ? 'warning' : 'gray',+ href:'/data-cleanup#libraryProcessing',label:problem || state.status === 'failed' ? '查看并处理' : '查看进度',+ value:state.checked || 0,max:state.status === 'running' ? state.total : undefined,+ })}} />;}return <><div class="geist-fieldset-content library-processing">diff --git a/frontend/src/islands/release-updates.tsx b/frontend/src/islands/release-updates.tsxindex 127ea933c..1db07cb94 100644--- a/frontend/src/islands/release-updates.tsx+++ b/frontend/src/islands/release-updates.tsx@@ -97,7 +97,8 @@ export function ReleaseUpdates({ initial, initialJob }: { initial: ReleaseState;{job.state !== 'idle' ? <div aria-live="polite"><p class={job.state === 'error' ? 'configbad' : 'confighelp'}>{job.message}</p>{job.state !== 'error' ? <>- <div dangerouslySetInnerHTML={{__html:progressHtml(job.state === 'downloading' ? '下载进度' : '安装进度',job.state === 'downloading' ? job.downloaded || 0 : job.progress,job.state === 'downloading' ? job.total || 1 : 100)}} />+ <div dangerouslySetInnerHTML={{__html:progressHtml('更新准备进度:下载、校验、解压、准备安装',job.progress,100,{stops:[{value:65,label:'下载结束'},{value:67,label:'校验结束'},{value:90,label:'准备安装'}]})}} />+ <p class="confighelp">下载 → 校验 → 解压 → 准备安装 · {job.message}</p><p class="confighelp">{job.state === 'downloading' && job.total ? `${((job.downloaded || 0)/1048576).toFixed(1)} / ${(job.total/1048576).toFixed(1)} MB` : `${job.progress}%`}</p></> : null}</div> : null}diff --git a/frontend/src/jobs.ts b/frontend/src/jobs.tsindex bb7e528b8..2e32469f7 100644--- a/frontend/src/jobs.ts+++ b/frontend/src/jobs.ts@@ -6,6 +6,7 @@ export interface JobState {total?: number;older?: boolean;error?: string;+ message?: string;current?: { label?: string; provider?: string; attempt?: number;max_attempts?: number; retry_in?: number };}@@ -77,7 +78,7 @@ export function followJobProgress(options: {const current = state.current;const attempt = (current?.attempt || 1) > 1? ` · 第 ${current?.attempt}/${current?.max_attempts} 次尝试${current?.retry_in ? `,${current.retry_in} 秒后重试` : ''}` : '';- const text = (options.title || (state.total+ const text = (state.message || (options.title ? options.title + (state.total ? `:已完成 ${state.checked || 0}/${state.total}` : '') : '') || (state.total? `${state.older ? '抓取历史' : '检查更新'}:已完成 ${state.checked || 0}/${state.total} 个来源`: '正在准备检查任务…'))+ (current ? ` · ${current.label || current.provider || ''}${attempt}` : '');diff --git a/frontend/src/legacy/core.d.ts b/frontend/src/legacy/core.d.tsindex 2dacf09ca..03022d761 100644--- a/frontend/src/legacy/core.d.ts+++ b/frontend/src/legacy/core.d.ts@@ -7,6 +7,7 @@/** 来源代号到界面名称:`local`→`本地`、`115`→`115`、`pikpak`→`PikPak`、`online`→`在线`。 */export declare const LOC: Record<string, string>;export declare function icon(name: string): string;+export declare function requestErrorMessage(cause: unknown, status?: number): string;/** 秒数格式化成 `h:mm:ss`/`m:ss`;`0`、负数与非有限值都是 `—`(probe 的硬失败哨兵)。 */export declare function fmtDur(seconds: number | null | undefined): string;diff --git a/frontend/src/legacy/ui.d.ts b/frontend/src/legacy/ui.d.tsindex 8234c594f..ee74e56fb 100644--- a/frontend/src/legacy/ui.d.ts+++ b/frontend/src/legacy/ui.d.ts@@ -17,7 +17,7 @@ export declare function fieldsetTitle(id: string, title: string): string;export declare function badgeHtml(text: string): string;export declare function checkboxHtml(inputAttrs?: string): string;export declare function loadingDotsHtml(label?: string, options?: { className?: string }): string;-export declare function progressHtml(label: string, value: number, max?: number): string;+export declare function progressHtml(label: string, value: number, max?: number, options?:{variant?:'active'|'warning'|'error';stops?:{value:number;label:string}[]}): string;export declare function confirmModal(options: {title: string; body: string; confirmLabel: string; cancelLabel?: string; danger?: boolean; onConfirm?: () => Promise<unknown>}): Promise<{confirmed: boolean; result?: unknown}>;export declare function selectFieldHtml(items: string[][], current: string,@@ -38,5 +38,8 @@ export declare function noteHtml(variant?: 'secondary' | 'warning' | 'error' | 'success';label?: string;className?: string;+ size?: 'small' | 'medium';+ filled?: boolean;},): string;+export declare function projectBannerHtml(message:string,options:{variant?:'gray'|'success'|'warning'|'error';href:string;label:string;value?:number;max?:number}):string;diff --git a/frontend/test/feedback.test.ts b/frontend/test/feedback.test.tsnew file mode 100644index 000000000..44474c0ff--- /dev/null+++ b/frontend/test/feedback.test.ts@@ -0,0 +1,39 @@+import {describe,expect,it} from 'vitest';+// @ts-expect-error 使用浏览器正式模块验证共享契约。+import {requestErrorMessage} from '../../web/js/core.js';+// @ts-expect-error 使用浏览器正式控件验证输出。+import {noteHtml,projectBannerHtml,gaugeHtml,progressHtml} from '../../web/js/ui-components.js';++describe('中文错误反馈',()=>{+ it.each(['Failed to fetch','NetworkError when attempting to fetch resource.','Load failed'])('网络异常 %s 给出连接检查方法',message=>{+ expect(requestErrorMessage(new TypeError(message))).toBe('无法连接到 Peach 服务,请确认网络连接和托盘服务已启动。');+ });+ it.each([[401,'登录已失效'],[403,'没有执行此操作的权限'],[404,'已不存在'],[429,'过于频繁'],[503,'暂时不可用'],[504,'超时']])('HTTP %s 使用明确原因', (code,reason)=>{+ expect(requestErrorMessage('request failed',code)).toContain(reason);+ });+ it('保留服务端明确的中文原因',()=>{+ expect(requestErrorMessage('媒体盘没有挂载,请先连接媒体盘。',409)).toBe('媒体盘没有挂载,请先连接媒体盘。');+ });+});+describe('持久提示控件',()=>{+ it('容量比例和任务计数使用真实上限,未知容量不显示零',()=>{+ const host=document.createElement('div');host.innerHTML=gaugeHtml('使用率',25,50);+ expect(host.querySelector('[role=progressbar]')?.getAttribute('aria-valuenow')).toBe('50');+ expect(gaugeHtml('使用率',0,0)).toContain('未取得');+ host.innerHTML=progressHtml('分析记录',3,10,{stops:[{value:5,label:'分析结束'}],variant:'warning'});+ expect(host.querySelector('[role=progressbar]')?.getAttribute('aria-valuemax')).toBe('10');+ expect(host.querySelector('[aria-label="分析结束"]')).not.toBeNull();+ });+ it('Note 错误不会直接输出英文网络异常',()=>{+ const host=document.createElement('div');host.innerHTML=noteHtml('Failed to fetch',{variant:'error',size:'small',filled:true});+ expect(host.querySelector('[role=alert]')?.textContent).toContain('无法连接到 Peach');+ expect(host.querySelector('.geist-note-small.geist-note-filled')).not.toBeNull();+ expect(host.querySelector('button')).toBeNull();+ });+ it('Project Banner 包含处理入口且没有关闭键',()=>{+ const host=document.createElement('div');host.innerHTML=projectBannerHtml('扫描未完成',{variant:'warning',href:'/data-cleanup',label:'查看并处理'});+ expect(host.querySelector('.project-banner-warning')).not.toBeNull();+ expect(host.querySelector('a')?.getAttribute('href')).toBe('/data-cleanup');+ expect(host.querySelector('button')).toBeNull();+ });+});diff --git a/frontend/test/jobs.test.ts b/frontend/test/jobs.test.tsindex ce338690c..ae1f70f01 100644--- a/frontend/test/jobs.test.ts+++ b/frontend/test/jobs.test.ts@@ -4,6 +4,19 @@ import { watchJob, followJobProgress } from '../src/jobs';afterEach(() => { vi.useRealTimers(); sessionStorage.clear(); document.body.innerHTML = ''; });describe('后台任务状态恢复', () => {+ it('后台阶段说明随轮询更新并保留真实计数', async () => {+ vi.useFakeTimers();+ const host=document.createElement('div');document.body.append(host);+ let state={status:'running',job_id:'taste',checked:0,total:3,message:'分析浏览记录:已处理 0 / 3 条'};+ followJobProgress({host,active:()=>true,read:async()=>state,busy:()=>{},complete:()=>{},+ title:'读取浏览记录',note:text=>text,loading:text=>text,progress:(value,max)=>`${value}/${max}`});+ await vi.advanceTimersByTimeAsync(0);+ expect(host.textContent).toContain(state.message);+ state={...state,checked:2,message:'分析浏览记录:已处理 2 / 3 条'};+ await vi.advanceTimersByTimeAsync(4000);+ expect(host.textContent).toContain(state.message);+ expect(host.textContent).toContain('2/3');+ });it('页面重建后恢复来源进度并只接收一次完成回执', async () => {vi.useFakeTimers();const host = document.createElement('div'); document.body.append(host);diff --git a/frontend/test/quality-goals.test.tsx b/frontend/test/quality-goals.test.tsxindex 00c4ab5b3..adbf1dc16 100644--- a/frontend/test/quality-goals.test.tsx+++ b/frontend/test/quality-goals.test.tsx@@ -86,7 +86,7 @@ describe('高清版目标列表', () => {it('读取失败时把原因留在原位,用 error Note', async () => {await seedGoalsError('请求失败(500)');const { el } = show();- expect(el.querySelector('.geist-note-error')?.textContent).toContain('请求失败(500)');+ expect(el.querySelector('.geist-note-error')?.textContent).toContain('Peach 服务处理失败');expect(el.querySelector('[data-geist-empty-state]')).toBeNull();});diff --git a/frontend/test/stubs/legacy-core.ts b/frontend/test/stubs/legacy-core.tsindex 362f99ec8..2fe3dff8f 100644--- a/frontend/test/stubs/legacy-core.ts+++ b/frontend/test/stubs/legacy-core.ts@@ -3,6 +3,8 @@* 真实实现由 Peach 在浏览器里提供,node 里不存在。这里照抄它的**行为**而不是引用它:* 断言要能说明「island 用的是遗留层的格式化口径」,所以哨兵值(时长 0/负数 → `—`)* 必须一起复制过来,否则测试会放过一个把 `-1` 画成 `0:-1` 的回归。 */+// @ts-expect-error 测试直接复用正式错误映射。+export {requestErrorMessage} from '../../../web/js/core.js';export const LOC: Record<string, string> = {local: '本地','115': '115',diff --git a/frontend/test/stubs/legacy-ui.ts b/frontend/test/stubs/legacy-ui.tsindex 32f2cc8cc..7856eab73 100644--- a/frontend/test/stubs/legacy-ui.ts+++ b/frontend/test/stubs/legacy-ui.ts@@ -12,6 +12,8 @@ export const emptyStateHtml = (+ `<div class="es-icon" data-icon="${iconName}"></div>`+ `<div class="es-copy"><h3>${title}</h3><p>${description}</p></div>${options.actions || ''}</div>`;+// @ts-expect-error 横幅复用正式模板。+export {projectBannerHtml} from '../../../web/js/ui-components.js';export const fieldsetTitle = (id: string, title: string): string =>`<h3 class="geist-fieldset-title" id="${id}">${title}</h3>`;export const loadingDotsHtml = (label: string): string => `<span>${label}</span>`;diff --git a/src/peach/taste_history.py b/src/peach/taste_history.pyindex 34663b5d6..faee23222 100644--- a/src/peach/taste_history.py+++ b/src/peach/taste_history.py@@ -161,7 +161,7 @@ def _iso_from_unix_microseconds(value: int | float) -> str:return datetime.fromtimestamp(float(value) / 1_000_000, UTC).isoformat()-def _read_visits(snapshot: Path, _browser: str | None = None) -> list[HistoryVisit]:+def _read_visits(snapshot: Path, _browser: str | None = None, *, progress=None) -> list[HistoryVisit]:"""Use browserexport's maintained schema adapters and keep Peach's private DTO.The source database is already a consistent SQLite backup when this is called for a@@ -189,6 +189,8 @@ def _read_visits(snapshot: Path, _browser: str | None = None) -> list[HistoryVisif visit.metadata is not None:title = str(visit.metadata.title or "")visits.append(HistoryVisit(visit_key, visited_at, url, title))+ if progress and len(visits) % 1000 == 0:+ progress(len(visits))try:with snapshot.open("rb") as handle:@@ -258,14 +260,24 @@ def refresh_history(store_path: Path,*,host: str | None = None,+ progress=None,) -> list[dict[str, object]]:results: list[dict[str, object]] = []with _open_history_store(store_path, host) as (store, host, now):- for source in sources:+ for index, source in enumerate(sources):+ def report(count=0):+ if progress:+ progress(stage="reading", checked=count, total=None,+ message=f"读取浏览记录:第 {index + 1} / {len(sources)} 个浏览器资料,已读取 {count:,} 条")with tempfile.TemporaryDirectory(prefix="peach-history-") as temp_dir:snapshot = Path(temp_dir) / "history.sqlite"+ if progress:+ progress(stage="snapshot", checked=0, total=None,+ message=f"准备浏览器快照:第 {index + 1} / {len(sources)} 个资料")_consistent_copy(source.path, snapshot)- visits = _read_visits(snapshot, source.browser)+ report()+ visits = _read_visits(snapshot, source.browser, progress=report)+ report(len(visits))source_key = _source_key(source, host)path_hash = hashlib.sha256(str(source.path.resolve()).encode("utf-8")).hexdigest()store.execute(@@ -1104,7 +1116,7 @@ def _url_candidates(url: str) -> tuple[str | None, set[str], set[str]]:return domain or None, tags, creators-def analyze_history(store_path: Path, output_dir: Path, *, since: str | None = None) -> dict[str, object]:+def analyze_history(store_path: Path, output_dir: Path, *, since: str | None = None, progress=None) -> dict[str, object]:output_dir.mkdir(parents=True, exist_ok=True)query = ("SELECT v.source_key, v.visited_at, v.url, s.browser, s.profile "@@ -1127,6 +1139,12 @@ def analyze_history(store_path: Path, output_dir: Path, *, since: str | None = Ntotal = 0with closing(sqlite3.connect(store_path)) as db:source_count = db.execute("SELECT COUNT(*) FROM history_source").fetchone()[0]+ ceiling = db.execute("SELECT COUNT(*) FROM (" + query + ")", params).fetchone()[0]+ def report_analysis():+ if progress:+ progress(stage="analyzing", checked=total, total=ceiling,+ message=f"分析浏览记录:已处理 {total:,} / {ceiling:,} 条")+ report_analysis()for source_key, visited_at, url, browser, profile in db.execute(query, params):total += 1min_time = visited_at if min_time is None or visited_at < min_time else min_time@@ -1148,6 +1166,12 @@ def analyze_history(store_path: Path, output_dir: Path, *, since: str | None = Ncreator_visits[creator] += 1creator_urls[creator].add(url_hash)creator_sources[creator].add(source_label)+ if total % 1000 == 0:+ report_analysis()+ report_analysis()++ if progress:+ progress(stage="reporting", checked=0, total=None, message="正在生成口味分析报告与候选清单")stamp = datetime.now().astimezone().strftime("%Y%m%d-%H%M%S")tag_path = output_dir / f"taste-tag-candidates-{stamp}.csv"diff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex 4d8b73a4b..55852055d 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -1036,7 +1036,7 @@ def _external_search_payload(search) -> dict:"url": search.url, "evidence": search.evidence}-def w_follow_resolve(contract, body) -> dict:+def w_follow_resolve(contract, body, *, progress=None) -> dict:"""把粘进来的每一行解析成「可以添加什么」,但**不添加**。一行是链接就直接认;不是链接就当成名字或 id 拿去各来源查一遍。两种都只返回结果,@@ -1044,8 +1044,12 @@ def w_follow_resolve(contract, body) -> dict:自动登记等于替用户做决定。"""if body.get("background"):- return contract.follow_resolve_job.start_result(- lambda: w_follow_resolve(contract, {**body, "background": False}))+ job = contract.follow_resolve_job+ def work(job_id):+ result = w_follow_resolve(contract, {**body, "background": False},+ progress=lambda **fields: job.update(job_id, **fields))+ job.update(job_id, **result, status="complete", completed_at=time.time())+ return job.start(work, restart=True, initial={"message": "正在准备查找关注来源"})raw = body.get("lines")if isinstance(raw, str):raw = raw.splitlines()@@ -1060,7 +1064,10 @@ def w_follow_resolve(contract, body) -> dict:known = {(row["provider"], canonical_source_ref(row["provider"], row["ref"])) for row in(_source_payload(r) for r in _existing_sources(contract))}results = []- for line in lines:+ for index, line in enumerate(lines):+ if progress:+ progress(checked=index, total=len(lines),+ message=f"查找关注来源:已完成 {index} / {len(lines)} 行,正在解析第 {index + 1} 行")try:parsed = parse_source_url(line)except FollowSourceError as url_error:diff --git a/src/peach/web_links.py b/src/peach/web_links.pyindex 18c30a133..81e56ebd3 100644--- a/src/peach/web_links.py+++ b/src/peach/web_links.py@@ -160,7 +160,7 @@ def w_links_check(contract: LinkContract, body=None):))-def w_links_prune(contract: LinkContract, body):+def w_links_prune(contract: LinkContract, body, *, progress=None):"""删掉上一次检查判定为 gone 的链接。只接受**刚跑完的那一次**检查的 `check_id`:拿一份放了半天的清单去删,删的可能是@@ -170,8 +170,12 @@ def w_links_prune(contract: LinkContract, body):if body.get("confirm") is not True:return {"ok": False, "error": "需要 confirm"}if body.get("background"):- return contract.link_prune_job.start_result(- lambda: w_links_prune(contract, {**body, "background": False}))+ job = contract.link_prune_job+ def work(job_id):+ result = w_links_prune(contract, {**body, "background": False},+ progress=lambda **fields: job.update(job_id, **fields))+ job.update(job_id, **result, status="complete" if result.get("ok") else "failed", completed_at=time.time())+ return job.start(work, restart=True, initial={"message": "正在核对失效链接清单"})state = contract.link_check.snapshot()if state is None or state["status"] != "complete":return {"ok": False, "error": "没有已完成的检查结果"}@@ -180,11 +184,15 @@ def w_links_prune(contract: LinkContract, body):planned = [dict(item) for item in state["gone"]]confirmed, recovered = [], []- for item in planned:+ for index, item in enumerate(planned):+ if progress:+ progress(checked=index, total=len(planned), message=f"重验失效链接:已检查 {index} / {len(planned)} 条")status, note = _probe(item["url"])(confirmed if link_verdict(status, note) == "gone" else recovered).append(item)removed = 0+ if progress:+ progress(checked=len(planned), total=len(planned), message=f"重验结束:准备删除 {len(confirmed)} 条,保留 {len(recovered)} 条")if confirmed:# 整批删除走同一个写事务:要么这一次判定的 gone 全部落库,要么一条都不落。with contract.write_transaction() as connection:diff --git a/src/peach/web_resource_sync.py b/src/peach/web_resource_sync.pyindex 89ee15262..28d883907 100644--- a/src/peach/web_resource_sync.py+++ b/src/peach/web_resource_sync.py@@ -276,12 +276,16 @@ def _resource_orphan_plan(contract: ResourceSyncContract, excluded_ids: Sequence}-def clean_resource_orphans(contract: ResourceSyncContract) -> dict:+def clean_resource_orphans(contract: ResourceSyncContract, *, progress=None) -> dict:+ if progress:+ progress(checked=0, total=None, message="正在核对可重建缓存清单")plan = _resource_orphan_plan(contract)removed = 0reclaimed = 0blocked = []- for kind, path, size in plan["files"]:+ for index, (kind, path, size) in enumerate(plan["files"]):+ if progress:+ progress(checked=index, total=len(plan["files"]), message=f"清理缓存:已处理 {index} / {len(plan['files'])} 个")try:path.unlink(missing_ok=True)removed += 1@@ -289,6 +293,8 @@ def clean_resource_orphans(contract: ResourceSyncContract) -> dict:except OSError as error:blocked.append({"kind": kind, "name": path.name,"reason": error.strerror or str(error)})+ if progress:+ progress(checked=0, total=None, message="正在整理缓存目录并汇总释放空间")for directory in sorted(plan["dirs"], key=lambda item: len(item.parts), reverse=True):try:shutil.rmtree(directory)@@ -398,14 +404,18 @@ def _recheck_resource_scan_ids(contract: ResourceSyncContract, asset_ids: Sequenreturn missing-def w_resource_sync_apply(contract: ResourceSyncContract, body):+def w_resource_sync_apply(contract: ResourceSyncContract, body, *, progress=None):if not configured_cloud_locations():raise ValueError("请先在配置页添加网盘来源")if body.get("confirm") is not True:raise ValueError("resource sync requires confirmation")if body.get("background"):- return contract.resource_apply_job.start_result(- lambda: w_resource_sync_apply(contract, {**body, "background": False}))+ job = contract.resource_apply_job+ def work(job_id):+ result = w_resource_sync_apply(contract, {**body, "background": False},+ progress=lambda **fields: job.update(job_id, **fields))+ job.update(job_id, **result, status="complete", completed_at=time.time())+ return job.start(work, restart=True, initial={"message": "正在重新核对来源挂载与缺失文件"})scan_id = str(body.get("scan_id") or "")if scan_id:state = contract.resource_scan.snapshot()@@ -423,6 +433,8 @@ def w_resource_sync_apply(contract: ResourceSyncContract, body):scan = _scan_missing_resources(contract)missing_ids = scan["missing_ids"]if missing_ids:+ if progress:+ progress(checked=0, total=None, message=f"正在把 {len(missing_ids)} 个确认缺失的条目移入回收站")with contract.write_transaction() as connection:stamp = time.time()connection.executemany(@@ -430,7 +442,7 @@ def w_resource_sync_apply(contract: ResourceSyncContract, body):[(stamp, asset_id) for asset_id in missing_ids],)contract.cache_bust()- cleanup = clean_resource_orphans(contract) if body.get("clean_cache", True) else {+ cleanup = clean_resource_orphans(contract, progress=progress) if body.get("clean_cache", True) else {"cache_removed": 0, "bytes_reclaimed": 0, "cache_blocked": [],}return {"ok": True, "moved_to_trash": len(missing_ids),diff --git a/src/peach/web_stats.py b/src/peach/web_stats.pyindex 12c183c32..cb5754808 100644--- a/src/peach/web_stats.py+++ b/src/peach/web_stats.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport jsonimport reimport shutil+import timefrom datetime import UTC, datetime, timedelta@@ -112,17 +113,24 @@ def q_taste(contract: WebContract, args=None):return payload-def w_taste_refresh(contract: WebContract, body):+def w_taste_refresh(contract: WebContract, body, *, progress=None):if body.get("background"):- return contract.taste_refresh_job.start_result(- lambda: w_taste_refresh(contract, {**body, "background": False}))+ job = contract.taste_refresh_job+ def work(job_id):+ result = w_taste_refresh(contract, {**body, "background": False},+ progress=lambda **fields: job.update(job_id, **fields))+ job.update(job_id, **result, status="complete", message="口味分析已更新", completed_at=time.time())+ return job.start(work, restart=True, initial={+ "stage": "discovering", "message": "正在查找 Peach 主机上的浏览器资料"})window = str(body.get("window") or "all")sources = discover_history_sources()- results = refresh_history(sources, contract.taste_history_store) if sources else []+ results = refresh_history(sources, contract.taste_history_store, progress=progress) if sources else []if contract.taste_history_store.is_file():- analysis = analyze_history(contract.taste_history_store, contract.taste_history_root)+ analysis = analyze_history(contract.taste_history_store, contract.taste_history_root, progress=progress)write_manifest(contract.taste_history_manifest, results, analysis)contract.cache_bust()+ if progress:+ progress(stage="dashboard", checked=0, total=None, message="正在汇总口味分布、标签与创作者排名")return {"refresh": results, "dashboard": q_taste(contract, {"window": window})}diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex cfc811950..c3e057907 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -1956,25 +1956,20 @@ class FollowWebSourceTests(unittest.TestCase):def test_the_page_says_where_the_credential_actually_lands(self):# 从 Mac 浏览 Windows 实例时,凭据落在 Windows 上——不能写成「本机」。- self.assertPageContains("运行 Peach 的那台机器")+ self.assertPageContains("运行 Peach 的电脑")self.assertPageContains("Windows 上不收紧文件权限")self.assertPageContains("row.path")self.assertPageContains("row.world_readable")- def test_credential_explanation_uses_an_accessible_viewport_clamped_tooltip(self):+ def test_credential_information_card_stays_inside_the_viewport(self):self.assertPageContains('class="fdescinfo" data-fdesc-tooltip')self.assertPageContains('aria-label="凭据存放位置说明"')- self.assertPageContains('id="follow-credential-tooltip" role="tooltip" hidden')- self.assertPageContains("tooltipTrigger.setAttribute('aria-describedby',tooltip.id)")- self.assertPageContains("tooltipTrigger.removeAttribute('aria-describedby')")+ self.assertPageContains('id="follow-credential-tooltip" role="dialog"')+ self.assertPageContains("trigger.setAttribute('aria-controls',panel.id)")+ self.assertPageContains("panel.setAttribute('popover','manual')")self.assertPageContains("event.key==='Escape'")- tooltip = self.page[self.page.index(".fdescpop{"):]- tooltip = tooltip[:tooltip.index("}")]- self.assertIn("position:fixed", tooltip)- self.assertIn("max-width:min(250px,calc(100vw - 16px))", tooltip)- self.assertIn("pointer-events:none", tooltip)- self.assertNotIn("340px", tooltip)- self.assertPageContains("innerWidth-box.width-8")+ self.assertPageContains("max-width:calc(100vw - 16px)")+ self.assertPageContains("innerWidth-width-8")def test_author_aliases_use_the_real_geist_collapse_motion(self):self.assertPageContains(".fcollapse{overflow:hidden;transition:height .2s ease-in-out}")@@ -2530,7 +2525,7 @@ class FollowWebSourceTests(unittest.TestCase):self.assertPageContains("${followCheckReport?followCheckFailNote(followCheckReport):''}")for needle in ("新增 <b>", "更新 <b>", "个来源没有更新", "没有任何更新","个失败", "fcheckfail", "没有更多历史内容",- "data-follow-report-dismiss"):+ "geist-note"):self.assertPageContains(needle)# 失败要说清是哪个站,不能让用户去猜 `rule34xxx` 是什么。self.assertPageContains("row.provider_label||row.provider")@@ -2837,7 +2832,7 @@ class FollowWebSourceTests(unittest.TestCase):self.assertPageContains("source:followMediaSourceLabel(image,item)")self.assertPageContains("const resolution=image?.naturalWidth&&image?.naturalHeight")self.assertPageContains("reveal.hidden=!asset")- self.assertPageContains("const target=reveal.hidden?title:reveal;target.focus()")+ self.assertPageContains("wireContextCard(")self.assertPageContains(".photodetail>button[hidden]{display:none}")self.assertPageLacks("if(!asset){toggle.hidden=true;dismiss();return}","在线图片的整个信息入口仍被隐藏")diff --git a/tests/test_taste_history.py b/tests/test_taste_history.pyindex 02feb3311..e024ef1aa 100644--- a/tests/test_taste_history.py+++ b/tests/test_taste_history.py@@ -150,13 +150,22 @@ class TasteHistoryTests(unittest.TestCase):HistorySource("safari", "iCloud", safari),]store = self.root / "sources" / "history.sqlite"- first = refresh_history(sources, store, host="test-host")+ updates = []+ first = refresh_history(sources, store, host="test-host", progress=lambda **state: updates.append(state))+ self.assertEqual(updates[-1]["checked"], first[-1]["visits"])+ self.assertIsNone(updates[-1]["total"])+ self.assertNotIn("secret", str(updates))second = refresh_history(sources, store, host="test-host")self.assertEqual(sum(item["added"] for item in first), 3)self.assertEqual(sum(item["added"] for item in second), 0)output = self.root / "review"- result = analyze_history(store, output)+ result = analyze_history(store, output, progress=lambda **state: updates.append(state))+ measured = [state for state in updates if state["stage"] == "analyzing"]+ self.assertEqual(measured[0]["checked"], 0)+ self.assertEqual(measured[-1]["checked"], result["visits"])+ self.assertEqual(measured[-1]["total"], result["visits"])+ self.assertEqual(updates[-1]["stage"], "reporting")report = Path(result["report"]).read_text(encoding="utf-8")self.assertIn("足系", report)self.assertIn("cosplay", report)diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 727d43232..f94e3271f 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -2551,7 +2551,7 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains(".confighelp a:hover{text-decoration:underline;")for selector, declarations in re.findall(r'([^{}]+)\{([^{}]*)\}', stylesheet_source()):if "text-decoration:underline" in declarations:- self.assertIn(":hover", selector)+ self.assertTrue(":hover" in selector or selector.strip() == ".project-banner>a", selector)def test_configuration_uses_fieldset_surfaces_and_shared_select(self):css = stylesheet_source()@@ -3818,7 +3818,7 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains('aria-label="图片详情" title="图片详情">${icon(\'info\')}</button>')self.assertPageContains('.runtimegate{display:grid;grid-template-columns:16px minmax(0,1fr) auto;align-items:center;gap:12px')self.assertPageContains('.runtimegate>svg{width:16px;height:16px;flex:none;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}')- self.assertPageContains('.geist-note>svg{width:16px;height:16px;margin-top:2px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}')+ self.assertPageContains('.geist-note>svg{width:16px;height:24px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}')self.assertPageContains('.runtimegate a{grid-column:2/-1}')def test_project_web_ui_skill_keeps_future_changes_on_shared_primitives(self):@@ -4214,7 +4214,7 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("if(staticManageCount)countRow.classList.remove('is-stuck')")self.assertPageContains(".count.manage-static{position:relative;top:auto;z-index:1}")self.assertPageContains("if(!response.ok){")- self.assertPageContains("throw new Error(detail||`请求失败(${response.status})`)")+ self.assertPageContains("throw new Error(requestErrorMessage(detail,response.status))")self.assertPageContains("catch(error){actionFailure('批量操作',error)}")self.assertPageContains("wireJunkCards($('#grid'));paintSelection();return")self.assertPageContains("actionFailure('操作',error)")@@ -5765,15 +5765,9 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("tagPressed(filterState.tag,t.k)")self.assertPageContains("${esc(tagLabel(t))} <b data-untag=\"${esc(t)}\">✕</b>")# fwarn 提供 dismiss(会话内记忆),关闭钮样式与 toast 关闭钮同量纲。- self.assertPageContains("data-fwarn-dismiss")- self.assertPageContains("sessionStorage.setItem('peach-fwarn-dismissed','1')")- self.assertPageContains(".fwarn .wclose,.fcheckreport .wclose{width:24px;height:24px;padding:0;border:0;")- # 报告条的红发丝边和微红底由共用 Note 提供,本页只补关闭键那一列。- self.assertPageContains(- ".fcheckreport,.fwarn{grid-template-columns:16px minmax(0,1fr) 24px;margin:10px 0 14px}")- self.assertPageContains(- ".geist-note-error{border-color:color-mix(in srgb,var(--drop) 30%,transparent);"- "background:color-mix(in srgb,var(--drop) 7%,transparent)}")+ self.assertPageLacks("data-fwarn-dismiss")+ self.assertPageContains(".fcheckreport,.fwarn{grid-template-columns:16px minmax(0,1fr);")+ self.assertPageContains(".geist-note-error{--feedback-color:var(--drop);")self.assertPageLacks("border-left:2px solid var(--drop)")# 来源行状态徽章(ok 绿 tint / 失败红 tint / 未检查灰)。self.assertPageContains('<span class="sbadge ${badge}" title="${esc(stateTitle)}"><i aria-hidden="true"></i>')@@ -5811,7 +5805,7 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageLacks("wireReviewScrollers")self.assertPageLacks("reviewscrollbtns")self.assertPageContains(".settinggroup>h3{margin:0;padding:14px 0 10px;font-size:var(--fs-lg);font-weight:600;color:var(--ink)}")- self.assertPageContains(".settinggroup .settingrow{margin:0 -16px;padding-left:16px;padding-right:16px}")+ self.assertPageContains(".settinggroup .settingrow{margin:0;padding-left:0;padding-right:0}")self.assertCode(".pagetitle,.listtitle,.managetitle,.index .ihead h2,.playlistpage h2{""\n font-size:var(--fs-3xl);line-height:1.25;letter-spacing:-.01em;font-weight:600}")@@ -5974,7 +5968,7 @@ class WebUiSourceTests(unittest.TestCase):"@media (max-width:760px){.iconswitch.themeswitch label{width:44px;height:44px}}")# 分隔线属于整块卡片,铺到框边再断。self.assertCode(- ".settinggroup .settingrow+.sidebarsetting{margin:0 -16px;padding:14px 16px 0;"+ ".settinggroup .settingrow+.sidebarsetting{margin:0;padding:14px 0 0;""border-top:1px solid var(--line-soft)}")def test_search_menu_has_local_history_and_recommendations(self):@@ -7392,7 +7386,7 @@ class WebUiSourceTests(unittest.TestCase):# 标题的 tabindex,以及无条件 reveal.focus() 不许回来。bcf112e 改了实现只更新了# tests/test_follow_web.py,这里的旧断言留在原地,master 上因此挂了一段时间。self.assertPageContains(- "queueMicrotask(()=>{const target=reveal.hidden?title:reveal;target.focus()})")+ "wireContextCard(")self.assertPageContains('<h2 id="photoDetailTitle" data-middle-truncate tabindex="-1">',"标题要接得住焦点,缺 tabindex=-1 时 reveal 隐藏那条路径等于没聚焦")diff --git a/web/app.js b/web/app.jsindex 374d498a9..e06537c60 100644--- a/web/app.js+++ b/web/app.js@@ -11,9 +11,9 @@ import { javImageKind, normalizeJavImage, normalizeJavLayout, normalizeJavPreferimport {attachOverlayScrollbar, breadcrumbHtml, checkboxHtml, closeAnchoredMenu, confirmModal, emptyStateHtml, fieldsetTitle,fillSkeletonTier, fitSkeleton, iconSwitchHtml, indexSkeletonHtml, loadingDotsHtml,- mediaViewButtonsHtml, noteHtml, progressHtml, scrollerHtml, searchInputHtml, selectFieldHtml,+ mediaViewButtonsHtml, noteHtml, progressHtml, gaugeHtml, scrollerHtml, searchInputHtml, selectFieldHtml,setActionBusy, skeletonHtml, spinnerHtml, wireAnchoredMenu, wireBusyActions, wireCollapse,- wireIconSwitch, wireOverlayScrollbars, wireScrollers, wireSelectField,+ wireIconSwitch, wireOverlayScrollbars, wireScrollers, wireSelectField, wireContextCard,} from './js/ui-components.js';initMiddleTruncate(document);@@ -2945,7 +2945,7 @@ async function openStats(push=true){`<div class="insightempty">${emptyStateHtml('tags','还没有标签来源','刮削或手动打标之后,这里会显示每个来源覆盖了多少视频。')}</div>`);const storageTable=(d.storage_volumes||[]).length?`<table class="insightdatatable"><thead><tr><th>位置</th><th>已用</th><th>可用</th><th>使用率</th></tr></thead><tbody>${(d.storage_volumes||[]).map(row=>{const measured=row.total!=null, usedPct=measured?pct(row.used,row.total):0;- return `<tr><th scope="row"><span>${esc(row.label)}</span><small>${row.root?esc(row.root):'未映射'}</small></th><td>${measured?gb(row.used):'—'}</td><td>${measured?gb(row.free):'—'}</td><td>${measured?usedPct+'%':(row.online?'容量未取得':'离线')}</td></tr>`}).join('')}</tbody></table>`+ return `<tr><th scope="row"><span>${esc(row.label)}</span><small>${row.root?esc(row.root):'未映射'}</small></th><td>${measured?gb(row.used):'—'}</td><td>${measured?gb(row.free):'—'}</td><td>${measured?gaugeHtml(`${row.label}空间使用率`,row.used,row.total)+usedPct+'%':(row.online?'容量未取得':'离线')}</td></tr>`}).join('')}</tbody></table>`:emptyStateHtml('hard-drive','还没有存储来源','添加媒体文件夹后,这里会显示存储空间。');$('#stats').innerHTML=`<div class="insightpage statsdashboard" data-stats-dashboard>@@ -3102,7 +3102,7 @@ async function wireLinkManager(){function wirePruneProgress(){return wireOperationProgress({host:$('#link-manager'),path:'/api/links/prune',key:'peach-link-prune-job',title:'正在重验并删除失效链接…',busy:running=>{const button=$('#linkPrune');if(button){setActionBusy(button,running);if(!running)button.textContent='重试删除失效链接'}},- complete:out=>{$('#linkCheckResult').innerHTML=noteHtml(`已删除 ${out.removed} 条;保留 ${out.recovered} 条未确认失效的链接。`,{label:'完成'})}});+ complete:out=>{$('#linkCheckResult').innerHTML=noteHtml(`已删除 ${out.removed} 条;保留 ${out.recovered} 条未确认失效的链接。`,{variant:'success',label:'完成'})}});}function resourceSyncMarkup(){return `<section class="resourcesync" id="resource-sync" aria-labelledby="resourceSyncTitle">@@ -3181,7 +3181,7 @@ async function wireResourceSync(){function wireResourceApplyProgress(){return wireOperationProgress({host:$('#resource-sync'),path:'/api/resource-sync/apply',key:'peach-resource-apply-job',title:'正在核对来源、同步并清理缓存…',busy:running=>{const button=$('#resourceApply');if(button){setActionBusy(button,running);if(!running)button.textContent='同步并清理'}},- complete:out=>{$('#resourceSyncResult').innerHTML=noteHtml(`已把 ${out.moved_to_trash} 项移入回收站,清理 ${out.cache_removed} 个缓存,释放 ${fmtSize(out.bytes_reclaimed||0)}。`,{label:'完成'})}});+ complete:out=>{$('#resourceSyncResult').innerHTML=noteHtml(`已把 ${out.moved_to_trash} 项移入回收站,清理 ${out.cache_removed} 个缓存,释放 ${fmtSize(out.bytes_reclaimed||0)}。`,{variant:'success',label:'完成'})}});}/* 旧直达 URL 仍然可用,落点跟着面板一起搬到数据管理。 */async function openResourceSync(push=true){@@ -4503,19 +4503,17 @@ function followCheckFailNote(report){const exhausted=rows.filter(r=>r.exhausted);const evidence=rows.filter(r=>r.evidence_error);if(!failed.length&&!evidence.length&&!exhausted.length)return '';- const dismiss=`<button type="button" class="wclose" data-follow-report-dismiss- aria-label="关闭检查结果">${icon('x')}</button>`;const ended=exhausted.length?`<div class="geist-note geist-note-secondary fcheckreport" role="note">${icon('info')}<div><p><b>${exhausted.length} 个来源没有更多内容</b></p>${exhausted.map(row=>`<p class="fchecknote">${esc([row.provider_label||row.provider,row.ref]- .filter(Boolean).join(' '))}:没有更多历史内容</p>`).join('')}</div>${dismiss}</div>`:'';+ .filter(Boolean).join(' '))}:没有更多历史内容</p>`).join('')}</div></div>`:'';const errors=failed.length||evidence.length?`<div class="geist-note geist-note-error fcheckreport" role="alert">${icon('alert')}<div>${failed.length?`<p><b>${failed.length} 个来源检查失败</b></p>`:''}${failed.map(row=>`<p class="fcheckfail"><strong>${esc(row.provider_label||row.provider||'')}</strong><strong>${esc(row.author||row.label||row.ref||'')}</strong>${row.provider?':':''}${esc(row.error||'未说明原因')}</p>`).join('')}${evidence.length?`<p class="fchecknote">候选已入库,但这一次的原始响应没有留档:${esc(evidence[0].evidence_error)}</p>`:''}- </div>${dismiss}</div>`:'';+ </div></div>`:'';return `<div class="fcheckreports">${ended}${errors}</div>`;}@@ -4617,8 +4615,8 @@ function renderFollow(){topTags.map(([key,label,n])=>`<button class="pill r34-${esc(groupTagType(groups,key))}" data-follow-tag="${esc(key)}" aria-pressed="${followTags.has(key)}">${esc(label)}${n?` <span class="n mono">${n}</span>`:''}</button>`).join(''):''}</div>- ${broken.length&&!sessionStorage.getItem('peach-fwarn-dismissed')- ?`<div class="geist-note geist-note-error fwarn" role="alert">${icon('alert')}<span>${broken.length} 个来源上次检查失败,去<button class="flink" data-follow-manage>管理关注</button>看原因。</span><button class="wclose" data-fwarn-dismiss title="本次会话不再显示" aria-label="关闭提醒">${icon('x')}</button></div>`:''}+ ${broken.length+ ?`<div class="geist-note geist-note-error fwarn" role="alert">${icon('alert')}<span>${broken.length} 个来源上次检查失败,去<button class="flink" data-follow-manage>管理关注</button>看原因。</span></div>`:''}<div class="followlist${followMediaView==='images'?' followphotowall':''}">${visible.length?visible.map(group=>{const source=sourceOf(group),siblings=source&&authorSources.get(source.author_key)||[];return followCard(group,siblings)}).join('')@@ -4660,8 +4658,7 @@ function renderFollow(){applyFollowView()});$('#stats').querySelectorAll('[data-follow-manage]').forEach(button=>button.onclick=()=>openFollowManage());- $('#stats').querySelectorAll('[data-fwarn-dismiss]').forEach(button=>button.onclick=()=>{- sessionStorage.setItem('peach-fwarn-dismissed','1');renderFollow()});+}/* 往回抓到哪儿了。不说的话,用户点一次只看到列表变长一点,不知道自己走到第几页,@@ -4719,7 +4716,9 @@ async function wireOperationProgress({host,path,key,title,busy,complete}){storageKey:key,title,busy,watchIdle:false,complete:report=>{if(report.status==='failed'){marker.innerHTML=noteHtml(report.error||'任务失败',{variant:'error',label:'任务失败'});return}complete(report)},note:text=>noteHtml(text,{label:'任务状态'}),- loading:text=>loadingDotsHtml(text),progress:()=>''});+ loading:text=>loadingDotsHtml(text),+ container:content=>`<section class="followtask" data-geist-fieldset aria-label="任务进度"><div class="geist-fieldset-content">${content}</div></section>`,+ progress:(value,max)=>progressHtml(`已处理 ${value} / ${max}`,value,max)});}function wireTasteProgress(){const button=$('#stats').querySelector('[data-taste-refresh]');@@ -5078,11 +5077,11 @@ function renderFollowManage(credentials){<div class="fsechead"><h3>凭据</h3>${needCred.length?`<span class="fmeta warn">${needCred.length} 个待配置</span>`:''}</div><div class="frows">${creds.map(followCredentialRow).join('')}</div>- <p class="fdesc"><b>存放位置与权限+ <div class="fdesc"><b>存放位置与权限<button type="button" class="fdescinfo" data-fdesc-tooltiparia-label="凭据存放位置说明">${icon('info')}</button></b><span>Windows 上不收紧文件权限</span>- <span class="fdescpop" id="follow-credential-tooltip" role="tooltip" hidden>存放在<b>运行 Peach 的那台机器</b>上,不是浏览器所在机器;不进 Git、URL、日志或 ledger。NTFS 的访问控制走 ACL,<code>chmod</code> 在那里没有效果;POSIX 上建成 0600。</span></p>+ <div class="context-card" id="follow-credential-tooltip" role="dialog" aria-label="凭据存放信息" hidden><h3>凭据存放信息</h3><dl><dt>所在设备</dt><dd>运行 Peach 的电脑</dd><dt>访问权限</dt><dd>由该电脑的文件访问权限控制</dd><dt>其他设备</dt><dd>浏览器不会保存这份凭据文件</dd></dl></div></div></section></div></div>`;wireFollowManage(creds);@@ -5181,30 +5180,7 @@ function wireFollowManage(creds=[]){renderFollowSrcFilter(root.querySelector('#followSrcFilter'),creds);const tooltipTrigger=root.querySelector('[data-fdesc-tooltip]');const tooltip=root.querySelector('#follow-credential-tooltip');- if(tooltipTrigger&&tooltip){- let tooltipHovered=false,tooltipFocused=false;- const hideTooltip=()=>{- tooltip.hidden=true;tooltipTrigger.removeAttribute('aria-describedby');- window.removeEventListener('resize',hideTooltip);- window.removeEventListener('scroll',hideTooltip,true)};- const hideTooltipIfIdle=()=>{if(!tooltipHovered&&!tooltipFocused)hideTooltip()};- const showTooltip=()=>{- tooltip.hidden=false;tooltipTrigger.setAttribute('aria-describedby',tooltip.id);- tooltip.style.left='0px';tooltip.style.top='0px';- const anchor=tooltipTrigger.getBoundingClientRect(),box=tooltip.getBoundingClientRect();- const left=Math.max(8,Math.min(anchor.left+(anchor.width-box.width)/2,innerWidth-box.width-8));- let top=anchor.top-box.height-10;- if(top<8)top=Math.min(innerHeight-box.height-8,anchor.bottom+10);- tooltip.style.left=left+'px';tooltip.style.top=Math.max(8,top)+'px';- window.addEventListener('resize',hideTooltip);- window.addEventListener('scroll',hideTooltip,{capture:true,passive:true})};- tooltipTrigger.addEventListener('pointerenter',()=>{tooltipHovered=true;showTooltip()});- tooltipTrigger.addEventListener('pointerleave',()=>{tooltipHovered=false;hideTooltipIfIdle()});- tooltipTrigger.addEventListener('focus',()=>{tooltipFocused=true;showTooltip()});- tooltipTrigger.addEventListener('blur',()=>{tooltipFocused=false;hideTooltipIfIdle()});- tooltipTrigger.addEventListener('keydown',event=>{- if(event.key==='Escape'){tooltipHovered=false;tooltipFocused=false;hideTooltip();tooltipTrigger.blur()}});- }+ if(tooltipTrigger&&tooltip)wireContextCard(tooltipTrigger.closest('.fdesc'),tooltipTrigger,tooltip);/* 作者别名和凭据行都走 Geist Collapse,两处同一份实现。凭据行的 `details.fcred`必须是 block:flex 行布局接不上 Collapse 的高度过渡。 */wireCollapse(root,'details.faliasmanager','follow-alias-collapse');@@ -5378,8 +5354,8 @@ function wireFollowManage(creds=[]){});root.querySelectorAll('[data-follow-view]').forEach(button=>button.onclick=()=>openFollow());- root.querySelectorAll('[data-follow-report-dismiss]').forEach(button=>button.onclick=()=>{- followCheckReport=null;root.querySelector('.fcheckreports')?.remove()});++}/* 查找结果先摆出来由人勾选,不自动登记:发现要联网,结果也可能不止一个,@@ -6209,13 +6185,11 @@ function wirePhotoDetail(box,items,index){if(!asset&&image&&!image.complete)image.addEventListener('load',()=>{if(painted===at)paint(at)},{once:true});};- const dismiss=returnFocus=>{panel.hidden=true;toggle.setAttribute('aria-expanded','false');+ const context=wireContextCard(box,toggle,panel);+ const dismiss=returnFocus=>{context.hide();toggle.setAttribute('aria-expanded','false');if(returnFocus&&document.contains(toggle))toggle.focus()};const dismissOutside=target=>{if(panel.hidden||toggle.contains(target)||panel.contains(target))return false;dismiss();return true};- toggle.onclick=()=>{if(panel.hidden){panel.hidden=false;toggle.setAttribute('aria-expanded','true');- queueMicrotask(()=>{const target=reveal.hidden?title:reveal;target.focus()})}- else dismiss()};reveal.onclick=()=>{if(reveal.dataset.photoReveal)revealSource(Number(reveal.dataset.photoReveal),status,{button:reveal})};paint(index);return {paint,dismiss,dismissOutside,isOpen:()=>!panel.hidden};@@ -6224,6 +6198,7 @@ function wirePhotoDetail(box,items,index){function closePhotoLightbox(){if(!activeLightbox)return;document.removeEventListener('keydown',photoLightKeys,true);+ activeLightbox.detail?.dismiss();activeLightbox.resize?.disconnect();activeLightbox.main.destroy(true,true);activeLightbox.strip.destroy(true,true);activeLightbox.box.remove();activeLightbox=null;diff --git a/web/css/04-manage.css b/web/css/04-manage.cssindex d5ce6a624..302a0ee2e 100644--- a/web/css/04-manage.css+++ b/web/css/04-manage.css@@ -143,8 +143,6 @@.scraping-source{min-width:0}.scraping-source .geist-fieldset-footer{flex-wrap:wrap}@media(max-width:600px){.scraping-page{--control-h:44px}.scraping-source button{min-height:44px}.scraping-cookie-method span{height:44px}}-.library-processing-banner{--control-h:32px;display:flex;align-items:center;justify-content:center;gap:12px;padding:16px;margin-bottom:16px;background:var(--hover);color:var(--ink);font-size:var(--fs-lg);flex-wrap:wrap}-.library-processing-banner .geist-button{border-radius:var(--pill-radius);font-size:var(--fs-md)}#libraryProcessing{scroll-margin-top:80px}.reviewbulktoolbar{width:100%;padding-block:0;margin-bottom:0}diff --git a/web/css/16-settings.css b/web/css/16-settings.cssindex 3f38765dc..761cc2e0e 100644--- a/web/css/16-settings.css+++ b/web/css/16-settings.css@@ -40,7 +40,7 @@ body.settings-open{overflow:hidden}.settinggroup{margin:16px 0 0;border:1px solid var(--field-ring);border-radius:var(--floating-radius);background:var(--ground);padding:0 16px 12px}.settinggroup>h3{margin:0;padding:14px 0 10px;font-size:var(--fs-lg);font-weight:600;color:var(--ink)}-.settinggroup .settingrow{margin:0 -16px;padding-left:16px;padding-right:16px}+.settinggroup .settingrow{margin:0;padding-left:0;padding-right:0}/* 布尔开关用 Geist Toggle 而不是原生复选框(取证 vercel-geist-semantics-measured.md):中号 36×20 轨道 + 17px 圆点,关 = 灰轨道圆点靠左,开 = 主题蓝圆点靠右;Geist 的「Switch」是分段选择器(radio 语义),布尔开关的正确控件叫 Toggle。 */@@ -67,7 +67,7 @@ body.settings-open{overflow:hidden}@media (max-width:760px){.iconswitch.themeswitch label{width:44px;height:44px}}/* 同一组里排在设置行后面的分区自带分隔线。线属于整块卡片,所以和 .settingrow 一样用负边距铺到框边,不在正文宽度里断一截。 */-.settinggroup .settingrow+.sidebarsetting{margin:0 -16px;padding:14px 16px 0;+.settinggroup .settingrow+.sidebarsetting{margin:0;padding:14px 0 0;border-top:1px solid var(--line-soft)}.sidebarsetting{display:grid;gap:12px;padding:0}.sidebarsetting>span b,.sidebarsetting>span small{display:block}.sidebarsetting>span small{margin-top:3px;color:var(--muted);line-height:1.45}.sidebarorder{display:grid;gap:6px}/* 这一列的行、下面那个下拉和「添加」按钮同高:它们是同一张清单的三段,差几像素就看得出是两拨控件。34px 的图标钮加上下 1px 内边距和 1px 边框正好是 --control-h。 */diff --git a/web/css/20-offdisk.css b/web/css/20-offdisk.cssindex d88861ed9..0fa48ea8b 100644--- a/web/css/20-offdisk.css+++ b/web/css/20-offdisk.css@@ -9,3 +9,7 @@.gate.offline span{max-width:34ch;text-align:center;line-height:1.6}.gate.offline .chip{cursor:pointer;margin-top:4px}++.gate.offline{box-sizing:border-box;min-height:220px;padding:24px;background:var(--ground);color:var(--ink)}+.gate.offline>svg{width:32px;height:32px;flex:none;fill:none;stroke:currentColor;stroke-width:2}+.gate.offline span{color:var(--ink-2)}diff --git a/web/css/22-followmanage.css b/web/css/22-followmanage.cssindex 1e8c57ac7..0535503c1 100644--- a/web/css/22-followmanage.css+++ b/web/css/22-followmanage.css@@ -63,13 +63,6 @@.fdescinfo:hover{color:var(--ink)}.fdescinfo:focus-visible{color:var(--ink);outline:none;box-shadow:0 0 0 2px var(--tungsten)}.fdescinfo svg{width:13px;height:13px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}-.fdescpop{position:fixed;z-index:var(--layer-tooltip);width:max-content;- max-width:min(250px,calc(100vw - 16px));padding:6px 8px;border-radius:var(--surface-radius);- background:var(--surface);color:var(--ink);border:1px solid var(--border-15);- font-size:var(--fs-sm);line-height:1.3;overflow-wrap:anywhere;pointer-events:none;- box-shadow:0 12px 40px #0007;text-align:left}-.fdescpop[hidden]{display:none}-.fdescpop code{font-family:"Cascadia Mono",Consolas,ui-monospace,"Microsoft YaHei UI","PingFang SC",monospace}.fnote{margin:8px 0 0;font-size:var(--fs-sm);line-height:1.7;color:var(--muted)}.fnote:empty{display:none}.fnote b{color:var(--ink-2);font-weight:600}@@ -79,14 +72,31 @@/* Geist Note:字段、卡片、分区旁的持久上下文,以及需要用户处理的失败,全部走这里。瞬时回执用 toast,销毁确认用 dialog/confirm。整页范围的失败也是这个盒子,只是多一个关闭键(见下面的 .fwarn/.fcheckreport),不另立一套横幅。 */-.geist-note{display:grid;grid-template-columns:16px minmax(0,1fr);align-items:start;gap:9px;margin:10px 0;padding:11px 12px;border:1px solid var(--line-soft);border-radius:var(--surface-radius);background:var(--overlay-5);color:var(--ink-2);font-size:var(--fs-sm);line-height:1.55}.geist-note>svg{width:16px;height:16px;margin-top:2px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.geist-note>p{margin:0}.geist-note>p b{margin-right:7px;color:var(--ink)}.geist-note-secondary{color:var(--muted)}.geist-note-warning{border-color:color-mix(in srgb,var(--meter) 32%,transparent);background:color-mix(in srgb,var(--meter) 7%,transparent)}.geist-note-error{border-color:color-mix(in srgb,var(--drop) 30%,transparent);background:color-mix(in srgb,var(--drop) 7%,transparent)}.geist-note-error>svg{color:var(--drop)}.geist-note-success{border-color:color-mix(in srgb,var(--success) 30%,transparent);background:color-mix(in srgb,var(--success) 7%,transparent)}.geist-note-success>svg{color:var(--success)}+/* Note 默认无填充,filled 使用不透明浅色面;状态含义由文字和图标共同表达。 */+:root{--feedback-success:oklch(53.18% .2399 256.99)}+:root[data-theme="dark"]{--feedback-success:oklch(71.7% .1648 250.794)}+@media(prefers-color-scheme:dark){:root:not([data-theme="light"]){--feedback-success:oklch(71.7% .1648 250.794)}}+.geist-note{--feedback-color:var(--muted);display:grid;grid-template-columns:16px minmax(0,1fr);align-items:start;gap:12px;margin:0;padding:6px 12px;min-height:40px;box-sizing:border-box;border:1px solid var(--line);border-radius:var(--control-radius);background:transparent;color:var(--feedback-color);font-size:var(--fs-md);line-height:24px;overflow-wrap:anywhere}+.geist-note>svg{width:16px;height:24px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}+.geist-note>p{margin:0}.geist-note>p b{margin-right:8px;color:inherit}+.geist-note-warning{--feedback-color:var(--meter);border-color:color-mix(in srgb,var(--meter) 32%,var(--ground))}+.geist-note-error{--feedback-color:var(--drop);border-color:color-mix(in srgb,var(--drop) 30%,var(--ground))}+.geist-note-success{--feedback-color:var(--feedback-success);border-color:color-mix(in srgb,var(--feedback-success) 30%,var(--ground))}+.geist-note-filled{background:color-mix(in srgb,var(--feedback-color) 8%,var(--ground))}+.geist-note-small{min-height:32px;padding:4px 8px;font-size:var(--fs-xs);line-height:22px}+.geist-note-small>svg{height:22px}+.project-banner{--feedback-color:var(--muted);display:flex;align-items:center;justify-content:center;gap:8px 16px;flex-wrap:wrap;padding:8px 24px;min-height:40px;border-block:1px solid color-mix(in srgb,var(--feedback-color) 30%,var(--ground));background:color-mix(in srgb,var(--feedback-color) 5%,var(--ground));color:var(--feedback-color);font-size:var(--fs-md);line-height:20px}+.project-banner>div{display:flex;align-items:center;gap:8px;min-width:0}.project-banner p{margin:0;overflow-wrap:anywhere}+.project-banner svg{width:16px;height:16px;flex:none;fill:none;stroke:currentColor;stroke-width:2}+.project-banner>a{color:inherit;text-decoration:underline;text-underline-offset:5px;font-weight:500;flex:none}+.project-banner-error{--feedback-color:var(--drop)}.project-banner-warning{--feedback-color:var(--meter)}.project-banner-success{--feedback-color:var(--feedback-success)}+.context-card{position:fixed;inset:auto;margin:0;width:320px;max-width:calc(100vw - 16px);box-sizing:border-box;overflow:auto;overscroll-behavior:contain;padding:16px;border:1px solid var(--line);border-radius:var(--floating-radius);background:var(--ground);color:var(--ink);box-shadow:0 8px 24px rgba(0,0,0,.16);font-size:var(--fs-md);line-height:1.5;overflow-wrap:anywhere;z-index:var(--layer-popover);pointer-events:auto}+.context-card[hidden]{display:none}.context-card h3{margin:0 0 8px;font-size:var(--fs-md)}.context-card dl{display:grid;grid-template-columns:auto minmax(0,1fr);gap:8px 12px;margin:0}.context-card dt{color:var(--muted)}.context-card dd{margin:0}+@media(max-width:600px){.project-banner{justify-content:flex-start}.project-banner>a{margin-left:24px}}-/* 检查结果的页内持久行(.fwarn 是上次检查的存量失败,.fcheckreport 是这次- 检查的失败明细)。失败不能只发 toast——那是转身就丢的通知;原因和恢复入口- 必须留在页面上,所以它们是 Geist Note 的可关闭变体:盒子、发丝边、图标尺寸- 和 error/secondary 两套配色全部来自 `.geist-note`,这里只补关闭键那一列。- 自带一份边框和内距的话,同一条失败在关注页和管理页会长成两个样子。 */-.fcheckreport,.fwarn{grid-template-columns:16px minmax(0,1fr) 24px;margin:10px 0 14px}++/* 检查失败明细持续保留到状态解决,复用 Note 的边界、图标和语义色。 */+.fcheckreport,.fwarn{grid-template-columns:16px minmax(0,1fr);margin:10px 0 14px}.fcheckreport>div,.fwarn>span{min-width:0}.fcheckreport p,.fwarn p{margin:0}.fcheckreport b{color:var(--ink);font-variant-numeric:tabular-nums}@@ -98,11 +108,6 @@.sbadge i{width:6px;height:6px;border-radius:50%;background:var(--muted);flex:none}.sbadge.ok i{background:var(--success)}.sbadge.error i{background:var(--drop)}-.fwarn .wclose,.fcheckreport .wclose{width:24px;height:24px;padding:0;border:0;- border-radius:var(--control-radius);background:transparent;color:var(--muted);- display:grid;place-items:center;cursor:pointer}-.fwarn .wclose:hover,.fcheckreport .wclose:hover{background:var(--hover);color:var(--ink)}-.fwarn .wclose svg,.fcheckreport .wclose svg{width:13px;height:13px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round}/* 批量动作是 2292 条级别的操作,不是行内文字链接:按钮的边界让「这会改状态」在点击前就看得见,也和本页其他 .fbtn(检查全部/去看更新)同一套语言。 */.fbulk{display:inline-flex;gap:8px;margin-left:auto;flex:none}@@ -405,3 +410,6 @@ details.fcred{display:block;min-width:0}但那条规则量不出行内元素的可用宽度。 */.linktable .linkurl a{display:block;color:var(--muted);text-decoration:none}.linktable .linkurl a:hover{color:var(--ink)}+.photolight.has-strip .photodetail.context-card,.photodetail.context-card{position:fixed;inset:auto;width:320px;max-width:calc(100vw - 16px);background:var(--ground);color:var(--ink);backdrop-filter:none}.photodetail.context-card .photodetailmeta,.photodetail.context-card .srcstate{color:var(--muted)}.photodetail.context-card>button{color:var(--ink);border-color:var(--line)}++.geist-gauge{display:inline-flex;width:32px;height:32px;flex:none;vertical-align:middle;margin-inline-end:8px}.geist-gauge svg{width:100%;height:100%;fill:none;stroke-width:3}.geist-gauge circle:first-child{stroke:var(--line-soft)}.geist-gauge circle:last-child{stroke:var(--feedback-success);transform:rotate(-90deg);transform-origin:center}.geist-progress{position:relative}.geist-progress i{background:var(--progress-color,var(--feedback-success))}.geist-progress-stop{position:absolute;top:0;bottom:0;width:2px;background:var(--ground);transform:translateX(-50%)}diff --git a/web/js/core.js b/web/js/core.jsindex 98cbb5020..b7fa49add 100644--- a/web/js/core.js+++ b/web/js/core.js@@ -14,16 +14,27 @@ const icon=(name,cls='')=>{return `<svg${classes?` class="${classes}"`:''} viewBox="${box}" aria-hidden="true"><use href="#i-${name}"/></svg>`};/* `signal` 写成显式的一项,不靠 Object.assign 顺带透传:表面切换要能作废上一屏还没读完的请求,「这个请求可被取消」得在签名上看得见。 */+export function requestErrorMessage(cause,status=0){+ const text=String(cause?.message??cause??'');+ const code=Number(status||cause?.status||text.match(/\b(400|401|403|404|408|409|413|429|500|502|503|504)\b/)?.[1]);+ const messages={400:'提交内容有误,请检查输入后重试。',401:'登录已失效,请刷新页面重新登录。',403:'当前设备没有执行此操作的权限,请在运行 Peach 的电脑上操作。',404:'请求的内容已不存在,请刷新列表。',408:'请求超时,请稍后重试。',409:'当前状态不允许此操作,请刷新后重试。',413:'提交内容过大,请减少数量后重试。',429:'请求过于频繁,请稍后重试。',500:'Peach 服务处理失败,请重试;持续失败时查看托盘日志。',502:'连接上游服务失败,请检查代理或来源服务。',503:'Peach 服务暂时不可用,请稍后重试。',504:'等待服务响应超时,请稍后重试。'};+ if(/Failed to fetch|fetch failed|NetworkError|Load failed|network request failed|ERR_CONNECTION/i.test(text))return '无法连接到 Peach 服务,请确认网络连接和托盘服务已启动。';+ if(cause?.name==='TimeoutError'||/timed? ?out|timeout/i.test(text))return '等待服务响应超时,请检查连接后重试。';+ if(/[\u3400-\u9fff]/.test(text)&&!/^请求失败[((]/.test(text))return text;+ if(messages[code])return messages[code];+ return '操作未完成,请重试;持续失败时查看托盘日志。';+}const api=async(p,o)=>{const {signal=null,...rest}=o||{};const init={headers:{'Content-Type':'application/json'},...rest};if(signal)init.signal=signal;- const response=await fetch(p,init);+ let response;+ try{response=await fetch(p,init)}catch(error){if(error?.name==='AbortError')throw error;throw new Error(requestErrorMessage(error),{cause:error})}let payload=null;try{payload=await response.json()}catch(_e){}if(!response.ok){const detail=payload&&(payload.message||payload.detail||payload.error);- throw new Error(detail||`请求失败(${response.status})`);+ throw new Error(requestErrorMessage(detail,response.status));}return payload;};diff --git a/web/js/ui-components.js b/web/js/ui-components.jsindex f11d13567..45f7b7248 100644--- a/web/js/ui-components.js+++ b/web/js/ui-components.js@@ -1,15 +1,28 @@-import { esc, icon } from './core.js';+import { esc, icon, requestErrorMessage } from './core.js';export { MEDIA_SOURCE_ICONS } from './media-source-icons.js';const NOTE_VARIANTS=new Set(['secondary','warning','error','success']);/** Inline, persistent context beside the field/card/section it describes. */-export function noteHtml(message,{variant='secondary',label='',className=''}={}){+export function noteHtml(message,{variant='secondary',label='',className='',size='medium',filled=false}={}){const kind=NOTE_VARIANTS.has(variant)?variant:'secondary';const symbol=kind==='secondary'?'info':kind==='success'?'check':'alert';const role=kind==='error'?' role="alert"':' role="note"';- return `<div class="geist-note geist-note-${kind}${className?` ${esc(className)}`:''}"${role}>- ${icon(symbol)}<p>${label?`<b>${esc(label)}</b>`:''}<span>${esc(message)}</span></p></div>`;+ return `<div class="geist-note geist-note-${kind}${className?` ${esc(className)}`:''}${size==='small'?' geist-note-small':''}${filled?' geist-note-filled':''}"${role}>+ ${icon(symbol)}<p>${label?`<b>${esc(label)}</b>`:''}<span>${esc(kind==='error'?requestErrorMessage(message):message)}</span></p></div>`;+}++const PROJECT_BANNER_CLASSES={gray:'project-banner-gray',success:'project-banner-success',warning:'project-banner-warning',error:'project-banner-error'};+export function projectBannerHtml(message,{variant='gray',href,label,value,max}={}){+ const kind=['gray','success','warning','error'].includes(variant)?variant:'gray';+ return `<aside class="project-banner ${PROJECT_BANNER_CLASSES[kind]}" role="${kind==='error'?'alert':'status'}"><div>${Number(max)>0?gaugeHtml('任务完成率',value,max):icon(kind==='error'||kind==='warning'?'alert':'info')}<p>${esc(message)}</p></div><a href="${esc(href)}">${esc(label)}</a></aside>`;+}++export function gaugeHtml(label,value,max=100){+ const ceiling=Number(max), current=Number(value);+ if(!Number.isFinite(ceiling)||ceiling<=0||!Number.isFinite(current))return `<span>${esc(label)}:未取得</span>`;+ const percent=Math.max(0,Math.min(100,current/ceiling*100));+ return `<span class="geist-gauge" role="progressbar" aria-label="${esc(label)}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${percent}"><svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="13"/><circle cx="16" cy="16" r="13" pathLength="100" stroke-dasharray="${percent} 100"/></svg></span>`;}/**@@ -41,13 +54,13 @@ export function breadcrumbHtml(items){}/** Determinate progress only. Callers supply real units instead of a decorative width. */-export function progressHtml(label,value,max=100){+export function progressHtml(label,value,max=100,{variant='active',stops=[]}={}){const ceiling=Math.max(0,Number(max)||0);const current=Math.max(0,Math.min(Number(value)||0,ceiling));const percent=ceiling?current/ceiling*100:0;return `<div class="geist-progress" role="progressbar" aria-label="${esc(label)}"aria-valuemin="0" aria-valuemax="${ceiling}" aria-valuenow="${current}"- style="--progress-value:${percent}%"><i></i></div>`;+ style="--progress-value:${percent}%;--progress-color:var(${variant==='error'?'--drop':variant==='warning'?'--meter':'--feedback-success'})"><i></i>${stops.filter(stop=>Number(stop.value)>0&&Number(stop.value)<ceiling&&stop.label).map(stop=>`<span class="geist-progress-stop" style="left:${Number(stop.value)/ceiling*100}%" role="img" aria-label="${esc(stop.label)}"></span>`).join('')}</div>`;}/** Geist Spinner: immediate feedback for a user-triggered action. */@@ -507,7 +520,8 @@ export function wireAnchoredMenu(mount,toggle,menu){const downward=under>=naturalHeight||under>=over;const height=Math.min(naturalHeight,Math.max(downward?under:over,0));menu.style.maxHeight=height+'px';- menu.style.left=Math.max(8,Math.min(anchor.right-width,innerWidth-width-8))+'px';+ const preferredLeft=menu.classList.contains('context-card')?anchor.left:anchor.right-width;+ menu.style.left=Math.max(8,Math.min(preferredLeft,innerWidth-width-8))+'px';menu.style.top=(downward?anchor.bottom+8:anchor.top-8-height)+'px'};/* 页面滚走了就关掉:菜单固定在视口里,锚点跟着内容跑,留着就悬在半空。菜单自己的滚动不算——它装不下时本来就要在内部滚,滚一下就关等于底下那几项@@ -521,6 +535,7 @@ export function wireAnchoredMenu(mount,toggle,menu){const inTopLayer=menu.hasAttribute('popover');const setOpen=open=>{if(open){+ if(openedMenu&&openedMenu.mount!==mount)openedMenu.setOpen(false);menu.hidden=false;if(inTopLayer)menu.showPopover();position();window.addEventListener('resize',position);window.addEventListener('scroll',closeFromViewport,{capture:true,passive:true});@@ -538,6 +553,26 @@ export function wireAnchoredMenu(mount,toggle,menu){return {setOpen,isOpen:()=>!menu.hidden};}+/** 复杂补充信息复用顶层浮层和视口避让,正文可聚焦并独立滚动。 */+export function wireContextCard(mount,trigger,panel){+ panel.classList.add('context-card');panel.setAttribute('popover','manual');+ panel.setAttribute('role','dialog');panel.tabIndex=-1;+ trigger.setAttribute('aria-haspopup','dialog');trigger.setAttribute('aria-controls',panel.id);+ const floating=wireAnchoredMenu(mount,trigger,panel);+ let timer;+ const hide=()=>{clearTimeout(timer);floating.setOpen(false)};+ const enter=()=>{clearTimeout(timer);timer=setTimeout(()=>{if(trigger.isConnected)floating.setOpen(true)},150)};+ const leave=()=>{clearTimeout(timer);timer=setTimeout(()=>{if(!panel.matches(':hover')&&!trigger.matches(':hover')&&!panel.contains(document.activeElement)&&document.activeElement!==trigger)hide()},150)};+ trigger.addEventListener('pointerenter',enter);trigger.addEventListener('pointerleave',leave);+ panel.addEventListener('pointerenter',()=>clearTimeout(timer));panel.addEventListener('pointerleave',leave);+ trigger.addEventListener('focus',enter);trigger.addEventListener('blur',leave);+ trigger.addEventListener('click',()=>clearTimeout(timer));+ mount.addEventListener('keydown',event=>{if(event.key==='Escape')hide()});+ panel.addEventListener('focusout',leave);+ trigger.addEventListener('keydown',event=>{if(event.key==='ArrowDown'&&!panel.hidden){event.preventDefault();(panel.querySelector('a,button,[tabindex="0"]')||panel).focus()}});+ return {...floating,hide};+}+/* Geist Select:站内每一个下拉都是它,没有一个走浏览器自带的 select 控件。原生下拉的弹出层由操作系统画,不认站内色板:浅色主题下它要么跟着系统换成另一套灰白,