Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: 配置页并入主站管理菜单,首启页与配置页可弹系统对话框选文件夹

longmeidao7ca7d6a30782
diff --git a/docs/FRONTEND.md b/docs/FRONTEND.md
index 25a7f3991..f5a4a1cc3 100644
--- a/docs/FRONTEND.md
+++ b/docs/FRONTEND.md
@@ -21,9 +21,18 @@ Vite + TypeScript + Preact。迁移方式是 strangler:**遗留路由继续拥
| `web/dist/peach-ui.js` | 构建产物,**进 Git**,由 `/dist/{name}` 提供 |
首次运行页(未配置时的 `GET /` 与 `POST /setup`)不在这张表里:它是 SPA 外壳之外的一张
-独立页面,HTML 与样式都自包含在 `src/peach/routes_pages.py`,不引 `web/` 的任何资产,也不是
+独立页面,HTML 与样式都自包含在 `src/peach/routes_pages.py`,只借 `/js/ui-components.js` 的 `wireCollapse` 画「高级设置」的折叠,此外不引 `web/` 的资产,也不是
island。原因是那一套一上来就打 `/api/items`,而未配置的机器还没有数据库;它也没有客户端
-状态,原生 `<form method="post">` 不写一行 JS 就能工作。本机 `/configuration` 复用同一套服务端表单和主题 token,设置成功以浏览器 cookie 登录并跳入馆藏。
+状态,原生 `<form method="post">` 不写一行 JS 就能工作。设置成功以浏览器 cookie 登录并跳入馆藏。
+它的配色 token 从 `web/css/01-base.css` 的 `:root` 两段抽出来,跟随系统深浅色。
+
+配置好之后改文件夹与端口走 `/configuration`:那是主站里的一屏(管理菜单 → 配置),
+由 `frontend/src/islands/configuration.tsx` 渲染,数据契约是 `/api/configuration`
+(`src/peach/routes_configuration.py`)。服务端按两道门放行——只有独立包、只有回环地址——
+并在 `/healthz` 里按调用方回 `configurable`,遗留层据此决定菜单里列不列这一项。
+表单校验的原因由服务端按字段给(400 的 `errors`),island 写回原位,不在前端复制判定。
+浏览器直接导航撞上 `HTTPException` 时,`api.py` 的处理器按 `Accept` 回一张 HTML 错误页
+(`routes_pages.error_page`),`/api/` 下和非导航请求仍回 JSON。
产物名字不带内容哈希:引用它的 `web/app.js` 不经过构建,构建时改不了那里的路径。
缓存由服务端兜住:`/dist/` 与 `/app.js`、`/app.css`、`/js/` 同一档,回
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 0851e7de6..cbdf20871 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -21,6 +21,10 @@
扫描摘要。写出的 `[media.locations]` 只有 `local`,几个目录就几个声明根:Windows 上直接是
那些目录、`[media.mounts]` 为空;macOS 上声明根是 `R:\media`(第二个起 `R:\media2`……)、
目录按同样顺序写进 `[media.mounts] local`。页面上的媒体文件夹是可加减的列表,配置页同样。
+ 配置页在主站里:管理菜单 → 配置(`/configuration`),只在运行 Peach 的这台电脑上、
+ 且只有独立包才出现;数据走 `/api/configuration`,保存后写重启标记由托盘接手。
+ 每行文件夹旁的「选择文件夹」让运行 Peach 的这台电脑弹系统对话框(Windows 资源管理器、
+ macOS Finder),走 `/api/pick-folder`,同样只对本机开放;首启页也有这颗键。
复制、writer 镜像、SMB 一律不问,保持关闭或留空。建目录、迁库、生成 CA 与口令、写设置文件
这一整段在 `onboarding.apply()`,CLI 与设置页调的是同一个函数,只在打印方式上不同。
- 不进终端的那条路是托盘首启的引导服务。`peach-tray` 启动时新鲜读一次设置文件,判据在
diff --git a/docs/REUSE.md b/docs/REUSE.md
index ab344031a..78f617821 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -54,6 +54,7 @@
| 能力 | 复用实现 | Peach 负责 |
|---|---|---|
+| 本机文件夹对话框 | Windows 自带 `powershell.exe` 经 `Add-Type` 调 Shell 的 `IFileOpenDialog`(带地址栏的文件夹选择框);macOS `osascript` 的 `choose folder` | `src/peach/folder_picker.py` 只拼命令、区分取消与失败、一次只开一个;不为一个对话框引入 tkinter 或 GUI 框架 |
| HTTP | 默认复用全项目共用的 `httpx.Client`/transport;FANBOX 公开 `post.info` 按固定证据复用 `curl_cffi==0.16.2` | 来源策略、DTO、脱敏、站点限定、大小上限;不求解机器人质询 |
| RSS/Atom | `feedparser` | 有界抓取、快照、复核、导入 |
| 追更来源接口 | FANBOX 公开帖子 API(详情只使用用户自己的可选 Cookie 与 Firefox 传输特征)、kemono 系公开 JSON API(`Accept: text/css`,站点自述的抓取路径)、rule34.xxx 官方 dapi(需账号 API key)与官方 tag 补全(公开)、Paheal 标签/详情页、Gofile contents API(需 Premium 账号 API token)、f95zone `latest_data.php`、站内搜索(需登录 cookie)、线程页与站内 masked XHR | 连接器边界、凭据隔离、多媒体顺序、文件站目标校验、变体与跨站重复判定、候选复核与批准后的 online asset 投影 |
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index 4e5868181..463dcf327 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -8,11 +8,14 @@
/** 服务端明确回了非 2xx。`status` 留给调用方区分 401/409/404 这类需要不同处置的情况。 */
export class ApiError extends Error {
readonly status: number;
+ /** 响应体原样。表单校验那种 400 会在 `errors` 里按字段给原因,页面要把它们写回原位。 */
+ readonly body: unknown;
- constructor(message: string, status: number) {
+ constructor(message: string, status: number, body: unknown = null) {
super(message);
this.name = 'ApiError';
this.status = status;
+ this.body = body;
}
}
@@ -52,3 +55,23 @@ export async function apiGet<T>(path: string, signal?: AbortSignal): Promise<T>
}
return payload as T;
}
+
+/** 带 JSON 请求体的写操作。失败时原响应体挂在 `ApiError.body` 上,字段级原因由调用方取。 */
+export async function apiSend<T>(path: string, body: unknown, method = 'POST'): Promise<T> {
+ const response = await fetch(path, {
+ method,
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
+ credentials: 'same-origin',
+ body: JSON.stringify(body),
+ });
+ let payload: unknown = null;
+ try {
+ payload = await response.json();
+ } catch {
+ // 同上:失败响应不一定是 JSON。
+ }
+ if (!response.ok) {
+ throw new ApiError(reasonOf(payload) || `请求失败(${response.status})`, response.status, payload);
+ }
+ return payload as T;
+}
diff --git a/frontend/src/islands.ts b/frontend/src/islands.ts
index 850120784..14f970eba 100644
--- a/frontend/src/islands.ts
+++ b/frontend/src/islands.ts
@@ -13,9 +13,11 @@
* 容器由遗留层拥有:它会在别的页面进入时直接 `innerHTML=`。因此 `mountIsland` 每次
* 都先自我卸载,`unmountIsland` 也不假设 DOM 还在原处。 */
import { h, render } from 'preact';
-import type { ComponentType } from 'preact';
+import type { Attributes, ComponentType } from 'preact';
import { errorMessage } from './api';
+import { Configuration, loadConfiguration } from './islands/configuration';
+import type { ConfigurationData, ConfigurationProps } from './islands/configuration';
import { QualityGoals, loadQualityGoals } from './islands/quality-goals';
import type { QualityGoalsProps } from './islands/quality-goals';
import type { QualityGoalsData } from './state/quality-goals';
@@ -37,6 +39,7 @@ export interface IslandState<D> {
/** 每个 island 的 props 与首屏数据类型。新增 island 时在这里登记,注册表随之要求实现。 */
export interface IslandContracts {
'quality-goals': { props: QualityGoalsProps; data: QualityGoalsData };
+ configuration: { props: ConfigurationProps; data: ConfigurationData };
}
export type IslandName = keyof IslandContracts;
@@ -51,6 +54,7 @@ interface IslandDefinition<N extends IslandName> {
const REGISTRY: { [N in IslandName]: IslandDefinition<N> } = {
'quality-goals': { load: loadQualityGoals, component: QualityGoals },
+ configuration: { load: loadConfiguration, component: Configuration },
};
/** 已注册的 island 名字。遗留层与测试用它核对路由表,不必知道注册表结构。 */
@@ -100,7 +104,10 @@ export async function mountIsland<N extends IslandName>(
// 旧属性。整个清掉再画,一次替换,只有一次布局变化。
el.textContent = '';
mount.painted = true;
- render(h(island.component, { ...props, ...state }), el);
+ // 注册表有多个 island 之后 `PropsOf<N>` 是按名字分发的索引类型,TS 推不出它与
+ // `Attributes` 相交仍是同一个对象,这里把结论写给它。
+ const attrs = { ...props, ...state } as Attributes & PropsOf<N> & IslandState<DataOf<N>>;
+ render(h(island.component, attrs), el);
}
/** 卸载容器上的 island:中止在途取数并清空自己画过的内容。没挂过的容器是空操作。 */
diff --git a/frontend/src/islands/configuration.tsx b/frontend/src/islands/configuration.tsx
new file mode 100644
index 000000000..400ff341e
--- /dev/null
+++ b/frontend/src/islands/configuration.tsx
@@ -0,0 +1,274 @@
+/* 配置页(`/configuration`):这台电脑的媒体文件夹与本机端口,加一块运行信息。
+ *
+ * 数据契约在 `/api/configuration`(`src/peach/routes_configuration.py`)。服务端按两道门
+ * 放行:只有独立包、且只有从运行 Peach 的这台电脑打开时 `editable` 才为真;其它情况
+ * 表单不画,只留一句为什么和运行信息。保存成功后 Peach 会重启,这里给一句持久 Note、
+ * 一条新地址的链接,并在托盘换好进程后自己跳过去。
+ *
+ * 表单校验的原因由服务端按字段给(400 的 `errors`),页面把它们写回原位,不在前端
+ * 复制一份路径与端口的判定。 */
+import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';
+import type { JSX } from 'preact';
+
+import { fieldsetTitle, noteHtml, setActionBusy } from '@peach/legacy/ui';
+import { ApiError, apiGet, apiSend, errorMessage } from '../api';
+
+export interface ConfigurationProps {
+ /** 保存成功后的过去时回执(遗留层的 Toast)。 */
+ receipt(message: string): void;
+}
+
+export interface ConfigurationFact {
+ term: string;
+ value: string;
+}
+
+export interface ConfigurationData {
+ editable: boolean;
+ /** 不能编辑时给用户看的原因,可编辑时为空。 */
+ notice: string;
+ /** 设置文件的指纹,保存时带回去,服务端据此拒绝盖掉别处的改动。 */
+ revision: string;
+ media_dirs: string[];
+ port: number;
+ facts: ConfigurationFact[];
+}
+
+interface FieldErrors {
+ media_dirs?: string[];
+ port?: string;
+}
+
+interface SaveResult {
+ saved: boolean;
+ url: string;
+ revision: string;
+}
+
+export const CONFIGURATION_URL = '/api/configuration';
+/** 让运行 Peach 的这台电脑弹系统文件夹对话框;浏览器自己拿不到本机绝对路径。 */
+export const PICK_FOLDER_URL = '/api/pick-folder';
+
+/** 保存后等托盘换好进程再跳到新地址的时间。首启完成页用的是同一个数。 */
+export const RESTART_REDIRECT_MS = 8000;
+
+export const loadConfiguration = (
+ _props: ConfigurationProps,
+ signal: AbortSignal,
+): Promise<ConfigurationData> => apiGet<ConfigurationData>(CONFIGURATION_URL, signal);
+
+type State = { data: ConfigurationData | null; error: string };
+
+const Html = ({ html, class: className }: { html: string; class?: string }) => (
+ <div class={className} dangerouslySetInnerHTML={{ __html: html }} />
+);
+
+const fieldErrorsOf = (cause: unknown): FieldErrors | null => {
+ if (!(cause instanceof ApiError) || cause.status !== 400) return null;
+ const body = cause.body as { errors?: FieldErrors } | null;
+ return body?.errors ?? null;
+};
+
+function Facts({ facts }: { facts: ConfigurationFact[] }) {
+ return (
+ <section class="configfieldset" data-geist-fieldset aria-labelledby="configFactsTitle">
+ <div class="geist-fieldset-content">
+ <Html html={fieldsetTitle('configFactsTitle', '运行信息')} />
+ <dl class="configfacts">
+ {facts.map((fact) => (
+ <>
+ <dt>{fact.term}</dt>
+ <dd>{fact.value}</dd>
+ </>
+ ))}
+ </dl>
+ </div>
+ </section>
+ );
+}
+
+function ConfigurationForm({ data, receipt }: { data: ConfigurationData; receipt: ConfigurationProps['receipt'] }) {
+ const [dirs, setDirs] = useState<string[]>(data.media_dirs.length ? data.media_dirs : ['']);
+ const [port, setPort] = useState(String(data.port));
+ const [scanNow, setScanNow] = useState(false);
+ const [rowErrors, setRowErrors] = useState<string[]>([]);
+ const [portError, setPortError] = useState('');
+ const [failure, setFailure] = useState('');
+ const [saved, setSaved] = useState<SaveResult | null>(null);
+ const [focusRow, setFocusRow] = useState<number | null>(null);
+ const busy = useRef(false);
+ const revision = useRef(data.revision);
+ const rows = useRef<(HTMLInputElement | null)[]>([]);
+ const saveButton = useRef<HTMLButtonElement>(null);
+
+ // 新加的一行直接接过焦点:添加之后下一步一定是往里打路径。布局效应在提交 DOM 后立刻跑,焦点不等下一帧。
+ useLayoutEffect(() => {
+ if (focusRow === null) return;
+ rows.current[focusRow]?.focus();
+ setFocusRow(null);
+ }, [focusRow]);
+
+ useEffect(() => {
+ if (!saved) return undefined;
+ const timer = setTimeout(() => location.assign(saved.url), RESTART_REDIRECT_MS);
+ return () => clearTimeout(timer);
+ }, [saved]);
+
+ const update = (index: number, value: string) => {
+ setDirs((list) => list.map((dir, i) => (i === index ? value : dir)));
+ };
+ const add = () => {
+ setFocusRow(dirs.length);
+ setDirs((list) => [...list, '']);
+ };
+ const remove = (index: number) => {
+ setDirs((list) => list.filter((_, i) => i !== index));
+ setRowErrors((errors) => errors.filter((_, i) => i !== index));
+ };
+ const setRowError = (index: number, message: string) => {
+ setRowErrors((errors) => {
+ const next = [...errors];
+ while (next.length <= index) next.push('');
+ next[index] = message;
+ return next;
+ });
+ };
+ // 对话框开着的时候按钮置忙;取消什么也不改,打不开时原因写在这一行下面。
+ const pick = async (index: number, button: HTMLButtonElement) => {
+ if (button.getAttribute('aria-busy') === 'true') return;
+ setActionBusy(button, true);
+ try {
+ const { path } = await apiSend<{ path: string | null }>(PICK_FOLDER_URL, { initial: dirs[index] ?? '' });
+ if (path) {
+ update(index, path);
+ setRowError(index, '');
+ }
+ } catch (cause) {
+ setRowError(index, errorMessage(cause));
+ } finally {
+ setActionBusy(button, false);
+ }
+ };
+
+ const submit = async (event: JSX.TargetedEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ if (busy.current) return;
+ busy.current = true;
+ setActionBusy(saveButton.current, true);
+ setFailure('');
+ try {
+ const result = await apiSend<SaveResult>(CONFIGURATION_URL, {
+ revision: revision.current,
+ media_dirs: dirs,
+ port,
+ scan_now: scanNow,
+ });
+ revision.current = result.revision;
+ setRowErrors([]);
+ setPortError('');
+ receipt('已保存配置');
+ setSaved(result);
+ } catch (cause) {
+ const fields = fieldErrorsOf(cause);
+ if (fields) {
+ setRowErrors(fields.media_dirs ?? []);
+ setPortError(fields.port ?? '');
+ } else {
+ setRowErrors([]);
+ setPortError('');
+ setFailure(errorMessage(cause));
+ }
+ } finally {
+ busy.current = false;
+ setActionBusy(saveButton.current, false);
+ }
+ };
+
+ if (saved) {
+ return (
+ <div class="configsaved" role="status">
+ <Html html={noteHtml('配置已保存,Peach 正在重新启动。', { variant: 'success', label: '已保存' })} />
+ <p class="confighelp">
+ 几秒后自动打开新地址;没跳转就点 <a href={saved.url}>进入馆藏</a>。
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <form class="configfieldset" data-geist-fieldset aria-labelledby="configTitle" onSubmit={submit} noValidate>
+ <div class="geist-fieldset-content">
+ <Html html={fieldsetTitle('configTitle', '这台电脑')} />
+ <div class="configfield">
+ <span class="configlabel" id="configDirsLabel">媒体文件夹</span>
+ <div class="configdirs" role="group" aria-labelledby="configDirsLabel">
+ {dirs.map((value, index) => (
+ <div class="configdir" key={index}>
+ <input
+ class="geist-input"
+ type="text"
+ value={value}
+ aria-label={`媒体文件夹 ${index + 1}`}
+ aria-invalid={rowErrors[index] ? 'true' : undefined}
+ onInput={(event) => update(index, event.currentTarget.value)}
+ ref={(el) => { rows.current[index] = el; }}
+ />
+ <button type="button" class="geist-button configpick" aria-label="选择文件夹" onClick={(event) => pick(index, event.currentTarget)}>
+ <svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-folder-search" /></svg>
+ </button>
+ {dirs.length > 1 ? (
+ <button type="button" class="geist-button configrm" aria-label="移除这个文件夹" onClick={() => remove(index)}>
+ <svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-x" /></svg>
+ </button>
+ ) : null}
+ {rowErrors[index] ? <p class="configbad" role="alert">{rowErrors[index]}</p> : null}
+ </div>
+ ))}
+ </div>
+ <button type="button" class="geist-button configadd" onClick={add}>添加文件夹</button>
+ <p class="confighelp">Peach 从这些文件夹读取视频和图片。可以是外置硬盘上的文件夹,但必须已经存在。</p>
+ </div>
+ <div class="configfield">
+ <label for="configPort">本机访问端口</label>
+ <input
+ id="configPort"
+ class="geist-input"
+ type="text"
+ inputMode="numeric"
+ value={port}
+ aria-invalid={portError ? 'true' : undefined}
+ onInput={(event) => setPort(event.currentTarget.value)}
+ />
+ {portError ? <p class="configbad" role="alert">{portError}</p> : null}
+ <p class="confighelp">浏览器地址里冒号后面的数字,一般不用改。</p>
+ </div>
+ <label class="configcheck">
+ <span class="pcheck">
+ <input type="checkbox" checked={scanNow} onChange={(event) => setScanNow(event.currentTarget.checked)} />
+ <span aria-hidden="true"><svg viewBox="0 0 24 24"><use href="#i-check" /></svg></span>
+ </span>
+ <span>保存后扫描媒体文件夹</span>
+ </label>
+ {failure ? <Html html={noteHtml(failure, { variant: 'error', label: '没有保存' })} /> : null}
+ </div>
+ <div class="geist-fieldset-footer" data-geist-fieldset-footer>
+ <p>保存后 Peach 会重新启动,端口改了就用新地址打开。</p>
+ <button type="submit" class="geist-button primary" ref={saveButton}>保存配置</button>
+ </div>
+ </form>
+ );
+}
+
+export function Configuration({ receipt, data, error }: ConfigurationProps & State) {
+ if (error || !data) {
+ return <Html class="configpage" html={noteHtml(error || '没有读到配置', { variant: 'error', label: '打不开配置' })} />;
+ }
+ return (
+ <div class="configpage">
+ {data.editable
+ ? <ConfigurationForm data={data} receipt={receipt} />
+ : <Html html={noteHtml(data.notice, { variant: 'secondary', label: '只读' })} />}
+ <Facts facts={data.facts} />
+ </div>
+ );
+}
diff --git a/frontend/src/legacy/ui.d.ts b/frontend/src/legacy/ui.d.ts
index 376a7b8f4..97772cf08 100644
--- a/frontend/src/legacy/ui.d.ts
+++ b/frontend/src/legacy/ui.d.ts
@@ -12,6 +12,13 @@ export declare function emptyStateHtml(
options?: { className?: string; actions?: string },
): string;
+/** Geist Fieldset 的标题:放在框体里的 h3,不用原生 legend。 */
+export declare function fieldsetTitle(id: string, title: string): string;
+
+/** 用户触发的动作等待结果时的忙态:`aria-busy` 与 `aria-disabled` 一起写,控件仍可聚焦,
+ * 重复触发由遗留层的 `wireBusyActions` 拦住。请求等待期不许改用原生 `disabled`。 */
+export declare function setActionBusy(control: Element | null, busy?: boolean): void;
+
/** Geist Note:字段、卡片、分区旁的持久反馈。 */
export declare function noteHtml(
message: string,
diff --git a/frontend/test/configuration.test.tsx b/frontend/test/configuration.test.tsx
new file mode 100644
index 000000000..f33f1a789
--- /dev/null
+++ b/frontend/test/configuration.test.tsx
@@ -0,0 +1,179 @@
+import { render } from 'preact';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ CONFIGURATION_URL, Configuration, PICK_FOLDER_URL, loadConfiguration,
+} from '../src/islands/configuration';
+import type { ConfigurationData } from '../src/islands/configuration';
+
+const data = (over: Partial<ConfigurationData> = {}): ConfigurationData => ({
+ editable: true,
+ notice: '',
+ revision: 'rev-1',
+ media_dirs: ['D:\\Media'],
+ port: 9123,
+ facts: [{ term: '版本', value: '0.7.25' }, { term: 'FFmpeg', value: '内置' }],
+ ...over,
+});
+
+const mount = (props: Partial<ConfigurationData> = {}, receipt = vi.fn()) => {
+ const el = document.createElement('div');
+ document.body.append(el);
+ render(<Configuration receipt={receipt} data={data(props)} error="" />, el);
+ return { el, receipt };
+};
+
+const inputs = (el: Element) => [...el.querySelectorAll<HTMLInputElement>('.configdir .geist-input')];
+const submit = (el: Element) => {
+ el.querySelector('form')?.dispatchEvent(new Event('submit', { cancelable: true }));
+};
+// Preact 把状态更新攒到微任务里再画;输入之后、提交之前都要等它落地。
+const settle = async () => {
+ for (let i = 0; i < 4; i += 1) await Promise.resolve();
+};
+type FetchCall = [string, RequestInit];
+const fetchMock = (status: number, body: unknown) => vi.fn<(...call: FetchCall) => Promise<unknown>>(
+ async () => ({ ok: status < 400, status, json: async () => body }),
+);
+
+afterEach(() => {
+ for (const el of [...document.body.children]) render(null, el);
+ document.body.innerHTML = '';
+ vi.unstubAllGlobals();
+});
+
+describe('配置页取数', () => {
+ it('首屏走 /api/configuration 并带上中止信号', async () => {
+ const fetch = fetchMock(200, data());
+ vi.stubGlobal('fetch', fetch);
+ const controller = new AbortController();
+ await loadConfiguration({ receipt: vi.fn() }, controller.signal);
+ const [url, init] = fetch.mock.calls[0] ?? [];
+ expect(url).toBe(CONFIGURATION_URL);
+ expect(init?.signal).toBe(controller.signal);
+ });
+});
+
+describe('媒体文件夹列表', () => {
+ it('一行一个文件夹,只有一行时没有移除键', () => {
+ const { el } = mount();
+ expect(inputs(el).map((input) => input.value)).toEqual(['D:\\Media']);
+ expect(el.querySelector('.configrm')).toBeNull();
+ });
+
+ it('添加文件夹是次级按钮,新行接过焦点,之后每行都能移除', async () => {
+ const { el } = mount();
+ const add = el.querySelector<HTMLButtonElement>('.configadd');
+ expect(add?.classList.contains('primary'), '每屏只有「保存配置」一个主动作').toBe(false);
+ add?.click();
+ await settle();
+ expect(inputs(el)).toHaveLength(2);
+ expect(document.activeElement).toBe(inputs(el)[1]);
+ expect(el.querySelectorAll('.configrm')).toHaveLength(2);
+ el.querySelectorAll<HTMLButtonElement>('.configrm')[0]?.click();
+ await settle();
+ expect(inputs(el)).toHaveLength(1);
+ expect(inputs(el)[0]?.value).toBe('');
+ });
+});
+
+describe('选择文件夹', () => {
+ it('让这台电脑弹系统对话框,选中的路径填回这一行', async () => {
+ const fetch = fetchMock(200, { path: 'E:\\Movies' });
+ vi.stubGlobal('fetch', fetch);
+ const { el } = mount();
+ const pickButtons = el.querySelectorAll('.configpick');
+ expect(pickButtons).toHaveLength(1);
+ expect(el.querySelector('.configdir')?.children[1]).toBe(pickButtons[0]);
+ el.querySelector<HTMLButtonElement>('.configpick')?.click();
+ await settle();
+ const [url, init] = fetch.mock.calls[0] ?? [];
+ expect(url).toBe(PICK_FOLDER_URL);
+ expect(init?.method).toBe('POST');
+ expect(JSON.parse(String(init?.body))).toEqual({ initial: 'D:\\Media' });
+ expect(inputs(el)[0]?.value).toBe('E:\\Movies');
+ expect(el.querySelector('.configpick')?.getAttribute('aria-busy'), '对话框关了忙态要撤掉').toBeNull();
+ });
+
+ it('取消什么也不改;打不开对话框时原因写在这一行下面', async () => {
+ vi.stubGlobal('fetch', fetchMock(200, { path: null }));
+ const { el } = mount();
+ el.querySelector<HTMLButtonElement>('.configpick')?.click();
+ await settle();
+ expect(inputs(el)[0]?.value).toBe('D:\\Media');
+ expect(el.querySelector('.configbad')).toBeNull();
+ vi.stubGlobal('fetch', fetchMock(501, { error: '这个系统上没有可用的文件夹对话框' }));
+ el.querySelector<HTMLButtonElement>('.configpick')?.click();
+ await settle();
+ expect(el.querySelector('.configdir .configbad')?.textContent).toContain('没有可用的文件夹对话框');
+ });
+});
+
+describe('保存', () => {
+ it('提交带上指纹、全部文件夹、端口与是否扫描,成功后发过去时回执并留下新地址', async () => {
+ const fetch = fetchMock(200, { saved: true, url: 'http://127.0.0.1:9124/', revision: 'rev-2' });
+ vi.stubGlobal('fetch', fetch);
+ const { el, receipt } = mount();
+ const port = el.querySelector<HTMLInputElement>('#configPort');
+ if (!port) throw new Error('端口输入框没有画出来');
+ port.value = '9124';
+ port.dispatchEvent(new Event('input'));
+ await settle();
+ submit(el);
+ await settle();
+ const [url, init] = fetch.mock.calls[0] ?? [];
+ expect(url).toBe(CONFIGURATION_URL);
+ expect(init?.method).toBe('POST');
+ expect(JSON.parse(String(init?.body))).toEqual({
+ revision: 'rev-1', media_dirs: ['D:\\Media'], port: '9124', scan_now: false,
+ });
+ expect(receipt).toHaveBeenCalledWith('已保存配置');
+ expect(el.querySelector('.geist-note-success')?.textContent).toContain('正在重新启动');
+ expect(el.querySelector<HTMLAnchorElement>('.configsaved a')?.getAttribute('href'))
+ .toBe('http://127.0.0.1:9124/');
+ expect(el.querySelector('form'), '保存后表单不再留在页面上').toBeNull();
+ });
+
+ it('服务端按字段退回的原因写回原位,不发回执', async () => {
+ vi.stubGlobal('fetch', fetchMock(400, {
+ error: '有几项需要修改',
+ errors: { media_dirs: ['', '和上面的文件夹重复了'], port: '端口要在 1024 到 65535 之间' },
+ }));
+ const { el, receipt } = mount({ media_dirs: ['D:\\Media', 'D:\\Media'] });
+ submit(el);
+ await settle();
+ const rows = el.querySelectorAll('.configdir');
+ expect(rows[0]?.querySelector('.configbad')).toBeNull();
+ expect(rows[1]?.querySelector('.configbad')?.textContent).toBe('和上面的文件夹重复了');
+ expect(inputs(el)[1]?.getAttribute('aria-invalid')).toBe('true');
+ expect(el.querySelector('#configPort + .configbad')?.textContent).toContain('端口');
+ expect(receipt).not.toHaveBeenCalled();
+ expect(el.querySelector('.geist-note-error'), '字段级原因不再叠一条整体 Note').toBeNull();
+ });
+
+ it('其它失败留在表单下方等重试', async () => {
+ vi.stubGlobal('fetch', fetchMock(409, { error: '配置已变更,请刷新后再保存' }));
+ const { el } = mount();
+ submit(el);
+ await settle();
+ expect(el.querySelector('.geist-note-error')?.textContent).toContain('配置已变更');
+ expect(el.querySelector('form')).not.toBeNull();
+ expect(el.querySelector('.geist-button.primary')?.getAttribute('aria-busy'), '失败后忙态要撤掉').toBeNull();
+ });
+});
+
+describe('不能编辑时', () => {
+ it('只说原因和运行信息,不画表单', () => {
+ const { el } = mount({ editable: false, notice: '请在运行 Peach 的电脑上打开配置' });
+ expect(el.querySelector('form')).toBeNull();
+ expect(el.querySelector('.geist-note-secondary')?.textContent).toContain('请在运行 Peach 的电脑上打开配置');
+ expect([...el.querySelectorAll('.configfacts dt')].map((dt) => dt.textContent)).toEqual(['版本', 'FFmpeg']);
+ });
+
+ it('首屏取数失败时画原因', () => {
+ const el = document.createElement('div');
+ document.body.append(el);
+ render(<Configuration receipt={vi.fn()} data={null} error="请先完成首次设置" />, el);
+ expect(el.querySelector('.geist-note-error')?.textContent).toContain('请先完成首次设置');
+ });
+});
diff --git a/frontend/test/islands.test.ts b/frontend/test/islands.test.ts
index 4f38c0174..bd21b3982 100644
--- a/frontend/test/islands.test.ts
+++ b/frontend/test/islands.test.ts
@@ -22,7 +22,7 @@ afterEach(() => {
describe('island 注册表', () => {
it('登记的名字就是遗留路由能挂载的名字', () => {
- expect(islandNames()).toEqual(['quality-goals']);
+ expect(islandNames()).toEqual(['quality-goals', 'configuration']);
});
it('未注册的名字立刻失败,不是静默什么都不画', async () => {
diff --git a/frontend/test/stubs/legacy-ui.ts b/frontend/test/stubs/legacy-ui.ts
index 3c88d29e2..81398f892 100644
--- a/frontend/test/stubs/legacy-ui.ts
+++ b/frontend/test/stubs/legacy-ui.ts
@@ -11,6 +11,20 @@ export const emptyStateHtml = (
+ `<div class="es-icon" data-icon="${iconName}"></div>`
+ `<div class="es-copy"><h3>${title}</h3><p>${description}</p></div></div>`;
+export const fieldsetTitle = (id: string, title: string): string =>
+ `<h3 class="geist-fieldset-title" id="${id}">${title}</h3>`;
+
+export const setActionBusy = (control: Element | null, busy = true): void => {
+ if (!control) return;
+ if (busy) {
+ control.setAttribute('aria-busy', 'true');
+ control.setAttribute('aria-disabled', 'true');
+ } else {
+ control.removeAttribute('aria-busy');
+ control.removeAttribute('aria-disabled');
+ }
+};
+
export const noteHtml = (
message: string,
options: { variant?: string; label?: string } = {},
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 5e02b53f1..1f143a2a5 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -54,7 +54,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_link_rediscovery.py", "test_link_label_owner.py",
"test_agency_entity.py"),
"tooling": ("test_scripts.py", "test_auth.py", "test_cli.py", "test_script_policy.py",
- "test_scan.py", "test_onboarding.py", "test_ledger_backups.py",
+ "test_scan.py", "test_onboarding.py", "test_folder_picker.py", "test_ledger_backups.py",
"test_agent_worktree.py", "test_dependency_policy.py",
"test_restart_windows_tray.py",
"test_buildinfo.py", "test_versioning.py",
diff --git a/scripts/vendor_web_dependencies.mjs b/scripts/vendor_web_dependencies.mjs
index 434a04a5b..63a515ba0 100644
--- a/scripts/vendor_web_dependencies.mjs
+++ b/scripts/vendor_web_dependencies.mjs
@@ -85,6 +85,10 @@ const lucideIcons = new Map([
// 名字和上游对不上的只有排序键:Peach 叫 `sort`,Lucide 叫 `sort-desc`。
["sort", "sort-desc"], ["arrow-up", "arrow-up"], ["arrow-down", "arrow-down"],
["calendar", "calendar"], ["download", "download"], ["monitor", "monitor"],
+ // 管理菜单里的「配置」:这台电脑。`monitor` 已经归详情页的分辨率,不能兼任。
+ ["computer", "computer"],
+ // 配置页每行文件夹的「选择文件夹」:弹系统对话框去挑。`folder-open` 归「打开位置」,不兼任。
+ ["folder-search", "folder-search"],
]);
// 自绘 symbol:没有上游可对,所以在这里逐个点名。下面那道分区检查要求雪碧图里
diff --git a/src/peach/api.py b/src/peach/api.py
index 3a47e6cc3..2c143e7ec 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -25,9 +25,10 @@ from contextlib import asynccontextmanager
from typing import Any
from urllib.parse import quote
-from fastapi import FastAPI, HTTPException, Request
-from fastapi.responses import JSONResponse, PlainTextResponse, RedirectResponse
+from fastapi import FastAPI, Request
+from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
+from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.gzip import DEFAULT_EXCLUDED_CONTENT_TYPES, GZipMiddleware
from . import __version__, web_contract, web_follow
@@ -73,6 +74,13 @@ COMPRESSION_EXCLUDED_TYPES = (
)
+#: Starlette 自己抛的那几种 HTTPException 带的是英文 detail,给人看之前换成中文。
+_DEFAULT_DETAILS = {
+ "Not Found": "这个地址下没有页面。",
+ "Method Not Allowed": "这个地址不接受这种请求。",
+}
+
+
def _offline_response(exc: MediaOffline) -> JSONResponse:
"""脱盘:来源盘整体不在,客户端据此显示「脱盘模式」而不是当成文件丢失。"""
response = JSONResponse(
@@ -227,9 +235,24 @@ def create_app(
def _asset_login_required_handler(request: Request, exc: AssetLoginRequired):
return PlainTextResponse("需要 ?t=口令", status_code=401)
- @app.exception_handler(HTTPException)
- def _http_exception_handler(request: Request, exc: HTTPException):
- return JSONResponse({"error": str(exc.detail)}, status_code=exc.status_code)
+ # 挂在 Starlette 的基类上:路由没匹配到的 404 是它抛的,不是 FastAPI 子类,
+ # 只挂子类的话地址栏敲错一个字母仍会看到一行 JSON。
+ @app.exception_handler(StarletteHTTPException)
+ def _http_exception_handler(request: Request, exc: StarletteHTTPException):
+ detail = exc.detail
+ if isinstance(detail, dict):
+ # 表单校验那种带字段明细的 4xx:`message` 是总话,其余键原样带给页面。
+ body = {"error": str(detail.get("message", "")), **{k: v for k, v in detail.items() if k != "message"}}
+ else:
+ body = {"error": _DEFAULT_DETAILS.get(str(detail), str(detail))}
+ # 浏览器地址栏直接打开一个页面路径撞上 403/404/409 时,给人看的是一页话,
+ # 不是一行 JSON;`/api/` 与脚本取数(Accept 里没有 text/html)照旧回 JSON。
+ navigation = (request.method in {"GET", "HEAD"} and not request.url.path.startswith("/api/")
+ and "text/html" in request.headers.get("accept", ""))
+ if navigation:
+ return HTMLResponse(routes_pages.error_page(exc.status_code, body["error"]),
+ status_code=exc.status_code)
+ return JSONResponse(body, status_code=exc.status_code)
# 第三方前端依赖固定版本并随 Peach 自托管;局域网断网时仍可播放。
app.mount(
@@ -263,7 +286,7 @@ def create_app(
# 健康检查常被 HEAD 探测(`curl -I`、各种 uptime 工具)。本仓库其他公开端点
# 都显式声明了 GET+HEAD,只有这个漏了,HEAD 会拿到 405。
@app.api_route("/healthz", methods=["GET", "HEAD"])
- def healthz(ready: bool = False):
+ def healthz(request: Request, ready: bool = False):
from .health import database_status, readiness
if ready:
result = readiness(settings)
@@ -275,6 +298,9 @@ def create_app(
return {"ok": True, "service": "peach-api", "version": __version__, "mode": "fastapi",
# 这台机器跑过 `peach init` 没有。未配置时服务照常起,只是没有数据。
"configured": settings.configured,
+ # 这次请求的发起方能不能改这台机器的配置(独立包、回环地址)。它随调用方
+ # 变化,只决定管理菜单里「配置」显不显示;拒绝写入的判定在端点自己那里。
+ "configurable": routes_configuration.configurable(request),
"db": database_status(settings.db_path),
"ffmpeg": ffmpeg.source if ffmpeg else "unavailable",
"mdns": mdns.status if mdns is not None else "disabled",
diff --git a/src/peach/folder_picker.py b/src/peach/folder_picker.py
new file mode 100644
index 000000000..0ac77afe3
--- /dev/null
+++ b/src/peach/folder_picker.py
@@ -0,0 +1,188 @@
+"""让运行 Peach 的这台电脑弹系统自带的文件夹对话框,把选中的绝对路径交回页面。
+
+浏览器自己拿不到本机绝对路径:`webkitdirectory` 只给相对名,File System Access API 只给
+句柄。首启页和配置页要写的偏偏就是绝对路径。Peach 与浏览器在同一台机器上,所以由服务
+进程代为弹窗:Windows 走 Shell 的 `IFileOpenDialog`(带地址栏、能直接粘路径的那种
+选择框,`FOS_PICKFOLDERS`),macOS 走 AppleScript 的 `choose folder`。两者都是系统自带,
+不为一个对话框引入 tkinter 或 GUI 框架。
+
+调用方只在回环地址上开放这条路:否则局域网里任何人都能让这台电脑弹窗。
+
+Windows 这里刻意用 `powershell.exe`(Windows PowerShell 5.1):它在每台 Windows 上都有,
+pwsh 7 是另装的。它自带的 `FolderBrowserDialog` 是 XP 时代的树形面板、没有地址栏,所以
+用 `Add-Type` 编一段 COM 互操作直接调 `IFileOpenDialog`。脚本以 `-EncodedCommand` 传入,
+避开引号与中文的转义。
+"""
+from __future__ import annotations
+
+import base64
+import os
+import subprocess
+import sys
+import threading
+
+__all__ = ["PickerBusy", "PickerUnavailable", "command", "pick_folder"]
+
+
+class PickerUnavailable(RuntimeError):
+ """这台机器上没有可用的文件夹对话框,或者对话框没能打开。"""
+
+
+class PickerBusy(RuntimeError):
+ """已经有一个对话框开着:系统对话框是模态的,第二个只会藏在第一个后面。"""
+
+
+#: 一个用户一次只会看一个对话框;第二个请求直接拒绝,不排队。
+_LOCK = threading.Lock()
+
+#: 用户在对话框里翻多久都行,但进程不能被一个忘了关的窗口永久占住。
+DIALOG_TIMEOUT_SECONDS = 15 * 60
+
+PROMPT = "选择媒体文件夹"
+
+#: `IFileOpenDialog` 的最小互操作:vtable 顺序必须与 shobjidl 一致,一个都不能少。
+#: FOS_NOCHANGEDIR 0x8 不改进程工作目录,FOS_PICKFOLDERS 0x20 选文件夹,
+#: FOS_FORCEFILESYSTEM 0x40 只允许真实路径(库、此电脑这类虚拟节点不能当结果)。
+_WINDOWS_INTEROP = r"""
+using System;
+using System.Runtime.InteropServices;
+namespace PeachPick {
+ [ComImport, Guid("42f85136-db7e-439c-85f1-e4075d135fc8"),
+ InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ public interface IFileOpenDialog {
+ [PreserveSig] int Show(IntPtr parent);
+ void SetFileTypes(uint count, IntPtr filterSpec);
+ void SetFileTypeIndex(uint index);
+ void GetFileTypeIndex(out uint index);
+ void Advise(IntPtr events, out uint cookie);
+ void Unadvise(uint cookie);
+ void SetOptions(uint options);
+ void GetOptions(out uint options);
+ void SetDefaultFolder(IShellItem item);
+ void SetFolder(IShellItem item);
+ void GetFolder(out IShellItem item);
+ void GetCurrentSelection(out IShellItem item);
+ void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
+ void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
+ void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
+ void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text);
+ void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
+ void GetResult(out IShellItem item);
+ void AddPlace(IShellItem item, int placement);
+ void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension);
+ void Close(int hr);
+ void SetClientGuid(ref Guid guid);
+ void ClearClientData();
+ void SetFilter(IntPtr filter);
+ void GetResults(out IntPtr items);
+ void GetSelectedItems(out IntPtr items);
+ }
+ [ComImport, Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe"),
+ InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ public interface IShellItem {
+ void BindToHandler(IntPtr bindContext, ref Guid handlerId, ref Guid interfaceId, out IntPtr result);
+ void GetParent(out IShellItem parent);
+ void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
+ void GetAttributes(uint mask, out uint attributes);
+ void Compare(IShellItem other, uint hint, out int order);
+ }
+ [ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
+ public class FileOpenDialogRCW { }
+ public static class Picker {
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
+ static extern IShellItem SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid interfaceId);
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
+ static extern IntPtr FindWindow(string className, string title);
+ [DllImport("user32.dll")]
+ static extern bool SetWindowPos(IntPtr window, IntPtr insertAfter, int x, int y, int width, int height, uint flags);
+ [DllImport("user32.dll")]
+ static extern bool SetForegroundWindow(IntPtr window);
+ // 服务进程在后台,Windows 不给它前台权:对话框会开在浏览器后面。等它的窗口
+ // 出现后置顶(SetWindowPos 到 HWND_TOPMOST 不需要前台权),模态窗关掉即消失。
+ static void Raise(string title) {
+ for (int attempt = 0; attempt < 200; attempt++) {
+ var window = FindWindow("#32770", title);
+ if (window != IntPtr.Zero) {
+ SetWindowPos(window, new IntPtr(-1), 0, 0, 0, 0, 0x1 | 0x2 | 0x40);
+ SetForegroundWindow(window);
+ return;
+ }
+ System.Threading.Thread.Sleep(50);
+ }
+ }
+ public static string Pick(string title, string initial) {
+ var dialog = (IFileOpenDialog)new FileOpenDialogRCW();
+ new System.Threading.Thread(() => Raise(title)).Start();
+ dialog.SetOptions(0x8 | 0x20 | 0x40);
+ dialog.SetTitle(title);
+ if (!string.IsNullOrEmpty(initial) && System.IO.Directory.Exists(initial)) {
+ var shellItem = typeof(IShellItem).GUID;
+ try { dialog.SetFolder(SHCreateItemFromParsingName(initial, IntPtr.Zero, ref shellItem)); }
+ catch (Exception) { }
+ }
+ if (dialog.Show(IntPtr.Zero) != 0) return null;
+ IShellItem picked;
+ dialog.GetResult(out picked);
+ string path;
+ picked.GetDisplayName(0x80058000, out path);
+ return path;
+ }
+ }
+}
+"""
+
+#: 所有者窗口留空:Shell 自己会把新对话框放到前台;挂在一个透明置顶 Form 上的对话框
+#: 反而跟着所有者一起不可见,进程就卡在 Show 里。
+_WINDOWS_SCRIPT = """
+[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
+Add-Type -TypeDefinition @'
+@INTEROP@
+'@
+$picked = [PeachPick.Picker]::Pick('@PROMPT@', $env:PEACH_PICK_INITIAL)
+if ($picked) { [Console]::Out.Write($picked) }
+""".replace("@INTEROP@", _WINDOWS_INTEROP.strip()).replace("@PROMPT@", PROMPT)
+
+
+def _applescript_string(text: str) -> str:
+ return text.replace("\\", "\\\\").replace('"', '\\"')
+
+
+def command(initial: str | None, platform: str = sys.platform) -> tuple[list[str], dict[str, str]]:
+ """这个平台弹对话框的命令行,以及要附加的环境变量。"""
+ if platform == "win32":
+ encoded = base64.b64encode(_WINDOWS_SCRIPT.encode("utf-16-le")).decode("ascii")
+ argv = ["powershell.exe", "-NoProfile", "-NonInteractive", "-STA", "-EncodedCommand", encoded]
+ return argv, {"PEACH_PICK_INITIAL": initial or ""}
+ if platform == "darwin":
+ script = f'choose folder with prompt "{_applescript_string(PROMPT)}"'
+ if initial and os.path.isdir(initial):
+ script += f' default location POSIX file "{_applescript_string(initial)}"'
+ return ["osascript", "-e", f"POSIX path of ({script})"], {}
+ raise PickerUnavailable("这个系统上没有可用的文件夹对话框")
+
+
+def pick_folder(initial: str | None = None, *, platform: str = sys.platform,
+ run=subprocess.run) -> str | None:
+ """弹对话框,返回选中的绝对路径;用户取消返回 None。"""
+ argv, extra = command(initial, platform)
+ if not _LOCK.acquire(blocking=False):
+ raise PickerBusy("已经有一个选择文件夹的窗口开着")
+ try:
+ flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if platform == "win32" else 0
+ try:
+ result = run(argv, capture_output=True, env={**os.environ, **extra},
+ timeout=DIALOG_TIMEOUT_SECONDS, creationflags=flags)
+ except subprocess.TimeoutExpired:
+ return None
+ finally:
+ _LOCK.release()
+ stderr = (result.stderr or b"").decode("utf-8", "replace")
+ if result.returncode != 0:
+ # osascript 在用户取消时以 1 退出,stderr 是 "User canceled.";这不是失败。
+ if "canceled" in stderr.lower():
+ return None
+ raise PickerUnavailable("没能打开文件夹对话框")
+ text = (result.stdout or b"").decode("utf-8", "replace").strip()
+ if platform == "darwin" and len(text) > 1:
+ text = text.rstrip("/")
+ return text or None
diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.py
index 947ec2753..9ead02c9f 100644
--- a/src/peach/routes_configuration.py
+++ b/src/peach/routes_configuration.py
@@ -1,106 +1,147 @@
-"""本机配置表单:读取、校验、原子保存与托盘应用请求。"""
+"""本机配置的 JSON 契约:读取、校验、原子保存与托盘重启请求。
+
+页面本体是 `frontend/src/islands/configuration.tsx`,挂在主站的 `/configuration` 路由里
+(ADR-0022);这里只回数据。两道门都在服务端:只放行回环地址,只在独立包里可写。
+手机上的管理菜单不列这一页,靠的是 `/healthz` 的 `configurable`,但那只是入口的显隐,
+拒绝写入的判定在这里。
+"""
from __future__ import annotations
from dataclasses import replace
import hashlib
-from html import escape
import os
import shutil
import threading
-from urllib.parse import parse_qs
+from typing import Any
-from fastapi import APIRouter, Depends, HTTPException, Request
-from fastapi.responses import HTMLResponse
+from fastapi import APIRouter, Body, Depends, HTTPException, Request
-from . import distribution, onboarding, settings_file
-from .routes_auth import require_page_auth
-from .routes_pages import _check_html, _document, _field_html, _media_dirs_html, runtime_facts_html
+from . import distribution, folder_picker, onboarding, settings_file
+from .routes_auth import require_auth
+from .routes_pages import runtime_facts
router = APIRouter()
_SAVE_LOCK = threading.Lock()
RELOAD_NAME = onboarding.RELOAD_NAME
+#: 不在独立包里时页面上代替表单的那句话。
+FILE_MANAGED_NOTICE = "此部署通过配置文件管理服务,请在本机编辑下方的设置文件。"
def revision(config) -> str:
return hashlib.sha256(config.path.read_bytes()).hexdigest()
-def page(config, *, values=None, errors=None, saved=False) -> str:
- values, errors = values or {}, errors or {}
- media = list(config.mounts.get("local") or config.locations.get("local", ()))
- body = '<a href="/">返回馆藏</a><h1>配置 Peach</h1>'
- if saved:
- url = f"http://127.0.0.1:{config.server.port}/"
- body += ('<p role="status">配置已保存,正在重新启动服务。</p>'
- f'<p><a href="{url}">进入馆藏</a></p>'
- f'<meta http-equiv="refresh" content="8;url={url}">')
- else:
- body += '<p class="lede">管理这台电脑的媒体文件夹和访问端口。</p>'
- if distribution.standalone() and not saved:
- body += '<form method="post" action="/configuration">'
- body += f'<input type="hidden" name="revision" value="{revision(config)}">'
- for question in onboarding.questions(config, windows=os.name == "nt"):
- if question.key == "media_dir":
- body += _media_dirs_html(values.get("media_dir", media),
- errors.get("media_dir", []), "")
- elif question.key == "port":
- body += _field_html(question, values.get("port", str(config.server.port)),
- errors.get("port", ""), "")
- body += (_check_html("scan_now", "保存后扫描媒体文件夹", checked=False)
- + '<button type="submit">保存配置</button></form>')
- elif not distribution.standalone():
- body += '<p>此部署通过配置文件管理服务,请在本机编辑下方文件。</p>'
- body += runtime_facts_html(config)
- return _document("Peach · 配置", body)
-
-
-def local_only(request):
+def loopback_client(request: Request) -> bool:
+ """请求来自运行 Peach 的这台电脑。`/healthz` 与两个端点共用同一判据。"""
+ if not request.client or request.client.host not in {"127.0.0.1", "::1"}:
+ return False
+ if distribution.standalone() and request.url.hostname not in {"127.0.0.1", "localhost", "::1"}:
+ return False
+ return True
+
+
+def local_only(request: Request) -> None:
if not request.client or request.client.host not in {"127.0.0.1", "::1"}:
raise HTTPException(403, "请在运行 Peach 的电脑上打开配置")
if distribution.standalone() and request.url.hostname not in {"127.0.0.1", "localhost", "::1"}:
raise HTTPException(403, "请使用本机地址打开配置")
[email protected]("/configuration", response_class=HTMLResponse)
-def configuration(request: Request, _args=Depends(require_page_auth)):
+def configurable(request: Request) -> bool:
+ """这次请求的发起方能不能改这台机器的配置:独立包、已配置、且来自回环地址。"""
+ return (distribution.standalone() and bool(request.app.state.settings.configured)
+ and loopback_client(request))
+
+
+def snapshot(config) -> dict[str, Any]:
+ """配置页首屏要的一切:当前值、修订号、可写与否,以及这台机器的运行信息。"""
+ editable = distribution.standalone()
+ media = config.mounts.get("local") or config.locations.get("local", ())
+ return {
+ "editable": editable,
+ "notice": "" if editable else FILE_MANAGED_NOTICE,
+ "revision": revision(config),
+ "media_dirs": list(media),
+ "port": config.server.port,
+ "facts": [{"term": term, "value": value} for term, value in runtime_facts(config)],
+ }
+
+
[email protected]("/api/configuration")
+def read_configuration(request: Request, _args=Depends(require_auth)):
local_only(request)
config = settings_file.load_config()
if not config.present:
raise HTTPException(409, "请先完成首次设置")
- return HTMLResponse(page(config), headers={"Cache-Control": "no-store"})
+ return snapshot(config)
[email protected]("/configuration", response_class=HTMLResponse)
-async def save_configuration(request: Request, _args=Depends(require_page_auth)):
- local_only(request)
- if not distribution.standalone():
- raise HTTPException(409, "此部署通过配置文件管理服务")
+def _validate(body: dict[str, Any], config) -> tuple[dict[str, Any], dict[str, Any]]:
+ """逐项校验,错误按字段归位:文件夹按行、端口一句。全对时第一个返回值为空。"""
+ errors: dict[str, Any] = {}
+ validated: dict[str, Any] = {}
+ raws = body.get("media_dirs")
+ rows = [str(item) for item in raws] if isinstance(raws, list) else [str(raws or "")]
+ paths, problems = onboarding.read_media_dirs(
+ rows, validate=onboarding.media_dir_validator(windows=os.name == "nt"))
+ if problems:
+ errors["media_dirs"] = problems
+ else:
+ validated["media_dirs"] = paths
+ try:
+ port = onboarding.validate_port(str(body.get("port", "")))
+ onboarding.check_available_port(port, config.server.port)
+ validated["port"] = port
+ except ValueError as exc:
+ errors["port"] = str(exc)
+ return errors, validated
+
+
+def same_origin(request: Request) -> None:
+ """浏览器发来的写请求必须来自 Peach 自己的页面:带了别处的 Origin 就拒。"""
origin = request.headers.get("origin")
if origin and origin.rstrip("/") != str(request.base_url).rstrip("/"):
raise HTTPException(403, "请从 Peach 配置页提交")
- form = parse_qs((await request.body()).decode("utf-8", "replace"), keep_blank_values=True)
- values: dict[str, object] = {key: value[0] for key, value in form.items()}
- values["media_dir"] = list(form.get("media_dir", []))
+
+
[email protected]("/api/pick-folder")
+def pick_folder(request: Request, body: dict[str, Any] = Body(default_factory=dict),
+ _args=Depends(require_auth)):
+ """让运行 Peach 的这台电脑弹系统文件夹对话框,选中的绝对路径交回页面。
+
+ 只对回环地址开放:否则局域网里任何人都能让这台电脑弹窗。首启页和配置页共用这一条,
+ 所以不要求独立包。对话框是模态的,一次只开一个;用户取消时 `path` 为 None。
+ """
+ local_only(request)
+ same_origin(request)
+ initial = body.get("initial")
+ try:
+ path = folder_picker.pick_folder(initial if isinstance(initial, str) and initial else None)
+ except folder_picker.PickerBusy as exc:
+ raise HTTPException(409, str(exc)) from exc
+ except folder_picker.PickerUnavailable as exc:
+ raise HTTPException(501, str(exc)) from exc
+ return {"path": path}
+
+
[email protected]("/api/configuration")
+def save_configuration(request: Request, body: dict[str, Any] = Body(default_factory=dict),
+ _args=Depends(require_auth)):
+ local_only(request)
+ if not distribution.standalone():
+ raise HTTPException(409, "此部署通过配置文件管理服务")
+ same_origin(request)
with _SAVE_LOCK:
config = settings_file.load_config()
- if values.get("revision") != revision(config):
+ if not config.present:
+ raise HTTPException(409, "请先完成首次设置")
+ if body.get("revision") != revision(config):
raise HTTPException(409, "配置已变更,请刷新后再保存")
- errors: dict[str, object] = {}
- validated: dict[str, object] = {}
- paths, problems = onboarding.read_media_dirs(
- values["media_dir"], validate=onboarding.media_dir_validator(windows=os.name == "nt"))
- if problems:
- errors["media_dir"] = problems
- try:
- validated["port"] = onboarding.validate_port(str(values.get("port", "")))
- except ValueError as exc:
- errors["port"] = str(exc)
+ errors, validated = _validate(body, config)
if errors:
- return HTMLResponse(page(config, values=values, errors=errors), status_code=400)
- try:
- onboarding.check_available_port(validated["port"], config.server.port)
- except ValueError as exc:
- return HTMLResponse(page(config, values=values, errors={"port": str(exc)}), status_code=400)
+ # 400 的响应体带每个字段的原因:页面把它写回出错的那一行底下,不是弹一句总话。
+ raise HTTPException(400, {"message": "有几项需要修改", "errors": errors})
+ paths = validated["media_dirs"]
locations, mounts = dict(config.locations), dict(config.mounts)
if os.name == "nt":
locations["local"] = tuple(str(path) for path in paths)
@@ -114,10 +155,11 @@ async def save_configuration(request: Request, _args=Depends(require_page_auth))
shutil.copy2(config.path, config.path.with_suffix(".previous.toml"))
temporary.write_text(settings_file.render(prepared), encoding="utf-8")
os.replace(temporary, config.path)
- if "scan_now" in form:
+ if body.get("scan_now"):
onboarding.request_first_scan(prepared)
config.directory("state").mkdir(parents=True, exist_ok=True)
(config.directory("state") / RELOAD_NAME).write_text("reload", encoding="utf-8")
except OSError as exc:
raise HTTPException(500, f"配置保存失败:{exc}") from exc
- return HTMLResponse(page(prepared, saved=True), headers={"Cache-Control": "no-store"})
+ return {"saved": True, "url": f"http://127.0.0.1:{prepared.server.port}/",
+ "revision": revision(prepared)}
diff --git a/src/peach/routes_pages.py b/src/peach/routes_pages.py
index f0b50856d..689bc2c93 100644
--- a/src/peach/routes_pages.py
+++ b/src/peach/routes_pages.py
@@ -88,7 +88,21 @@ border-radius:var(--control-radius);color:var(--ink-2);cursor:pointer}
.switch label:has(input:focus-visible){outline:2px solid var(--tungsten);outline-offset:2px}
:focus-visible{outline:2px solid var(--tungsten);outline-offset:3px}
.help{margin:6px 0 0;color:var(--muted);font-size:var(--fs-sm)}
-details{margin-top:24px}summary{cursor:pointer;min-height:44px;display:list-item}
+/* 高级设置是 Geist Collapse:summary 是触发器,chevron 紧跟标题,与高度一样 200ms ease-in-out;
+ 折叠体由 /js/ui-components.js 的 wireCollapse 接管。 */
+details{margin-top:24px}
+summary{display:flex;align-items:center;gap:8px;min-height:44px;
+cursor:pointer;list-style:none;font-weight:500;color:var(--ink)}
+summary::-webkit-details-marker{display:none}
+summary svg{width:16px;height:16px;flex:none;stroke:currentColor;fill:none;stroke-width:2;
+stroke-linecap:round;stroke-linejoin:round;color:var(--muted);transition:transform .2s ease-in-out}
+details[open] summary svg{transform:rotate(180deg)}
+/* 折叠体裁切溢出,输入框的焦点环(2px 环加 3px 间距)会被切掉:把裁切框往外放 6px,
+ 横向靠 .fcollapse 的负外边距,纵向靠 .fcollapsebody 的内边距——内边距不能落在
+ .fcollapse 自己身上,否则高度收不到 0。 */
+.fcollapse{overflow:hidden;transition:height .2s ease-in-out;margin:0 -6px;padding:0 6px}
+.fcollapsebody{padding:6px 0}
+details .field{margin-top:0}
.bad{margin:6px 0 0;color:var(--drop);font-size:var(--fs-sm)}
.check{display:flex;align-items:center;gap:12px;min-height:44px;margin:24px 0 0;cursor:pointer}
.pcheck{position:relative;display:grid;place-items:center;width:20px;height:20px;flex:none}
@@ -103,23 +117,28 @@ button[type=submit]{margin-top:32px;width:100%;height:var(--control-h);border:1p
border-radius:var(--control-radius);cursor:pointer;background:var(--ink);color:var(--ground);
font:500 var(--fs-md) system-ui,sans-serif}
button[type=submit]:hover{background:color-mix(in srgb,var(--ink) 88%,var(--ground));color:var(--ground)}
-.dir{display:grid;grid-template-columns:1fr auto;gap:8px;margin-top:8px}
-.dir:first-child{margin-top:0}.dir .bad{grid-column:1/-1;margin:0}
-.dir input[type=text]{min-width:0}
-.rm,.add{height:var(--control-h);border:1px solid var(--line);border-radius:var(--control-radius);
+/* 一行:输入框、选择文件夹、移除。flex 而不是 grid:只剩一行时移除键隐藏,
+ grid 的空轨道会留下一段 gap。 */
+.dir{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}
+.dir:first-child{margin-top:0}.dir .bad{flex-basis:100%;margin:0}
+.dir input[type=text]{flex:1 1 auto;width:auto;min-width:0}
+.rm,.pick,.add{height:var(--control-h);border:1px solid var(--line);border-radius:var(--control-radius);
background:var(--ground);color:var(--ink);cursor:pointer;font:500 var(--fs-sm) system-ui,sans-serif}
-.rm{width:var(--control-h);display:grid;place-items:center;color:var(--muted)}
-.rm svg{width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round}
+.rm,.pick{width:var(--control-h);flex:none;display:grid;place-items:center;color:var(--muted)}
+.rm svg,.pick svg{width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;
+stroke-linejoin:round}
+.pick[aria-busy=true]{color:var(--muted);cursor:progress}
.add{margin-top:8px;padding:0 12px}
-.rm:hover,.add:hover{background:var(--hover);color:var(--ink)}
-.rm[hidden],.add[hidden]{display:none}
+.rm:hover,.pick:hover,.add:hover{background:var(--hover);color:var(--ink)}
+.rm[hidden],.pick[hidden],.add[hidden]{display:none}
+@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
@media(max-width:760px){input[type=text],input[type=number]{font-size:16px}}
@media(max-width:440px){body{padding:24px 20px}h1{font-size:var(--fs-2xl)}}
</style>"""
_SETUP_HEAD = ('<!doctype html>\n<html lang="zh-CN"><head><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width,initial-scale=1">'
- '<meta name="color-scheme" content="light">'
+ '<meta name="color-scheme" content="light dark">'
'<link rel="icon" href="/peach-logo.png" type="image/png">')
#: 键 -> 页面上的题目与一句说明。顺序、默认值与校验仍然来自 `onboarding.questions()`,
@@ -160,9 +179,40 @@ _SETUP_SCRIPT = """<script>
var rows=function(){return list.querySelectorAll('.dir');};
var refresh=function(){
var all=rows();
- all.forEach(function(row){row.querySelector('.rm').hidden=all.length<2;});
+ all.forEach(function(row){
+ row.querySelector('.rm').hidden=all.length<2;
+ row.querySelector('.pick').hidden=false;
+ });
+ };
+ /* 「选择文件夹」让运行 Peach 的这台电脑弹系统对话框,把选中的绝对路径填回这一行:
+ 浏览器自己拿不到本机绝对路径。等待期间按钮置忙,再点不发第二个请求。 */
+ var pickFolder=function(row,button){
+ if(button.getAttribute('aria-busy')==='true'){return;}
+ var input=row.querySelector('input');
+ var bad=row.querySelector('.bad');
+ button.setAttribute('aria-busy','true');button.setAttribute('aria-disabled','true');
+ fetch('/api/pick-folder',{method:'POST',credentials:'same-origin',
+ headers:{'Accept':'application/json','Content-Type':'application/json'},
+ body:JSON.stringify({initial:input.value})})
+ .then(function(response){return response.json().then(function(data){return {ok:response.ok,data:data};});})
+ .then(function(result){
+ if(!result.ok){throw new Error((result.data&&result.data.error)||'没能打开文件夹对话框');}
+ if(result.data.path){
+ input.value=result.data.path;input.setAttribute('aria-invalid','false');
+ if(bad){bad.remove();}
+ }
+ input.focus();
+ })
+ .catch(function(error){
+ var note=bad||document.createElement('p');
+ note.className='bad';note.setAttribute('role','alert');note.textContent=error.message;
+ row.appendChild(note);
+ })
+ .then(function(){button.removeAttribute('aria-busy');button.removeAttribute('aria-disabled');});
};
list.addEventListener('click',function(event){
+ var pick=event.target.closest('.pick');
+ if(pick){pickFolder(pick.closest('.dir'),pick);return;}
var remove=event.target.closest('.rm');
if(!remove||rows().length<2){return;}
remove.closest('.dir').remove();
@@ -185,14 +235,51 @@ _CHECK_SVG = ('<svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="
'<path d="M20 6 9 17l-5-5"/></svg>')
#: 移除一行媒体文件夹的字形(lucide `x`)。
_X_SVG = '<svg viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg>'
+#: 「选择文件夹」(lucide `folder-search`):弹系统对话框去挑一个文件夹。`folder-open` 归
+#: 站内的「打开位置」,不兼任。
+_FOLDER_SVG = ('<svg viewBox="0 0 24 24"><path d="M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 '
+ '1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1"/><path d="m21 21-1.9-1.9"/>'
+ '<circle cx="17" cy="17" r="3"/></svg>')
+#: 折叠触发器右侧的 chevron(lucide `chevron-down`),展开时转 180 度。
+_CHEVRON_SVG = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>'
+#: 高级设置的折叠由站内共用的 wireCollapse 接管:原生 <details> 不过渡高度。
+#: 只在页面里真有 <details> 时才挂,错误页与不带高级设置的首启页不加载这两个模块。
+_COLLAPSE_SCRIPT = ('<script type="module">import{wireCollapse}from"/js/ui-components.js";'
+ 'wireCollapse(document,"details","setup-collapse");</script>')
+
+
+def _theme_tokens() -> str:
+ """主站 `01-base.css` 里的两套色板:浅色的 `:root` 和跟随系统的深色覆盖。
+
+ 首启页在 SPA 外壳之外,但它必须和主站同一副面孔:系统是深色时主站是深色,这一页
+ 也得是,否则设置完一跳进馆藏就像换了个产品。
+ """
+ base = (PROJECT_ROOT / "web" / "css" / "01-base.css").read_text(encoding="utf-8")
+ light = re.search(r":root\s*\{[^}]+\}", base).group(0)
+ dark = re.search(r"@media \(prefers-color-scheme:dark\)\{:root:not\(\[data-theme=\"light\"\]\)\{[^}]+\}\}",
+ base).group(0)
+ return light + dark
-def _document(title: str, body: str) -> str:
+def _scrollbar_rules() -> str:
+ """主站的滚动条:细、无箭头、无轨道底色。首启页装不下时滚起来也得是同一条。"""
base = (PROJECT_ROOT / "web" / "css" / "01-base.css").read_text(encoding="utf-8")
- tokens = re.search(r":root\s*\{[^}]+\}", base).group(0)
+ return re.search(r"\*\{scrollbar-width:thin.*?::-webkit-scrollbar-button\{[^}]*\}", base, re.S).group(0)
+
+
+def error_page(status: int, message: str) -> str:
+ """浏览器导航撞上 403/404/409 时给人看的那一页,不是一行 JSON。"""
+ title = {403: "这里不能打开", 404: "没有这一页", 409: "现在不能这样做"}.get(status, "出了点问题")
+ body = (f'<img class="mark" src="/peach-logo.png" alt=""><h1>{title}</h1>'
+ f'<p class="lede">{escape(message)}</p><p><a href="/">返回馆藏</a></p>')
+ return _document(f"Peach · {title}", body)
+
+
+def _document(title: str, body: str) -> str:
# 页内脚本对两张页面都生效:找不到对应控件时它什么也不做。
- return (f"{_SETUP_HEAD}<title>{title}</title><style>{tokens}</style>{_SETUP_STYLE}"
- f"</head><body><main>{body}</main>{_SETUP_SCRIPT}</body></html>\n")
+ collapse = _COLLAPSE_SCRIPT if "<details" in body else ""
+ return (f"{_SETUP_HEAD}<title>{title}</title><style>{_theme_tokens()}{_scrollbar_rules()}</style>"
+ f"{_SETUP_STYLE}</head><body><main>{body}</main>{_SETUP_SCRIPT}{collapse}</body></html>\n")
def _check_html(name: str, text_html: str, *, checked: bool) -> str:
@@ -202,22 +289,26 @@ def _check_html(name: str, text_html: str, *, checked: bool) -> str:
+ f'><span aria-hidden="true">{_CHECK_SVG}</span></span><span>{text_html}</span></label>')
-def runtime_facts_html(config) -> str:
- """这台机器上 Peach 的位置与版本:设置完成页和配置页共用同一份。"""
+def runtime_facts(config) -> tuple[tuple[str, str], ...]:
+ """这台机器上 Peach 的位置与版本:设置完成页和 `/api/configuration` 共用同一份。"""
from . import __version__
from .ffmpeg import FFmpegResolver
available = FFmpegResolver(config.directory("tools") / "ffmpeg").ffmpeg() is not None
ffmpeg = "可用" if available else "未安装;MP4 可直接播放,转码和缩略图需要安装 FFmpeg。"
- rows = (
+ return (
("版本", __version__),
("数据目录", str(config.data_root)),
("设置文件", str(config.path)),
("日志目录", str(config.directory("logs"))),
("FFmpeg", ffmpeg),
)
+
+
+def runtime_facts_html(config) -> str:
return ("<h2>运行信息</h2><dl>"
- + "".join(f"<dt>{escape(term)}</dt><dd>{escape(value)}</dd>" for term, value in rows)
+ + "".join(f"<dt>{escape(term)}</dt><dd>{escape(value)}</dd>"
+ for term, value in runtime_facts(config))
+ "</dl>")
@@ -232,6 +323,7 @@ def _media_dir_row(value: str, error: str, *, first: bool) -> str:
return (f'<div class="dir"><input name="media_dir" type="text"{attrs} autocomplete="off" '
f'spellcheck="false" aria-invalid="{"true" if error else "false"}" '
f'value="{escape(value, quote=True)}">'
+ f'<button type="button" class="pick" aria-label="选择文件夹" hidden>{_FOLDER_SVG}</button>'
f'<button type="button" class="rm" aria-label="移除这个文件夹" hidden>{_X_SVG}</button>'
+ (f'<p class="bad" role="alert">{escape(error)}</p>' if error else "")
+ "</div>")
@@ -329,7 +421,7 @@ def setup_page(
field = _field_html(question, value, str(errors.get(question.key, "")), "")
if distribution.standalone() and question.key == "port":
opened = " open" if errors.get("port") else ""
- field = f'<details{opened}><summary>高级设置</summary>{field}</details>'
+ field = f'<details{opened}><summary><span>高级设置</span>{_CHEVRON_SVG}</summary>{field}</details>'
fields.append(field)
filled = [path for path in media_dirs if path]
if distribution.standalone() or not filled:
@@ -673,6 +765,9 @@ def peach_logo():
@router.api_route("/follow", methods=["GET", "HEAD"])
@router.api_route("/follow-manage", methods=["GET", "HEAD"])
@router.api_route("/follow/item/{item_id}", methods=["GET", "HEAD"])
+# 配置页是主站里的一屏(island),数据走 `/api/configuration`。未配置时 `index()` 给的是
+# 首次运行表单,正好就是「请先完成首次设置」该长的样子。
[email protected]_route("/configuration", methods=["GET", "HEAD"])
def client_route(request: Request, item_id: int | None = None,
seed_id: int | None = None, mix_item_id: int | None = None,
part_seed_id: int | None = None, part_item_id: int | None = None,
diff --git a/tests/test_folder_picker.py b/tests/test_folder_picker.py
new file mode 100644
index 000000000..0950dc90f
--- /dev/null
+++ b/tests/test_folder_picker.py
@@ -0,0 +1,102 @@
+"""`peach.folder_picker`:由运行 Peach 的这台电脑弹系统文件夹对话框,替浏览器拿到绝对路径。
+
+对话框本身没法在测试里弹,这里钉住的是命令行的形状、取消与失败的区分,以及一次只开一个。
+"""
+from __future__ import annotations
+
+import base64
+import subprocess
+import unittest
+from unittest import mock
+
+from peach import folder_picker
+
+
+class FakeRun:
+ def __init__(self, stdout: bytes = b"", returncode: int = 0, stderr: bytes = b""):
+ self.stdout, self.returncode, self.stderr = stdout, returncode, stderr
+ self.calls: list[tuple[list[str], dict]] = []
+
+ def __call__(self, argv, **kwargs):
+ self.calls.append((list(argv), kwargs))
+ return subprocess.CompletedProcess(argv, self.returncode, self.stdout, self.stderr)
+
+
+class CommandTests(unittest.TestCase):
+ def test_windows_uses_the_modern_folder_picker_through_the_built_in_powershell(self):
+ """`powershell.exe` 每台 Windows 都有,pwsh 7 是另装的;脚本以 -EncodedCommand 传,不碰引号转义。
+
+ 对话框是 Shell 的 `IFileOpenDialog`(带地址栏),不是 Windows Forms 那块树形面板。
+ """
+ argv, env = folder_picker.command(r"D:\Media", platform="win32")
+ self.assertEqual(argv[0], "powershell.exe")
+ self.assertIn("-STA", argv, "COM 对话框要求单线程套间")
+ self.assertEqual(argv[-2], "-EncodedCommand")
+ script = base64.b64decode(argv[-1]).decode("utf-16-le")
+ self.assertIn('Guid("42f85136-db7e-439c-85f1-e4075d135fc8")', script, "IFileOpenDialog 的接口 ID")
+ self.assertIn("dialog.SetOptions(0x8 | 0x20 | 0x40)", script, "FOS_NOCHANGEDIR、FOS_PICKFOLDERS、FOS_FORCEFILESYSTEM")
+ self.assertNotIn("FolderBrowserDialog", script)
+ self.assertIn("$env:PEACH_PICK_INITIAL", script)
+ self.assertIn("dialog.Show(IntPtr.Zero)", script, "不挂所有者窗口:透明置顶的 Form 会把对话框一起藏起来")
+ self.assertIn("SetWindowPos(window, new IntPtr(-1)", script, "后台服务进程没有前台权,对话框要自己置顶")
+ self.assertNotIn("System.Windows.Forms", script)
+ self.assertIn(f"Pick('{folder_picker.PROMPT}', $env:PEACH_PICK_INITIAL)", script)
+ self.assertEqual(env, {"PEACH_PICK_INITIAL": r"D:\Media"})
+
+ def test_macos_uses_applescript_choose_folder_and_escapes_the_initial_path(self):
+ with mock.patch("os.path.isdir", return_value=True):
+ argv, env = folder_picker.command('/Volumes/My "Disk"', platform="darwin")
+ self.assertEqual(argv[:2], ["osascript", "-e"])
+ self.assertTrue(argv[2].startswith("POSIX path of (choose folder with prompt"))
+ self.assertIn('default location POSIX file "/Volumes/My \\"Disk\\""', argv[2])
+ self.assertEqual(env, {})
+
+ def test_a_missing_initial_folder_is_not_passed_to_applescript(self):
+ """`choose folder` 收到不存在的 default location 会直接报错,还不如不给。"""
+ with mock.patch("os.path.isdir", return_value=False):
+ argv, _ = folder_picker.command("/gone", platform="darwin")
+ self.assertNotIn("default location", argv[2])
+
+ def test_other_platforms_say_so(self):
+ with self.assertRaises(folder_picker.PickerUnavailable):
+ folder_picker.command(None, platform="linux")
+
+
+class PickTests(unittest.TestCase):
+ def test_the_chosen_path_comes_back_stripped_and_the_initial_path_travels_by_environment(self):
+ run = FakeRun(b"E:\\Movies\r\n")
+ chosen = folder_picker.pick_folder(r"D:\Media", platform="win32", run=run)
+ self.assertEqual(chosen, r"E:\Movies")
+ (argv, kwargs), = run.calls
+ self.assertEqual(argv[0], "powershell.exe")
+ self.assertEqual(kwargs["env"]["PEACH_PICK_INITIAL"], r"D:\Media")
+ self.assertTrue(kwargs["capture_output"])
+
+ def test_cancelling_yields_none_on_both_platforms(self):
+ self.assertIsNone(folder_picker.pick_folder(platform="win32", run=FakeRun(b"")))
+ cancelled = FakeRun(b"", returncode=1, stderr=b"execution error: User canceled. (-128)\n")
+ self.assertIsNone(folder_picker.pick_folder(platform="darwin", run=cancelled))
+
+ def test_macos_paths_lose_the_trailing_slash(self):
+ self.assertEqual(folder_picker.pick_folder(platform="darwin", run=FakeRun(b"/Volumes/Media/\n")),
+ "/Volumes/Media")
+ self.assertEqual(folder_picker.pick_folder(platform="darwin", run=FakeRun(b"/\n")), "/")
+
+ def test_a_dialog_that_fails_to_open_is_reported_not_swallowed(self):
+ with self.assertRaises(folder_picker.PickerUnavailable):
+ folder_picker.pick_folder(platform="win32", run=FakeRun(b"", returncode=1, stderr=b"boom"))
+
+ def test_a_forgotten_dialog_does_not_hold_the_worker_forever(self):
+ def hang(argv, **kwargs):
+ raise subprocess.TimeoutExpired(argv, kwargs["timeout"])
+ self.assertIsNone(folder_picker.pick_folder(platform="win32", run=hang))
+
+ def test_only_one_dialog_opens_at_a_time(self):
+ """系统对话框是模态的,第二个只会藏在第一个后面。"""
+ with folder_picker._LOCK:
+ with self.assertRaises(folder_picker.PickerBusy):
+ folder_picker.pick_folder(platform="win32", run=FakeRun(b""))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_frontend_build.py b/tests/test_frontend_build.py
index 485f86319..a9c355be0 100644
--- a/tests/test_frontend_build.py
+++ b/tests/test_frontend_build.py
@@ -174,6 +174,48 @@ class IslandSourceContractTests(unittest.TestCase):
self.assertEqual(len(routed), 1, f"quality-goals 声明在 {routed}")
+class ConfigurationIslandContractTests(unittest.TestCase):
+ """配置页搬进 island 之后仍要守住的几条:控件复用、忙态、端点唯一、主动作唯一。"""
+
+ def setUp(self):
+ self.source = (FRONTEND / "src" / "islands" / "configuration.tsx").read_text(
+ encoding="utf-8")
+
+ def test_feedback_and_titles_reuse_the_shared_components(self):
+ """Note、Fieldset 标题与忙态都走 `/js/ui-components.js`,island 里不另画一份。"""
+ self.assertIn("from '@peach/legacy/ui'", self.source)
+ for helper in ("noteHtml(", "fieldsetTitle(", "setActionBusy("):
+ self.assertIn(helper, self.source)
+ self.assertNotIn("disabled=", self.source, "请求等待期用 aria-busy,不用原生 disabled")
+
+ def test_there_is_one_primary_action_and_the_add_row_button_is_not_it(self):
+ """每屏只有一个 `--ink` 底的主动作,是「保存配置」;「添加文件夹」是次级。"""
+ self.assertEqual(self.source.count('class="geist-button primary"'), 1)
+ self.assertIn('class="geist-button configadd"', self.source)
+ self.assertIn('aria-label="移除这个文件夹"', self.source)
+
+ def test_each_row_can_ask_this_machine_for_the_system_folder_dialog(self):
+ """选择键夹在输入框和移除键中间;对话框由服务端弹,页面只等 `path` 回来。"""
+ self.assertIn('class="geist-button configpick" aria-label="选择文件夹"', self.source)
+ self.assertIn('href="#i-folder-search"', self.source)
+ self.assertIn("PICK_FOLDER_URL = '/api/pick-folder'", self.source)
+ pick = self.source.index('class="geist-button configpick"')
+ self.assertLess(self.source.index('class="geist-input"'), pick)
+ self.assertLess(pick, self.source.index('class="geist-button configrm"'))
+
+ def test_validation_reasons_come_from_the_server(self):
+ """字段级原因读 400 的 `errors`,前端不复制一份路径与端口的判定。"""
+ self.assertIn("cause.status !== 400", self.source)
+ self.assertIn("fields.media_dirs", self.source)
+ self.assertIn("fields.port", self.source)
+
+ def test_the_endpoint_is_declared_once(self):
+ sources = sorted(path for path in (FRONTEND / "src").rglob("*.ts*"))
+ declared = [path.name for path in sources
+ if "'/api/configuration'" in path.read_text(encoding="utf-8")]
+ self.assertEqual(declared, ["configuration.tsx"], f"端点声明在 {declared}")
+
+
class SharedStateContractTests(unittest.TestCase):
"""跨岛共享状态只有一个家(ADR-0022)。
diff --git a/tests/test_onboarding.py b/tests/test_onboarding.py
index be1c7082c..d7410632b 100644
--- a/tests/test_onboarding.py
+++ b/tests/test_onboarding.py
@@ -558,6 +558,54 @@ class SetupPageTests(_Case):
self.assertEqual(response.status_code, 403)
self.assertFalse(self.data_root.exists())
+ def test_the_first_run_page_follows_the_system_theme(self):
+ """首启页在 SPA 之外,配色 token 从 `01-base.css` 的两段 `:root` 抽出来,深色系统就深色。"""
+ body = self._get("/").text
+ self.assertIn('<meta name="color-scheme" content="light dark">', body)
+ self.assertIn(":root{", body)
+ self.assertIn('@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){', body)
+ self.assertIn("--ground:", body)
+
+ def test_each_folder_row_can_open_the_system_folder_dialog(self):
+ """选择键夹在输入框和移除键中间,点了让这台电脑弹系统对话框,路径填回这一行。"""
+ body = self._get("/").text
+ self.assertIn('<button type="button" class="pick" aria-label="选择文件夹" hidden>', body)
+ self.assertLess(body.index('class="pick"'), body.index('class="rm"'))
+ self.assertIn("fetch('/api/pick-folder'", body)
+ self.assertIn("button.setAttribute('aria-busy','true')", body)
+ self.assertIn("row.querySelector('.pick').hidden=false", body)
+ with mock.patch("peach.folder_picker.pick_folder", return_value=str(self.media)) as picker:
+ import asyncio
+
+ async def run():
+ async with self._client() as client:
+ return await client.post("/api/pick-folder", json={"initial": "E:/old"})
+
+ response = asyncio.run(run())
+ self.assertEqual(response.status_code, 200, response.text)
+ self.assertEqual(response.json(), {"path": str(self.media)})
+ picker.assert_called_once_with("E:/old")
+
+ def test_advanced_settings_fold_with_the_shared_collapse_and_the_site_scrollbar(self):
+ """高级设置是 Geist Collapse:借主站的 wireCollapse,chevron 与高度都 200ms;滚动条也是主站那条。"""
+ with mock.patch("peach.distribution.standalone", return_value=True):
+ body = self._get("/").text
+ self.assertIn('<summary><span>高级设置</span><svg viewBox="0 0 24 24" aria-hidden="true">', body)
+ self.assertIn('import{wireCollapse}from"/js/ui-components.js";'
+ 'wireCollapse(document,"details","setup-collapse");', body)
+ self.assertIn('.fcollapse{overflow:hidden;transition:height .2s ease-in-out;margin:0 -6px;padding:0 6px}', body)
+ self.assertIn('.fcollapsebody{padding:6px 0}', body, "焦点环要留 6px,不能被折叠体的裁切切掉")
+ self.assertIn('transition:transform .2s ease-in-out}', body)
+ self.assertIn('details .field{margin-top:0}', body, "折叠体里的字段不再叠一层 24px 上边距")
+ self.assertIn('@media (prefers-reduced-motion:reduce)', body)
+ self.assertIn('::-webkit-scrollbar-thumb{background:var(--sb)', body)
+ self.assertIn('*{scrollbar-width:thin;scrollbar-color:var(--sb) transparent}', body)
+ script = self._get("/js/ui-components.js")
+ self.assertEqual(script.status_code, 200, "首启服务没有令牌,共享控件脚本得放行")
+ self.assertIn("export function wireCollapse", script.text)
+ plain = self._get("/").text
+ self.assertNotIn('<script type="module">', plain, "没有高级设置的页面不加载折叠脚本")
+
def test_a_second_submission_refuses_to_overwrite_the_settings_file(self):
self.assertEqual(self._post("/setup", self._form()).status_code, 200)
again = self._post("/setup", self._form(port="9100"))
@@ -587,41 +635,134 @@ class StandaloneConfigurationTests(_Case):
db_path=self.config.data_root / "database" / "ledger.db")),
client=(address, 12345), base_url="http://localhost")
- def test_authenticated_configuration_preserves_values_and_requests_reload(self):
- from peach.routes_configuration import RELOAD_NAME, revision
+ def test_the_configuration_page_is_a_screen_of_the_app_and_its_data_a_json_contract(self):
+ """`/configuration` 是主站外壳里的一屏,表单由 island 画;真相只在 `/api/configuration`。"""
+ from peach.routes_configuration import RELOAD_NAME
with self.client() as client:
headers = {"X-Token": "test-token"}
page = client.get("/configuration", headers=headers)
self.assertEqual(page.status_code, 200)
- self.assertIn("媒体", page.text)
- # 勾选框与运行信息都复用首启页的实现,不再各写一份。
- self.assertIn('<span class="pcheck"><input type="checkbox" name="scan_now" value="y">', page.text)
- self.assertIn("<h2>运行信息</h2>", page.text)
- self.assertIn("<dt>FFmpeg</dt>", page.text)
- self.assertIn('id="add-dir"', page.text, "配置页的媒体文件夹同样是可加减的列表")
+ self.assertIn('id="managebar"', page.text, "配置页由 SPA 外壳承载,不是独立页面")
+ self.assertTrue(client.get("/healthz").json()["configurable"])
+ snapshot = client.get("/api/configuration", headers=headers).json()
+ self.assertTrue(snapshot["editable"])
+ self.assertEqual(snapshot["notice"], "")
+ self.assertEqual(snapshot["media_dirs"], [str(self.media)])
+ self.assertEqual(snapshot["port"], 9123)
+ # 运行信息和首启完成页共用同一份 `runtime_facts`,不再各写一份。
+ self.assertIn("FFmpeg", [fact["term"] for fact in snapshot["facts"]])
self.config.directory("state").mkdir(parents=True, exist_ok=True)
- response = client.post("/configuration", headers=headers, data={
- "revision": revision(self.config), "media_dir": str(self.media), "port": "9124"})
+ response = client.post("/api/configuration", headers=headers, json={
+ "revision": snapshot["revision"], "media_dirs": [str(self.media)], "port": "9124"})
self.assertEqual(response.status_code, 200, response.text)
+ self.assertEqual(response.json()["url"], "http://127.0.0.1:9124/")
self.assertEqual(settings_file.load_config().server.port, 9124)
self.assertTrue(self.config.path.with_suffix(".previous.toml").is_file())
self.assertTrue((self.config.directory("state") / RELOAD_NAME).is_file())
self.assertFalse((self.config.directory("database") / "ledger.db").exists())
+ def test_field_errors_come_back_per_row_and_nothing_is_written(self):
+ from peach.routes_configuration import revision
+ before = self.config.path.read_bytes()
+ with self.client() as client:
+ response = client.post("/api/configuration", headers={"X-Token": "test-token"}, json={
+ "revision": revision(self.config), "media_dirs": [str(self.media), str(self.media)],
+ "port": "not-a-port"})
+ self.assertEqual(response.status_code, 400)
+ body = response.json()
+ self.assertEqual(body["error"], "有几项需要修改")
+ self.assertEqual(body["errors"]["media_dirs"][0], "", "没问题的行给空串,页面据此不画红字")
+ self.assertTrue(body["errors"]["media_dirs"][1], "重复的那一行要点名")
+ self.assertTrue(body["errors"]["port"])
+ self.assertEqual(before, self.config.path.read_bytes())
+
def test_settings_reject_unauthenticated_remote_cross_origin_and_stale_forms(self):
from peach.routes_configuration import revision
- data = {"revision": revision(self.config), "media_dir": str(self.media), "port": "9124"}
+ data = {"revision": revision(self.config), "media_dirs": [str(self.media)], "port": "9124"}
before = self.config.path.read_bytes()
with self.client() as client:
self.assertEqual(client.get("/configuration", follow_redirects=False).status_code, 303)
- response = client.post("/configuration", headers={"X-Token": "test-token", "Origin": "https://example.org"}, data=data)
+ self.assertEqual(client.get("/api/configuration").status_code, 401)
+ response = client.post("/api/configuration", headers={"X-Token": "test-token", "Origin": "https://example.org"}, json=data)
self.assertEqual(response.status_code, 403)
- response = client.post("/configuration", headers={"X-Token": "test-token"}, data={**data, "revision": "stale"})
+ response = client.post("/api/configuration", headers={"X-Token": "test-token"}, json={**data, "revision": "stale"})
self.assertEqual(response.status_code, 409)
with self.client(address="192.0.2.1") as client:
- self.assertEqual(client.get("/configuration", headers={"X-Token": "test-token"}).status_code, 403)
+ headers = {"X-Token": "test-token"}
+ # 外壳照常打开,拒绝的原因由页面里的 Note 说;菜单里根本不会列出这一项。
+ self.assertEqual(client.get("/configuration", headers=headers).status_code, 200)
+ self.assertFalse(client.get("/healthz").json()["configurable"])
+ response = client.get("/api/configuration", headers=headers)
+ self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.json(), {"error": "请在运行 Peach 的电脑上打开配置"})
+ response = client.post("/api/configuration", headers=headers, json=data)
+ self.assertEqual(response.status_code, 403)
self.assertEqual(before, self.config.path.read_bytes())
+ def test_browser_navigations_get_an_error_page_instead_of_raw_json(self):
+ """地址栏里直接打开一个 403/404/409 的路径,看到的是 Peach 的页面,不是一行 JSON。
+
+ `/api/` 下的路径和不要 HTML 的调用方仍拿 JSON——页面脚本按 `error` 字段取原因。
+ """
+ from fastapi import HTTPException
+ from fastapi.testclient import TestClient
+ from peach.api import create_app
+ from peach.config import PeachSettings
+ app = create_app(PeachSettings(configured=True, token="test-token",
+ db_path=self.config.data_root / "database" / "ledger.db"))
+
+ def refuse():
+ raise HTTPException(409, "请先完成首次设置")
+ # 页面 catch-all 排在最后会吃掉一切路径,测试路由要插到它前面。
+ app.add_api_route("/refuse", refuse, methods=["GET"])
+ app.router.routes.insert(0, app.router.routes.pop())
+ with TestClient(app, base_url="http://localhost") as client:
+ page = client.get("/refuse", headers={"Accept": "text/html,application/xhtml+xml"})
+ self.assertEqual(page.status_code, 409)
+ self.assertTrue(page.headers["content-type"].startswith("text/html"))
+ self.assertIn("<h1>现在不能这样做</h1>", page.text)
+ self.assertIn('<p class="lede">请先完成首次设置</p>', page.text)
+ self.assertIn('<a href="/">返回馆藏</a>', page.text)
+ self.assertIn("@media (prefers-color-scheme:dark)", page.text)
+ missing = client.get("/no-such-page", headers={"Accept": "text/html"})
+ self.assertEqual(missing.status_code, 404)
+ self.assertIn("<h1>没有这一页</h1>", missing.text, "路由没匹配到的 404 是 Starlette 抛的,也要成页")
+ self.assertIn("这个地址下没有页面。", missing.text, "Starlette 的英文 detail 不能原样给人看")
+ data = client.get("/refuse", headers={"Accept": "application/json"})
+ self.assertEqual(data.status_code, 409)
+ self.assertEqual(data.json(), {"error": "请先完成首次设置"})
+ api = client.get("/api/configuration", headers={"Accept": "text/html"})
+ self.assertEqual(api.status_code, 401)
+ self.assertEqual(api.headers["content-type"], "application/json")
+
+ def test_the_folder_dialog_is_opened_by_this_machine_for_loopback_callers_only(self):
+ """对话框弹在运行 Peach 的电脑上;局域网、跨站与没登录的请求都不能让它弹。"""
+ from peach import folder_picker
+ headers = {"X-Token": "test-token"}
+ with mock.patch("peach.folder_picker.pick_folder", return_value=str(self.media)) as picker:
+ with self.client() as client:
+ response = client.post("/api/pick-folder", headers=headers, json={"initial": ""})
+ self.assertEqual(response.status_code, 200, response.text)
+ self.assertEqual(response.json(), {"path": str(self.media)})
+ picker.assert_called_once_with(None)
+ crossed = client.post("/api/pick-folder", json={},
+ headers={**headers, "Origin": "https://example.org"})
+ self.assertEqual(crossed.status_code, 403)
+ self.assertEqual(client.post("/api/pick-folder", json={}).status_code, 401)
+ with self.client(address="192.0.2.1") as client:
+ self.assertEqual(client.post("/api/pick-folder", headers=headers, json={}).status_code, 403)
+ self.assertEqual(picker.call_count, 1)
+ with mock.patch("peach.folder_picker.pick_folder",
+ side_effect=folder_picker.PickerUnavailable("这个系统上没有可用的文件夹对话框")):
+ with self.client() as client:
+ response = client.post("/api/pick-folder", headers=headers, json={})
+ self.assertEqual(response.status_code, 501)
+ self.assertEqual(response.json()["error"], "这个系统上没有可用的文件夹对话框")
+ busy = folder_picker.PickerBusy("已经有一个选择文件夹的窗口开着")
+ with mock.patch("peach.folder_picker.pick_folder", side_effect=busy):
+ with self.client() as client:
+ self.assertEqual(client.post("/api/pick-folder", headers=headers, json={}).status_code, 409)
+
def test_standalone_tray_uses_its_own_binary_and_configured_loopback_port(self):
import sys
from peach.tray import _peach_executable, configured_service_specs, normal_url
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 38f976388..845da56cb 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -82,7 +82,7 @@ class StylesheetPartitionTests(unittest.TestCase):
"09-skeleton.css", "10-photolight.css", "11-identity.css", "12-cards.css",
"13-stage.css", "14-player.css", "15-detail.css", "16-settings.css",
"17-overlay.css", "18-drawer.css", "19-immersive.css", "20-offdisk.css",
- "21-online.css", "22-followmanage.css",
+ "21-online.css", "22-followmanage.css", "23-configuration.css",
)
@classmethod
@@ -2920,13 +2920,31 @@ class WebUiSourceTests(unittest.TestCase):
sections = self.page.split("const MANAGE_SECTIONS=[", 1)[1].split("];", 1)[0]
order = [line.split("'")[1] for line in sections.splitlines() if line.strip().startswith("['")]
self.assertEqual(
- order, ["stats", "taste", "review", "cleanup", "trash", "follow", "quality"],
+ order, ["stats", "taste", "review", "cleanup", "trash", "follow", "quality", "configuration"],
"身份注册表保留全部管理页,删掉哪一个就等于让它的标题和直达 URL 一起失效",
)
self.assertPageContains(
- "const MANAGE_MENU_SECTIONS=['stats','taste','cleanup','follow'];")
+ "const MANAGE_MENU_SECTIONS=['stats','taste','cleanup','follow','configuration'];")
self.assertPageContains("manageMenuSections().map(([k,label,ic])=>")
+ def test_the_configuration_entry_only_shows_on_the_machine_that_runs_peach(self):
+ """「配置」改的是这台电脑的文件夹与端口,在手机上点进去只会得到一句拒绝。
+
+ 服务端在 `/healthz` 里按调用方回 `configurable`;菜单第一次画时问一次,答复回来
+ 再补上这一项。它也不进可钉到侧栏的候选:侧栏顺序跨机同步,钉在手机上就是死链接。
+ """
+ self.assertPageContains("['configuration','配置','computer'],")
+ self.assertPageContains("let runtimeConfigurable=null;")
+ self.assertPageContains(" bar.hidden=!current;\n probeConfigurable();")
+ self.assertPageContains("api('/healthz').then(runtime=>{")
+ self.assertPageContains("runtimeConfigurable=!!runtime.configurable;")
+ self.assertPageContains("&&(key!=='configuration'||runtimeConfigurable===true));")
+ self.assertPageContains(
+ "const OPTIONAL_EDGE_ICONS=MANAGE_SECTIONS.filter(([key])=>key!=='configuration')")
+ # 入口只有管理菜单这一处:设置弹层里不再挂一条链接。
+ self.assertPageLacks('href="/configuration"')
+ self.assertPageLacks("媒体文件夹与服务配置")
+
def test_the_follow_management_section_is_named_after_the_page_it_opens(self):
"""管理区那一项叫「关注管理」:它开的是 /follow-manage,不是关注更新流。
@@ -3258,7 +3276,7 @@ class WebUiSourceTests(unittest.TestCase):
'/item/:id', '/follow/item/:id', '/performers', '/creators', '/tags',
'/stats', '/taste', '/review', '/data-cleanup', '/duplicates',
'/resource-sync', '/quality-goals', '/follow', '/follow-manage',
- '/immerse'):
+ '/configuration', '/immerse'):
self.route_entry(match)
# 目录页四态和四种实体页由既有的映射生成:两边各写一份就会出现
# 「路由认得、isCatalogPath 不认得」这种半死路径。
@@ -4625,7 +4643,8 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("const MANAGEMENT_PLACEHOLDERS={")
self.assertPageContains("const managementPlaceholder=path=>")
for path in ("'/stats'", "'/taste'", "'/data-cleanup'", "'/duplicates'",
- "'/review'", "'/quality-goals'", "'/playlists'", "'/follow-manage'"):
+ "'/review'", "'/quality-goals'", "'/playlists'", "'/follow-manage'",
+ "'/configuration'"):
self.assertPageContains(f" {path}:()=>", "占位没有收进唯一那份定义")
self.assertPageContains(f"managementPlaceholder({path})", "路由没有取那份定义")
# /resource-sync 只是数据管理页的锚点,启动占位得是数据管理那张。
@@ -5098,6 +5117,26 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("const props={openItem,javTitleHtml,javDisplayName,srcBadge}")
self.assertPageLacks("data-quality-open")
+ def test_the_configuration_page_is_an_island_inside_the_management_shell(self):
+ """这台电脑的媒体文件夹与端口是主站里的一屏,不是另一套独立页面。
+
+ 遗留层只铺骨架、交容器、发回执;表单与校验回显在 frontend/ 的 island 里,
+ 数据契约由 tests/test_onboarding.py 对 `/api/configuration` 断言。
+ """
+ self.assertRoute('/configuration', "section:'configuration'", "title:'配置'",
+ "openConfiguration(push)")
+ self.assertPageContains("async function openConfiguration(push=true)")
+ self.assertPageContains(
+ "await ui.mountIsland('configuration',$('#stats'),props,"
+ "{isCurrent:()=>surfaceCurrent(surface)})")
+ self.assertPageContains("const props={receipt:message=>actionReceipt(message)};")
+ self.assertPageContains(
+ "document.body.classList.toggle('configuration-layout',current==='configuration');")
+ # 骨架照最终结构:两块同宽的卡,和数据管理那套单列卡片一个轮廓。
+ self.assertPageContains(
+ "'/configuration':()=>`<div class=\"configpage\">${pageSkeletonHtml('正在读取配置',")
+ self.assertPageContains("{cards:true,count:2,fill:false,className:'cleanup-skeleton'})}</div>`,")
+
def test_review_page_is_a_separate_management_layer(self):
self.assertPageContains("route('/review')")
self.assertPageContains("const REVIEW_LABELS={metadata_fields:'元数据字段',creator_tags:'创作者标签'")
@@ -5498,6 +5537,13 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("['immerse','沉浸模式','gallery-vertical-end'],")
self.assertPageContains("<span>进入沉浸模式</span>")
self.assertPageContains("class=\"shorts-enter\" type=\"button\">${icon('play')}")
+ # 管理菜单的「配置」是这台电脑:`monitor` 已归详情页的分辨率,`settings` 归设置弹层。
+ self.assertPageContains("['configuration','配置','computer'],")
+ self.assertPageContains('<symbol id="i-computer" viewBox="0 0 24 24">')
+ # 配置页每行文件夹的「选择文件夹」弹系统对话框去挑:`folder-search`。`folder-open` 归「打开位置」。
+ self.assertPageContains('<symbol id="i-folder-search" viewBox="0 0 24 24">')
+ self.assertIn('href="#i-folder-search"', (Path(__file__).resolve().parents[1] / "frontend" / "src" / "islands" / "configuration.tsx")
+ .read_text(encoding="utf-8"))
# 换下来的三枚没有别的使用者,雪碧图里也不留。
for gone in ("i-monitor-cog", "i-star", "i-volume-2"):
self.assertPageLacks(f'<symbol id="{gone}"')
diff --git a/web/app.js b/web/app.js
index 7206faf3f..afd4f15e7 100644
--- a/web/app.js
+++ b/web/app.js
@@ -137,6 +137,9 @@ const ROUTES=[
open:(params,push)=>openFollow(push),reload:()=>openFollow(false)},
{match:'/follow-manage',section:'follow',title:'关注管理',refresh:'skip',
open:(params,push)=>openFollowManage(push)},
+ // 这台电脑的媒体文件夹与端口。页面是 island,数据走 /api/configuration。
+ {match:'/configuration',section:'configuration',title:'配置',refresh:'reopen',
+ open:(params,push)=>openConfiguration(push)},
{match:'/immerse',nav:'immerse',title:'沉浸模式',
open:(params,push)=>openTok(immerseStartId(),push)},
];
@@ -224,6 +227,9 @@ const MANAGEMENT_PLACEHOLDERS={
// 骨架照 .fsec 的轮廓画三块,六张 16:9 占位说的是另一个页面的结构。
'/follow-manage':()=>`<div class="follow">${pageSkeletonHtml('正在读取关注管理',
{cards:true,count:3,fill:false,className:'followmanage-skeleton'})}</div>`,
+ // 配置页是两块同宽的卡(表单、运行信息),骨架照数据管理那套单列卡片的轮廓画两块。
+ '/configuration':()=>`<div class="configpage">${pageSkeletonHtml('正在读取配置',
+ {cards:true,count:2,fill:false,className:'cleanup-skeleton'})}</div>`,
};
const managementPlaceholder=path=>
(MANAGEMENT_PLACEHOLDERS[path]||(()=>pageSkeletonHtml('正在读取页面')))();
@@ -242,7 +248,7 @@ function renderInitialSurfaceLoading(){
return;
}
const management=new Set(['/stats','/taste','/review','/data-cleanup','/duplicates','/quality-goals',
- '/playlists','/resource-sync','/follow','/follow-manage']);
+ '/playlists','/resource-sync','/follow','/follow-manage','/configuration']);
if(management.has(path)||path.startsWith('/follow/item/')){
hideDiscoveryBars();
const stats=$('#stats');stats.hidden=false;$('#grid').innerHTML='';
@@ -3589,6 +3595,19 @@ async function openQualityGoals(push=true){
await ui.mountIsland('quality-goals',$('#stats'),props,{isCurrent:()=>surfaceCurrent(surface)});
if(surfaceCurrent(surface))window.scrollTo({top:0,behavior:'smooth'});
}
+/* 配置页(这台电脑的媒体文件夹与端口)同样是 island。它只在运行 Peach 的这台电脑上
+ 有意义:服务端按回环地址与独立包两道门放行,手机上的管理菜单也不列它
+ (见 runtimeConfigurable)。保存成功的回执由遗留层的 Toast 发,island 只管表单。 */
+async function openConfiguration(push=true){
+ releaseHoverPreviews();disposeStage(false);enterManagementSurface();
+ if(push)route('/configuration');
+ const surface=claimSurface('/configuration');
+ showManagementBody({placeholder:managementPlaceholder('/configuration')});
+ const ui=await import('/dist/peach-ui.js');
+ const props={receipt:message=>actionReceipt(message)};
+ await ui.mountIsland('configuration',$('#stats'),props,{isCurrent:()=>surfaceCurrent(surface)});
+ if(surfaceCurrent(surface))window.scrollTo({top:0,behavior:'smooth'});
+}
/* ── 在线追更 ──
两个页面,因为是两件事:
@@ -6151,13 +6170,29 @@ const MANAGE_SECTIONS=[
// `/follow`。两处都叫「关注」时,管理菜单和页标题都在说一个它去不到的地方。
['follow','关注管理','rss'],
['quality','高清版','sparkles'],
+ // 这台电脑的媒体文件夹与端口,字形是一台电脑;`settings` 归右上角的设置弹层。
+ ['configuration','配置','computer'],
];
-/* 管理菜单只留四项。人工复核、回收站、高清版都是「收拾库里已有的东西」,
+/* 管理菜单只留五项。人工复核、回收站、高清版都是「收拾库里已有的东西」,
和垃圾文件、重复文件、空文件夹是同一件事的不同步骤,统一从数据管理进;
统计页也因此不再挂链接管理和资源同步这两块跟统计无关的面板。 */
-const MANAGE_MENU_SECTIONS=['stats','taste','cleanup','follow'];
-const manageMenuSections=()=>MANAGE_SECTIONS.filter(([key])=>MANAGE_MENU_SECTIONS.includes(key));
-const OPTIONAL_EDGE_ICONS=MANAGE_SECTIONS.map(([key,label,ic])=>
+const MANAGE_MENU_SECTIONS=['stats','taste','cleanup','follow','configuration'];
+/* 「配置」只对运行 Peach 的这台电脑有意义:服务端按调用方回 `/healthz` 的 `configurable`,
+ 手机和另一台电脑的菜单里不列它。第一次画管理条时问一次,答复回来后重画。 */
+let runtimeConfigurable=null;
+function probeConfigurable(){
+ if(runtimeConfigurable!==null)return;
+ runtimeConfigurable=false;
+ api('/healthz').then(runtime=>{
+ runtimeConfigurable=!!runtime.configurable;
+ if(runtimeConfigurable&&manageSection())buildManageBar();
+ }).catch(()=>{});
+}
+const manageMenuSections=()=>MANAGE_SECTIONS.filter(([key])=>MANAGE_MENU_SECTIONS.includes(key)
+ &&(key!=='configuration'||runtimeConfigurable===true));
+/* 配置页绑定这台机器,不进跨机同步的侧栏顺序:钉到手机的侧栏上只会得到一句「请在运行
+ Peach 的电脑上打开」。 */
+const OPTIONAL_EDGE_ICONS=MANAGE_SECTIONS.filter(([key])=>key!=='configuration').map(([key,label,ic])=>
key==='follow'?['follow-manage',label,ic]
:key==='cleanup'?['data-cleanup',label,ic]:[key,label,ic]);
const NAV_CATALOG=[...EDGE_ICONS,...OPTIONAL_EDGE_ICONS];
@@ -6317,6 +6352,7 @@ function manageSection(){
function buildManageBar(){
const current=manageSection(),bar=$('#managebar');
bar.hidden=!current;
+ probeConfigurable();
// 管理区是行政界面,不该顶着首页的人物/厂牌横条和标签筛选。
// 隐藏 tagbar 的同时同步 count 栏的吸顶偏移:它默认按「顶栏+筛选条」留位,
// 筛选条不在时那个偏移会留出一条 58px 的缝,滚动内容从缝里穿出来。
@@ -6357,6 +6393,7 @@ function paintManageTitle(){
重复文件正文都是全宽网格,跟着居中就是标题在宽屏上凭空左缩一截、跟内容对不齐。 */
document.body.classList.toggle('cleanup-layout',current==='cleanup'&&decodeURIComponent(location.pathname)==='/data-cleanup');
document.body.classList.toggle('follow-manage-layout',decodeURIComponent(location.pathname)==='/follow-manage');
+ document.body.classList.toggle('configuration-layout',current==='configuration');
const entry=MANAGE_SECTIONS.find(([k])=>k===current);
el.hidden=!entry;
// 数据管理之下按路径再分一层(MANAGE_CRUMB_PAGES):垃圾文件/重复文件的
diff --git a/web/css/23-configuration.css b/web/css/23-configuration.css
new file mode 100644
index 000000000..25aff4a58
--- /dev/null
+++ b/web/css/23-configuration.css
@@ -0,0 +1,29 @@
+/* 配置页(/configuration):这台电脑的媒体文件夹与本机端口,加一块运行信息。
+ 两块卡与数据管理 hub 同一条 812px 窄列;卡是 Geist Fieldset:正文 20px 内边距,
+ 底部操作条 --fieldset-bar-h、左说明右动作。 */
+.configuration-layout .managetitle,.configuration-layout .pagelede{width:min(812px,100%);margin-left:auto;margin-right:auto}
+.configpage{width:min(812px,100%);margin:0 auto;display:grid;gap:20px}
+.configfieldset{display:flex;flex-direction:column;min-width:0;margin:0;padding:0;overflow:hidden;
+ border:1px solid var(--line-soft);border-radius:var(--floating-radius);background:var(--surface)}
+.configfieldset>.geist-fieldset-content{flex:1;min-height:0;padding:20px;display:grid;gap:24px}
+.configfieldset .geist-fieldset-title{margin:0}
+.configfieldset>.geist-fieldset-footer{box-sizing:border-box;min-height:var(--fieldset-bar-h);
+ margin:0;padding:8px 16px 8px 20px;display:flex;align-items:center;justify-content:flex-end;gap:8px;
+ border-top:1px solid var(--border-10);background:var(--overlay-5)}
+.configfieldset>.geist-fieldset-footer>p{min-width:0;margin:0 auto 0 0;color:var(--muted);font-size:var(--fs-sm)}
+.configfield>label,.configfield>.configlabel{display:block;margin:0 0 8px;font-weight:500;color:var(--ink)}
+.confighelp{margin:8px 0 0;color:var(--muted);font-size:var(--fs-sm);line-height:1.5}
+.configbad{margin:6px 0 0;color:var(--drop);font-size:var(--fs-sm)}
+/* 一行一个文件夹:输入框、选择文件夹、移除,三者共用 --control-h,差 3px 就不是一行了。
+ flex 而不是 grid:只剩一行时移除键不画,grid 的空轨道会留下一段 gap。 */
+.configdir{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}
+.configdir .geist-input{flex:1 1 auto;width:auto;min-width:0}
+.configdir:first-child{margin-top:0}.configdir .configbad{flex-basis:100%;margin:0}
+.configrm.geist-button,.configpick.geist-button{width:var(--control-h);height:var(--control-h);flex:none;padding:0;color:var(--muted)}
+.configrm.geist-button:hover:not(:disabled),.configpick.geist-button:hover:not(:disabled){color:var(--ink)}
+.configrm svg,.configpick svg{width:16px;height:16px;stroke:currentColor;fill:none}
+.configadd{margin-top:8px}
+.configcheck{display:flex;align-items:center;gap:12px;min-height:32px;cursor:pointer;color:var(--ink)}
+.configfacts{margin:0;display:grid;grid-template-columns:max-content minmax(0,1fr);gap:10px 24px;align-items:baseline}
+.configfacts dt{color:var(--muted);font-size:var(--fs-sm)}.configfacts dd{margin:0;overflow-wrap:anywhere}
+@media(max-width:560px){.configfacts{grid-template-columns:minmax(0,1fr)}.configfacts dd{margin-top:-6px}}
diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.js
index cf7639203..02bbc3c8c 100644
--- a/web/dist/peach-ui.js
+++ b/web/dist/peach-ui.js
@@ -1,21 +1,21 @@
-import { LOC as e, fmtDur as t, fmtSize as n } from "/js/core.js";
-import { emptyStateHtml as r, noteHtml as i } from "/js/ui-components.js";
+import { emptyStateHtml as e, fieldsetTitle as t, noteHtml as n, setActionBusy as r } from "/js/ui-components.js";
+import { LOC as i, fmtDur as a, fmtSize as o } from "/js/core.js";
//#region node_modules/preact/dist/preact.module.js
-var a, o, s, c, l, u, d, f, p, m, h, g, _, v, y, b = {}, x = [], S = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, C = Array.isArray;
-function w(e, t) {
+var s, c, l, u, d, f, p, m, h, g, _, v, y, b, x, S = {}, C = [], w = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, T = Array.isArray;
+function E(e, t) {
for (var n in t) e[n] = t[n];
return e;
}
function ee(e) {
e && e.parentNode && e.parentNode.removeChild(e);
}
-function T(e, t, n) {
- var r, i, o, s = {};
- for (o in t) o == "key" ? r = t[o] : o == "ref" ? i = t[o] : s[o] = t[o];
- if (arguments.length > 2 && (s.children = arguments.length > 3 ? a.call(arguments, 2) : n), typeof e == "function" && e.defaultProps != null) for (o in e.defaultProps) s[o] === void 0 && (s[o] = e.defaultProps[o]);
- return E(e, s, r, i, null);
+function D(e, t, n) {
+ var r, i, a, o = {};
+ for (a in t) a == "key" ? r = t[a] : a == "ref" ? i = t[a] : o[a] = t[a];
+ if (arguments.length > 2 && (o.children = arguments.length > 3 ? s.call(arguments, 2) : n), typeof e == "function" && e.defaultProps != null) for (a in e.defaultProps) o[a] === void 0 && (o[a] = e.defaultProps[a]);
+ return O(e, o, r, i, null);
}
-function E(e, t, n, r, i) {
+function O(e, t, n, r, i) {
var a = {
type: e,
props: t,
@@ -27,68 +27,68 @@ function E(e, t, n, r, i) {
__e: null,
__c: null,
constructor: void 0,
- __v: i ?? ++s,
+ __v: i ?? ++l,
__i: -1,
__u: 0
};
- return i == null && o.vnode != null && o.vnode(a), a;
+ return i == null && c.vnode != null && c.vnode(a), a;
}
-function D(e) {
+function k(e) {
return e.children;
}
-function O(e, t) {
+function A(e, t) {
this.props = e, this.context = t;
}
-function k(e, t) {
- if (t == null) return e.__ ? k(e.__, e.__i + 1) : null;
+function j(e, t) {
+ if (t == null) return e.__ ? j(e.__, e.__i + 1) : null;
for (var n; t < e.__k.length; t++) if ((n = e.__k[t]) != null && n.__e != null) return n.__e;
- return typeof e.type == "function" ? k(e) : null;
+ return typeof e.type == "function" ? j(e) : null;
}
function te(e) {
if (e.__P && e.__d) {
- var t = e.__v, n = t.__e, r = [], i = [], a = w({}, t);
- a.__v = t.__v + 1, o.vnode && o.vnode(a), le(e.__P, a, t, e.__n, e.__P.namespaceURI, 32 & t.__u ? [n] : null, r, n ?? k(t), !!(32 & t.__u), i), a.__v = t.__v, a.__.__k[a.__i] = a, de(r, a, i), t.__e = t.__ = null, a.__e != n && A(a);
+ var t = e.__v, n = t.__e, r = [], i = [], a = E({}, t);
+ a.__v = t.__v + 1, c.vnode && c.vnode(a), de(e.__P, a, t, e.__n, e.__P.namespaceURI, 32 & t.__u ? [n] : null, r, n ?? j(t), !!(32 & t.__u), i), a.__v = t.__v, a.__.__k[a.__i] = a, pe(r, a, i), t.__e = t.__ = null, a.__e != n && M(a);
}
}
-function A(e) {
+function M(e) {
if ((e = e.__) != null && e.__c != null) return e.__e = e.__c.base = null, e.__k.some(function(t) {
if (t != null && t.__e != null) return e.__e = e.__c.base = t.__e;
- }), A(e);
+ }), M(e);
}
-function j(e) {
- (!e.__d && (e.__d = !0) && l.push(e) && !M.__r++ || u != o.debounceRendering) && ((u = o.debounceRendering) || d)(M);
+function ne(e) {
+ (!e.__d && (e.__d = !0) && d.push(e) && !re.__r++ || f != c.debounceRendering) && ((f = c.debounceRendering) || p)(re);
}
-function M() {
+function re() {
try {
- for (var e, t = 1; l.length;) l.length > t && l.sort(f), e = l.shift(), t = l.length, te(e);
+ for (var e, t = 1; d.length;) d.length > t && d.sort(m), e = d.shift(), t = d.length, te(e);
} finally {
- l.length = M.__r = 0;
+ d.length = re.__r = 0;
}
}
-function ne(e, t, n, r, i, a, o, s, c, l, u) {
- var d, f, p, m, h, g, _ = r && r.__k || x, v = t.length;
- for (c = re(n, t, _, c, v), d = 0; d < v; d++) (p = n.__k[d]) != null && (f = p.__i != -1 && _[p.__i] || b, p.__i = d, g = le(e, p, f, i, a, o, s, c, l, u), m = p.__e, p.ref && f.ref != p.ref && (f.ref && me(f.ref, null, p), u.push(p.ref, p.__c || m, p)), h == null && m != null && (h = m), 4 & p.__u ? (c = ie(p, c, e), f.__e && (f.__e = null)) : typeof p.type == "function" && g !== void 0 ? c = g : m && (c = m.nextSibling), p.__u &= -7);
+function ie(e, t, n, r, i, a, o, s, c, l, u) {
+ var d, f, p, m, h, g, _ = r && r.__k || C, v = t.length;
+ for (c = ae(n, t, _, c, v), d = 0; d < v; d++) (p = n.__k[d]) != null && (f = p.__i != -1 && _[p.__i] || S, p.__i = d, g = de(e, p, f, i, a, o, s, c, l, u), m = p.__e, p.ref && f.ref != p.ref && (f.ref && ge(f.ref, null, p), u.push(p.ref, p.__c || m, p)), h == null && m != null && (h = m), 4 & p.__u ? (c = oe(p, c, e), f.__e && (f.__e = null)) : typeof p.type == "function" && g !== void 0 ? c = g : m && (c = m.nextSibling), p.__u &= -7);
return n.__e = h, c;
}
-function re(e, t, n, r, i) {
+function ae(e, t, n, r, i) {
var a, o, s, c, l, u = n.length, d = u, f = 0;
- for (e.__k = Array(i), a = 0; a < i; a++) (o = t[a]) != null && typeof o != "boolean" && typeof o != "function" ? (typeof o == "string" || typeof o == "number" || typeof o == "bigint" || o.constructor == String ? o = e.__k[a] = E(null, o, null, null, null) : C(o) ? o = e.__k[a] = E(D, { children: o }, null, null, null) : o.constructor === void 0 && o.__b > 0 ? o = e.__k[a] = E(o.type, o.props, o.key, o.ref ? o.ref : null, o.__v) : e.__k[a] = o, c = a + f, o.__ = e, o.__b = e.__b + 1, s = null, (l = o.__i = ae(o, n, c, d)) != -1 && (d--, (s = n[l]) && (s.__u |= 2)), s == null || s.__v == null ? (l == -1 && (i > u ? f-- : i < u && f++), typeof o.type != "function" && (o.__u |= 4)) : l != c && (l == c - 1 ? f-- : l == c + 1 ? f++ : (l > c ? f-- : f++, o.__u |= 4))) : e.__k[a] = null;
- if (d) for (a = 0; a < u; a++) (s = n[a]) != null && !(2 & s.__u) && (s.__e == r && (r = k(s)), he(s, s));
+ for (e.__k = Array(i), a = 0; a < i; a++) (o = t[a]) != null && typeof o != "boolean" && typeof o != "function" ? (typeof o == "string" || typeof o == "number" || typeof o == "bigint" || o.constructor == String ? o = e.__k[a] = O(null, o, null, null, null) : T(o) ? o = e.__k[a] = O(k, { children: o }, null, null, null) : o.constructor === void 0 && o.__b > 0 ? o = e.__k[a] = O(o.type, o.props, o.key, o.ref ? o.ref : null, o.__v) : e.__k[a] = o, c = a + f, o.__ = e, o.__b = e.__b + 1, s = null, (l = o.__i = se(o, n, c, d)) != -1 && (d--, (s = n[l]) && (s.__u |= 2)), s == null || s.__v == null ? (l == -1 && (i > u ? f-- : i < u && f++), typeof o.type != "function" && (o.__u |= 4)) : l != c && (l == c - 1 ? f-- : l == c + 1 ? f++ : (l > c ? f-- : f++, o.__u |= 4))) : e.__k[a] = null;
+ if (d) for (a = 0; a < u; a++) (s = n[a]) != null && !(2 & s.__u) && (s.__e == r && (r = j(s)), _e(s, s));
return r;
}
-function ie(e, t, n) {
+function oe(e, t, n) {
var r, i;
if (typeof e.type == "function") {
- for (r = e.__k, i = 0; r && i < r.length; i++) r[i] && (r[i].__ = e, t = ie(r[i], t, n));
+ for (r = e.__k, i = 0; r && i < r.length; i++) r[i] && (r[i].__ = e, t = oe(r[i], t, n));
return t;
}
- e.__e != t && (t && e.type && !t.parentNode && (t = k(e)), t = n.insertBefore(e.__e, t || null));
+ e.__e != t && (t && e.type && !t.parentNode && (t = j(e)), t = n.insertBefore(e.__e, t || null));
do
t &&= t.nextSibling;
while (t != null && t.nodeType == 8);
return t;
}
-function ae(e, t, n, r) {
+function se(e, t, n, r) {
var i, a, o, s = e.key, c = e.type, l = t[n], u = l != null && !(2 & l.__u);
if (l === null && s == null || u && s == l.key && c == l.type) return n;
if (r > +!!u) {
@@ -96,18 +96,18 @@ function ae(e, t, n, r) {
}
return -1;
}
-function oe(e, t, n) {
- t[0] == "-" ? e.setProperty(t, n ?? "") : e[t] = n == null ? "" : typeof n != "number" || S.test(t) ? n : n + "px";
+function ce(e, t, n) {
+ t[0] == "-" ? e.setProperty(t, n ?? "") : e[t] = n == null ? "" : typeof n != "number" || w.test(t) ? n : n + "px";
}
-function se(e, t, n, r, i) {
+function le(e, t, n, r, i) {
var a, o;
n: if (t == "style") {
if (typeof n == "string") e.style.cssText = n;
else {
- if (typeof r == "string" && (e.style.cssText = r = ""), r) for (t in r) n && t in n || oe(e.style, t, "");
- if (n) for (t in n) r && n[t] == r[t] || oe(e.style, t, n[t]);
+ if (typeof r == "string" && (e.style.cssText = r = ""), r) for (t in r) n && t in n || ce(e.style, t, "");
+ if (n) for (t in n) r && n[t] == r[t] || ce(e.style, t, n[t]);
}
- } else if (t[0] == "o" && t[1] == "n") a = t != (t = t.replace(g, "$1")), o = t.toLowerCase(), t = o in e || t == "onFocusOut" || t == "onFocusIn" ? o.slice(2) : t.slice(2), e.l ||= {}, e.l[t + a] = n, n ? r ? n[h] = r[h] : (n[h] = _, e.addEventListener(t, a ? y : v, a)) : e.removeEventListener(t, a ? y : v, a);
+ } else if (t[0] == "o" && t[1] == "n") a = t != (t = t.replace(v, "$1")), o = t.toLowerCase(), t = o in e || t == "onFocusOut" || t == "onFocusIn" ? o.slice(2) : t.slice(2), e.l ||= {}, e.l[t + a] = n, n ? r ? n[_] = r[_] : (n[_] = y, e.addEventListener(t, a ? x : b, a)) : e.removeEventListener(t, a ? x : b, a);
else {
if (i == "http://www.w3.org/2000/svg") t = t.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
else if (t != "width" && t != "height" && t != "href" && t != "list" && t != "form" && t != "tabIndex" && t != "download" && t != "rowSpan" && t != "colSpan" && t != "role" && t != "popover" && t in e) try {
@@ -117,148 +117,149 @@ function se(e, t, n, r, i) {
typeof n == "function" || (n == null || !1 === n && t[4] != "-" ? e.removeAttribute(t) : e.setAttribute(t, t == "popover" && n == 1 ? "" : n));
}
}
-function ce(e) {
+function ue(e) {
return function(t) {
if (this.l) {
var n = this.l[t.type + e];
- if (t[m] == null) t[m] = _++;
- else if (t[m] < n[h]) return;
- return n(o.event ? o.event(t) : t);
+ if (t[g] == null) t[g] = y++;
+ else if (t[g] < n[_]) return;
+ return n(c.event ? c.event(t) : t);
}
};
}
-function le(e, t, n, r, i, a, s, c, l, u) {
- var d, f, p, m, h, g, _, v, y, b, S, T, E, te, A, j, M = t.type;
+function de(e, t, n, r, i, a, o, s, l, u) {
+ var d, f, p, m, h, g, _, v, y, b, x, S, w, D, O, te, M = t.type;
if (t.constructor !== void 0) return null;
- 128 & n.__u && (l = !!(32 & n.__u), a = [c = t.__e = n.__e]), (d = o.__b) && d(t);
+ 128 & n.__u && (l = !!(32 & n.__u), a = [s = t.__e = n.__e]), (d = c.__b) && d(t);
n: if (typeof M == "function") {
- f = s.length;
+ f = o.length;
try {
- if (y = t.props, b = M.prototype && M.prototype.render, S = (d = M.contextType) && r[d.__c], T = d ? S ? S.props.value : d.__ : r, n.__c ? v = (p = t.__c = n.__c).__ = p.__E : (b ? t.__c = p = new M(y, T) : (t.__c = p = new O(y, T), p.constructor = M, p.render = ge), S && S.sub(p), p.state || (p.state = {}), p.__n = r, m = p.__d = !0, p.__h = [], p._sb = []), b && p.__s == null && (p.__s = p.state), b && M.getDerivedStateFromProps != null && (p.__s == p.state && (p.__s = w({}, p.__s)), w(p.__s, M.getDerivedStateFromProps(y, p.__s))), h = p.props, g = p.state, p.__v = t, m) b && M.getDerivedStateFromProps == null && p.componentWillMount != null && p.componentWillMount(), b && p.componentDidMount != null && p.__h.push(p.componentDidMount);
+ if (y = t.props, b = M.prototype && M.prototype.render, x = (d = M.contextType) && r[d.__c], S = d ? x ? x.props.value : d.__ : r, n.__c ? v = (p = t.__c = n.__c).__ = p.__E : (b ? t.__c = p = new M(y, S) : (t.__c = p = new A(y, S), p.constructor = M, p.render = ve), x && x.sub(p), p.state || (p.state = {}), p.__n = r, m = p.__d = !0, p.__h = [], p._sb = []), b && p.__s == null && (p.__s = p.state), b && M.getDerivedStateFromProps != null && (p.__s == p.state && (p.__s = E({}, p.__s)), E(p.__s, M.getDerivedStateFromProps(y, p.__s))), h = p.props, g = p.state, p.__v = t, m) b && M.getDerivedStateFromProps == null && p.componentWillMount != null && p.componentWillMount(), b && p.componentDidMount != null && p.__h.push(p.componentDidMount);
else {
- if (b && M.getDerivedStateFromProps == null && y !== h && p.componentWillReceiveProps != null && p.componentWillReceiveProps(y, T), t.__v == n.__v || !p.__e && p.shouldComponentUpdate != null && !1 === p.shouldComponentUpdate(y, p.__s, T)) {
+ if (b && M.getDerivedStateFromProps == null && y !== h && p.componentWillReceiveProps != null && p.componentWillReceiveProps(y, S), t.__v == n.__v || !p.__e && p.shouldComponentUpdate != null && !1 === p.shouldComponentUpdate(y, p.__s, S)) {
t.__v != n.__v && (p.props = y, p.state = p.__s, p.__d = !1), t.__e = n.__e, t.__k = n.__k, t.__k.some(function(e) {
e && (e.__ = t);
- }), x.push.apply(p.__h, p._sb), p._sb = [], p.__h.length && s.push(p), c = k(n);
+ }), C.push.apply(p.__h, p._sb), p._sb = [], p.__h.length && o.push(p), s = j(n);
break n;
}
- p.componentWillUpdate != null && p.componentWillUpdate(y, p.__s, T), b && p.componentDidUpdate != null && p.__h.push(function() {
+ p.componentWillUpdate != null && p.componentWillUpdate(y, p.__s, S), b && p.componentDidUpdate != null && p.__h.push(function() {
p.componentDidUpdate(h, g, _);
});
}
- if (p.context = T, p.props = y, p.__P = e, p.__e = !1, E = o.__r, te = 0, b) p.state = p.__s, p.__d = !1, E && E(t), d = p.render(p.props, p.state, p.context), x.push.apply(p.__h, p._sb), p._sb = [];
+ if (p.context = S, p.props = y, p.__P = e, p.__e = !1, w = c.__r, D = 0, b) p.state = p.__s, p.__d = !1, w && w(t), d = p.render(p.props, p.state, p.context), C.push.apply(p.__h, p._sb), p._sb = [];
else do
- p.__d = !1, E && E(t), d = p.render(p.props, p.state, p.context), p.state = p.__s;
- while (p.__d && ++te < 25);
- p.state = p.__s, p.getChildContext != null && (r = w(w({}, r), p.getChildContext())), b && !m && p.getSnapshotBeforeUpdate != null && (_ = p.getSnapshotBeforeUpdate(h, g)), A = d != null && d.type === D && d.key == null ? fe(d.props.children) : d, c = ne(e, C(A) ? A : [A], t, n, r, i, a, s, c, l, u), p.base = t.__e, t.__u &= -161, p.__h.length && s.push(p), v && (p.__E = p.__ = null);
+ p.__d = !1, w && w(t), d = p.render(p.props, p.state, p.context), p.state = p.__s;
+ while (p.__d && ++D < 25);
+ p.state = p.__s, p.getChildContext != null && (r = E(E({}, r), p.getChildContext())), b && !m && p.getSnapshotBeforeUpdate != null && (_ = p.getSnapshotBeforeUpdate(h, g)), O = d != null && d.type === k && d.key == null ? me(d.props.children) : d, s = ie(e, T(O) ? O : [O], t, n, r, i, a, o, s, l, u), p.base = t.__e, t.__u &= -161, p.__h.length && o.push(p), v && (p.__E = p.__ = null);
} catch (e) {
- if (s.length = f, t.__v = null, l || a != null) {
+ if (o.length = f, t.__v = null, l || a != null) {
if (e.then) {
- for (t.__u |= l ? 160 : 128; c && c.nodeType == 8 && c.nextSibling;) c = c.nextSibling;
- a != null && (a[a.indexOf(c)] = null), t.__e = c;
- } else if (a != null) for (j = a.length; j--;) ee(a[j]);
+ for (t.__u |= l ? 160 : 128; s && s.nodeType == 8 && s.nextSibling;) s = s.nextSibling;
+ a != null && (a[a.indexOf(s)] = null), t.__e = s;
+ } else if (a != null) for (te = a.length; te--;) ee(a[te]);
} else t.__e = n.__e;
- t.__k ??= n.__k || [], e.then || ue(t), o.__e(e, t, n);
+ t.__k ??= n.__k || [], e.then || fe(t), c.__e(e, t, n);
}
- } else a == null && t.__v == n.__v ? (t.__k = n.__k, t.__e = n.__e) : c = t.__e = pe(n.__e, t, n, r, i, a, s, l, u);
- return (d = o.diffed) && d(t), 128 & t.__u ? void 0 : c;
+ } else a == null && t.__v == n.__v ? (t.__k = n.__k, t.__e = n.__e) : s = t.__e = he(n.__e, t, n, r, i, a, o, l, u);
+ return (d = c.diffed) && d(t), 128 & t.__u ? void 0 : s;
}
-function ue(e) {
- e && (e.__c && (e.__c.__e = !0), e.__k && e.__k.some(ue));
+function fe(e) {
+ e && (e.__c && (e.__c.__e = !0), e.__k && e.__k.some(fe));
}
-function de(e, t, n) {
- for (var r = 0; r < n.length; r++) me(n[r], n[++r], n[++r]);
- o.__c && o.__c(t, e), e.some(function(t) {
+function pe(e, t, n) {
+ for (var r = 0; r < n.length; r++) ge(n[r], n[++r], n[++r]);
+ c.__c && c.__c(t, e), e.some(function(t) {
try {
e = t.__h, t.__h = [], e.some(function(e) {
e.call(t);
});
} catch (e) {
- o.__e(e, t.__v);
+ c.__e(e, t.__v);
}
});
}
-function fe(e) {
- return typeof e != "object" || !e || e.__b > 0 ? e : C(e) ? e.map(fe) : e.constructor === void 0 ? w({}, e) : null;
+function me(e) {
+ return typeof e != "object" || !e || e.__b > 0 ? e : T(e) ? e.map(me) : e.constructor === void 0 ? E({}, e) : null;
}
-function pe(e, t, n, r, i, s, c, l, u) {
- var d, f, p, m, h, g, _, v = n.props || b, y = t.props, x = t.type;
- if (x == "svg" ? i = "http://www.w3.org/2000/svg" : x == "math" ? i = "http://www.w3.org/1998/Math/MathML" : i ||= "http://www.w3.org/1999/xhtml", s != null) {
- for (d = 0; d < s.length; d++) if ((h = s[d]) && "setAttribute" in h == !!x && (x ? h.localName == x : h.nodeType == 3)) {
- e = h, s[d] = null;
+function he(e, t, n, r, i, a, o, l, u) {
+ var d, f, p, m, h, g, _, v = n.props || S, y = t.props, b = t.type;
+ if (b == "svg" ? i = "http://www.w3.org/2000/svg" : b == "math" ? i = "http://www.w3.org/1998/Math/MathML" : i ||= "http://www.w3.org/1999/xhtml", a != null) {
+ for (d = 0; d < a.length; d++) if ((h = a[d]) && "setAttribute" in h == !!b && (b ? h.localName == b : h.nodeType == 3)) {
+ e = h, a[d] = null;
break;
}
}
if (e == null) {
- if (x == null) return document.createTextNode(y);
- e = document.createElementNS(i, x, y.is && y), l &&= (o.__m && o.__m(t, s), !1), s = null;
+ if (b == null) return document.createTextNode(y);
+ e = document.createElementNS(i, b, y.is && y), l &&= (c.__m && c.__m(t, a), !1), a = null;
}
- if (x == null) v === y || l && e.data == y || (e.data = y);
+ if (b == null) v === y || l && e.data == y || (e.data = y);
else {
- if (s = x == "textarea" && y.defaultValue != null ? null : s && a.call(e.childNodes), !l && s != null) for (v = {}, d = 0; d < e.attributes.length; d++) v[(h = e.attributes[d]).name] = h.value;
- for (d in v) h = v[d], d == "dangerouslySetInnerHTML" ? p = h : d == "children" || d in y || d == "value" && "defaultValue" in y || d == "checked" && "defaultChecked" in y || se(e, d, null, h, i);
- for (d in y) h = y[d], d == "children" ? m = h : d == "dangerouslySetInnerHTML" ? f = h : d == "value" ? g = h : d == "checked" ? _ = h : l && typeof h != "function" || v[d] === h || se(e, d, h, v[d], i);
+ if (a = b == "textarea" && y.defaultValue != null ? null : a && s.call(e.childNodes), !l && a != null) for (v = {}, d = 0; d < e.attributes.length; d++) v[(h = e.attributes[d]).name] = h.value;
+ for (d in v) h = v[d], d == "dangerouslySetInnerHTML" ? p = h : d == "children" || d in y || d == "value" && "defaultValue" in y || d == "checked" && "defaultChecked" in y || le(e, d, null, h, i);
+ for (d in y) h = y[d], d == "children" ? m = h : d == "dangerouslySetInnerHTML" ? f = h : d == "value" ? g = h : d == "checked" ? _ = h : l && typeof h != "function" || v[d] === h || le(e, d, h, v[d], i);
if (f) l || p && (f.__html == p.__html || f.__html == e.innerHTML) || (e.innerHTML = f.__html), t.__k = [];
- else if (p && (e.innerHTML = ""), ne(t.type == "template" ? e.content : e, C(m) ? m : [m], t, n, r, x == "foreignObject" ? "http://www.w3.org/1999/xhtml" : i, s, c, s ? s[0] : n.__k && k(n, 0), l, u), s != null) for (d = s.length; d--;) ee(s[d]);
- l && x != "textarea" || (d = "value", x == "progress" && g == null ? e.removeAttribute("value") : g != null && (g !== e[d] || x == "progress" && !g || x == "option" && g != v[d]) && se(e, d, g, v[d], i), d = "checked", _ != null && _ != e[d] && se(e, d, _, v[d], i));
+ else if (p && (e.innerHTML = ""), ie(t.type == "template" ? e.content : e, T(m) ? m : [m], t, n, r, b == "foreignObject" ? "http://www.w3.org/1999/xhtml" : i, a, o, a ? a[0] : n.__k && j(n, 0), l, u), a != null) for (d = a.length; d--;) ee(a[d]);
+ l && b != "textarea" || (d = "value", b == "progress" && g == null ? e.removeAttribute("value") : g != null && (g !== e[d] || b == "progress" && !g || b == "option" && g != v[d]) && le(e, d, g, v[d], i), d = "checked", _ != null && _ != e[d] && le(e, d, _, v[d], i));
}
return e;
}
-function me(e, t, n) {
+function ge(e, t, n) {
try {
if (typeof e == "function") {
var r = typeof e.__u == "function";
r && e.__u(), r && t == null || (e.__u = e(t));
} else e.current = t;
} catch (e) {
- o.__e(e, n);
+ c.__e(e, n);
}
}
-function he(e, t, n) {
+function _e(e, t, n) {
var r, i;
- if (o.unmount && o.unmount(e), (r = e.ref) && (r.current && r.current != e.__e || me(r, null, t)), (r = e.__c) != null) {
+ if (c.unmount && c.unmount(e), (r = e.ref) && (r.current && r.current != e.__e || ge(r, null, t)), (r = e.__c) != null) {
if (r.componentWillUnmount) try {
r.componentWillUnmount();
} catch (e) {
- o.__e(e, t);
+ c.__e(e, t);
}
r.base = r.__P = r.__n = null;
}
- if (r = e.__k) for (i = 0; i < r.length; i++) r[i] && he(r[i], t, n || typeof e.type != "function");
+ if (r = e.__k) for (i = 0; i < r.length; i++) r[i] && _e(r[i], t, n || typeof e.type != "function");
n || ee(e.__e), e.__c = e.__ = e.__e = void 0;
}
-function ge(e, t, n) {
+function ve(e, t, n) {
return this.constructor(e, n);
}
-function _e(e, t, n) {
- var r, i, s, c;
- t == document && (t = document.documentElement), o.__ && o.__(e, t), i = (r = typeof n == "function") ? null : n && n.__k || t.__k, s = [], c = [], le(t, e = (!r && n || t).__k = T(D, null, [e]), i || b, b, t.namespaceURI, !r && n ? [n] : i ? null : t.firstChild ? a.call(t.childNodes) : null, s, !r && n ? n : i ? i.__e : t.firstChild, r, c), de(s, e, c), e.props.children = null;
+function ye(e, t, n) {
+ var r, i, a, o;
+ t == document && (t = document.documentElement), c.__ && c.__(e, t), i = (r = typeof n == "function") ? null : n && n.__k || t.__k, a = [], o = [], de(t, e = (!r && n || t).__k = D(k, null, [e]), i || S, S, t.namespaceURI, !r && n ? [n] : i ? null : t.firstChild ? s.call(t.childNodes) : null, a, !r && n ? n : i ? i.__e : t.firstChild, r, o), pe(a, e, o), e.props.children = null;
}
-a = x.slice, o = { __e: function(e, t, n, r) {
+s = C.slice, c = { __e: function(e, t, n, r) {
for (var i, a, o; t = t.__;) if ((i = t.__c) && !i.__) try {
if ((a = i.constructor) && a.getDerivedStateFromError != null && (i.setState(a.getDerivedStateFromError(e)), o = i.__d), i.componentDidCatch != null && (i.componentDidCatch(e, r || {}), o = i.__d), o) return i.__E = i;
} catch (t) {
e = t;
}
throw e;
-} }, s = 0, c = function(e) {
+} }, l = 0, u = function(e) {
return e != null && e.constructor === void 0;
-}, O.prototype.setState = function(e, t) {
- var n = this.__s != null && this.__s != this.state ? this.__s : this.__s = w({}, this.state);
- typeof e == "function" && (e = e(w({}, n), this.props)), e && w(n, e), e != null && this.__v && (t && this._sb.push(t), j(this));
-}, O.prototype.forceUpdate = function(e) {
- this.__v && (this.__e = !0, e && this.__h.push(e), j(this));
-}, O.prototype.render = D, l = [], d = typeof Promise == "function" ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f = function(e, t) {
+}, A.prototype.setState = function(e, t) {
+ var n = this.__s != null && this.__s != this.state ? this.__s : this.__s = E({}, this.state);
+ typeof e == "function" && (e = e(E({}, n), this.props)), e && E(n, e), e != null && this.__v && (t && this._sb.push(t), ne(this));
+}, A.prototype.forceUpdate = function(e) {
+ this.__v && (this.__e = !0, e && this.__h.push(e), ne(this));
+}, A.prototype.render = k, d = [], p = typeof Promise == "function" ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, m = function(e, t) {
return e.__v.__b - t.__v.__b;
-}, M.__r = 0, p = Math.random().toString(8), m = "__d" + p, h = "__a" + p, g = /(PointerCapture)$|Capture$/i, _ = 0, v = ce(!1), y = ce(!0);
+}, re.__r = 0, h = Math.random().toString(8), g = "__d" + h, _ = "__a" + h, v = /(PointerCapture)$|Capture$/i, y = 0, b = ue(!1), x = ue(!0);
//#endregion
//#region src/api.ts
-var ve = class extends Error {
+var be = class extends Error {
status;
- constructor(e, t) {
- super(e), this.name = "ApiError", this.status = t;
+ body;
+ constructor(e, t, n = null) {
+ super(e), this.name = "ApiError", this.status = t, this.body = n;
}
-}, ye = (e) => {
+}, xe = (e) => {
if (!e || typeof e != "object") return "";
let t = e;
for (let e of [
@@ -270,8 +271,8 @@ var ve = class extends Error {
if (typeof n == "string" && n) return n;
}
return "";
-}, be = (e) => e instanceof Error ? e.message : String(e);
-async function xe(e, t) {
+}, N = (e) => e instanceof Error ? e.message : String(e);
+async function Se(e, t) {
let n = await fetch(e, {
headers: { Accept: "application/json" },
credentials: "same-origin",
@@ -280,112 +281,454 @@ async function xe(e, t) {
try {
r = await n.json();
} catch {}
- if (!n.ok) throw new ve(ye(r) || `请求失败(${n.status})`, n.status);
+ if (!n.ok) throw new be(xe(r) || `请求失败(${n.status})`, n.status);
return r;
}
+async function Ce(e, t, n = "POST") {
+ let r = await fetch(e, {
+ method: n,
+ headers: {
+ Accept: "application/json",
+ "Content-Type": "application/json"
+ },
+ credentials: "same-origin",
+ body: JSON.stringify(t)
+ }), i = null;
+ try {
+ i = await r.json();
+ } catch {}
+ if (!r.ok) throw new be(xe(i) || `请求失败(${r.status})`, r.status, i);
+ return i;
+}
//#endregion
//#region node_modules/preact/hooks/dist/hooks.module.js
-var Se, N, Ce, we, Te = 0, Ee = [], P = o, De = P.__b, Oe = P.__r, ke = P.diffed, Ae = P.__c, je = P.unmount, Me = P.__;
-function Ne(e, t) {
- P.__h && P.__h(N, e, Te || t), Te = 0;
- var n = N.__H || (N.__H = {
+var P, F, we, Te, Ee = 0, De = [], I = c, Oe = I.__b, ke = I.__r, Ae = I.diffed, je = I.__c, Me = I.unmount, Ne = I.__;
+function Pe(e, t) {
+ I.__h && I.__h(F, e, Ee || t), Ee = 0;
+ var n = F.__H || (F.__H = {
__: [],
__h: []
});
return e >= n.__.length && n.__.push({}), n.__[e];
}
-function Pe(e, t) {
- var n = Ne(Se++, 7);
- return Be(n.__H, t) && (n.__ = e(), n.__H = t, n.__h = e), n.__;
+function L(e) {
+ return Ee = 1, Fe(Ke, e);
+}
+function Fe(e, t, n) {
+ var r = Pe(P++, 2);
+ if (r.t = e, !r.__c && (r.__ = [n ? n(t) : Ke(void 0, t), function(e) {
+ var t = r.__N ? r.__N[0] : r.__[0], n = r.t(t, e);
+ t !== n && (r.__N = [n, r.__[1]], r.__c.setState({}));
+ }], r.__c = F, !F.__f)) {
+ var i = function(e, t, n) {
+ if (!r.__c.__H) return !0;
+ var i = !1, o = r.__c.props !== e;
+ if (r.__c.__H.__.some(function(e) {
+ if (e.__N) {
+ i = !0;
+ var t = e.__[0];
+ e.__ = e.__N, e.__N = void 0, t !== e.__[0] && (o = !0);
+ }
+ }), a) {
+ var s = a.call(this, e, t, n);
+ return i ? s || o : s;
+ }
+ return !i || o;
+ };
+ F.__f = !0;
+ var a = F.shouldComponentUpdate, o = F.componentWillUpdate;
+ F.componentWillUpdate = function(e, t, n) {
+ if (this.__e) {
+ var r = a;
+ a = void 0, i(e, t, n), a = r;
+ }
+ o && o.call(this, e, t, n);
+ }, F.shouldComponentUpdate = i;
+ }
+ return r.__N || r.__;
+}
+function Ie(e, t) {
+ var n = Pe(P++, 3);
+ !I.__s && Ge(n.__H, t) && (n.__ = e, n.u = t, F.__H.__h.push(n));
}
-function Fe() {
- for (var e; e = Ee.shift();) {
+function Le(e, t) {
+ var n = Pe(P++, 4);
+ !I.__s && Ge(n.__H, t) && (n.__ = e, n.u = t, F.__h.push(n));
+}
+function Re(e) {
+ return Ee = 5, ze(function() {
+ return { current: e };
+ }, []);
+}
+function ze(e, t) {
+ var n = Pe(P++, 7);
+ return Ge(n.__H, t) && (n.__ = e(), n.__H = t, n.__h = e), n.__;
+}
+function Be() {
+ for (var e; e = De.shift();) {
var t = e.__H;
if (e.__P && t) try {
- t.__h.some(Re), t.__h.some(ze), t.__h = [];
+ t.__h.some(Ue), t.__h.some(We), t.__h = [];
} catch (n) {
- t.__h = [], P.__e(n, e.__v);
+ t.__h = [], I.__e(n, e.__v);
}
}
}
-P.__b = function(e) {
- N = null, De && De(e);
-}, P.__ = function(e, t) {
- e && t.__k && t.__k.__m && (e.__m = t.__k.__m), Me && Me(e, t);
-}, P.__r = function(e) {
- Oe && Oe(e), Se = 0;
- var t = (N = e.__c).__H;
- t && (Ce === N ? (t.__h = [], N.__h = [], t.__.some(function(e) {
+I.__b = function(e) {
+ F = null, Oe && Oe(e);
+}, I.__ = function(e, t) {
+ e && t.__k && t.__k.__m && (e.__m = t.__k.__m), Ne && Ne(e, t);
+}, I.__r = function(e) {
+ ke && ke(e), P = 0;
+ var t = (F = e.__c).__H;
+ t && (we === F ? (t.__h = [], F.__h = [], t.__.some(function(e) {
e.__N && (e.__ = e.__N), e.u = e.__N = void 0;
- })) : (t.__h.some(Re), t.__h.some(ze), t.__h = [], Se = 0)), Ce = N;
-}, P.diffed = function(e) {
- ke && ke(e);
+ })) : (t.__h.some(Ue), t.__h.some(We), t.__h = [], P = 0)), we = F;
+}, I.diffed = function(e) {
+ Ae && Ae(e);
var t = e.__c;
- t && t.__H && (t.__H.__h.length && (Ee.push(t) !== 1 && we === P.requestAnimationFrame || ((we = P.requestAnimationFrame) || Le)(Fe)), t.__H.__.some(function(e) {
+ t && t.__H && (t.__H.__h.length && (De.push(t) !== 1 && Te === I.requestAnimationFrame || ((Te = I.requestAnimationFrame) || He)(Be)), t.__H.__.some(function(e) {
e.u &&= (e.__H = e.u, void 0);
- })), Ce = N = null;
-}, P.__c = function(e, t) {
+ })), we = F = null;
+}, I.__c = function(e, t) {
t.some(function(e) {
try {
- e.__h.some(Re), e.__h = e.__h.filter(function(e) {
- return !e.__ || ze(e);
+ e.__h.some(Ue), e.__h = e.__h.filter(function(e) {
+ return !e.__ || We(e);
});
} catch (n) {
t.some(function(e) {
e.__h &&= [];
- }), t = [], P.__e(n, e.__v);
+ }), t = [], I.__e(n, e.__v);
}
- }), Ae && Ae(e, t);
-}, P.unmount = function(e) {
- je && je(e);
+ }), je && je(e, t);
+}, I.unmount = function(e) {
+ Me && Me(e);
var t, n = e.__c;
n && n.__H && (n.__H.__.some(function(e) {
try {
- Re(e);
+ Ue(e);
} catch (e) {
t = e;
}
- }), n.__H = void 0, t && P.__e(t, n.__v));
+ }), n.__H = void 0, t && I.__e(t, n.__v));
};
-var Ie = typeof requestAnimationFrame == "function";
-function Le(e) {
+var Ve = typeof requestAnimationFrame == "function";
+function He(e) {
var t, n = function() {
- clearTimeout(r), Ie && cancelAnimationFrame(t), setTimeout(e);
+ clearTimeout(r), Ve && cancelAnimationFrame(t), setTimeout(e);
}, r = setTimeout(n, 35);
- Ie && (t = requestAnimationFrame(n));
+ Ve && (t = requestAnimationFrame(n));
}
-function Re(e) {
- var t = N, n = e.__c;
- typeof n == "function" && (e.__c = void 0, n()), N = t;
+function Ue(e) {
+ var t = F, n = e.__c;
+ typeof n == "function" && (e.__c = void 0, n()), F = t;
}
-function ze(e) {
- var t = N;
- e.__c = e.__(), N = t;
+function We(e) {
+ var t = F;
+ e.__c = e.__(), F = t;
}
-function Be(e, t) {
+function Ge(e, t) {
return !e || e.length !== t.length || t.some(function(t, n) {
return t !== e[n];
});
}
+function Ke(e, t) {
+ return typeof t == "function" ? t(e) : t;
+}
+//#endregion
+//#region node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js
+var qe = 0;
+Array.isArray;
+function R(e, t, n, r, i, a) {
+ t ||= {};
+ var o, s, l = t;
+ if ("ref" in l) for (s in l = {}, t) s == "ref" ? o = t[s] : l[s] = t[s];
+ var u = {
+ type: e,
+ props: l,
+ key: n,
+ ref: o,
+ __k: null,
+ __: null,
+ __b: 0,
+ __e: null,
+ __c: null,
+ constructor: void 0,
+ __v: --qe,
+ __i: -1,
+ __u: 0,
+ __source: i,
+ __self: a
+ };
+ if (typeof e == "function" && (o = e.defaultProps)) for (s in o) l[s] === void 0 && (l[s] = o[s]);
+ return c.vnode && c.vnode(u), u;
+}
+//#endregion
+//#region src/islands/configuration.tsx
+var Je = "/api/configuration", Ye = "/api/pick-folder", Xe = 8e3, Ze = (e, t) => Se(Je, t), z = ({ html: e, class: t }) => /* @__PURE__ */ R("div", {
+ class: t,
+ dangerouslySetInnerHTML: { __html: e }
+}), Qe = (e) => !(e instanceof be) || e.status !== 400 ? null : e.body?.errors ?? null;
+function $e({ facts: e }) {
+ return /* @__PURE__ */ R("section", {
+ class: "configfieldset",
+ "data-geist-fieldset": !0,
+ "aria-labelledby": "configFactsTitle",
+ children: /* @__PURE__ */ R("div", {
+ class: "geist-fieldset-content",
+ children: [/* @__PURE__ */ R(z, { html: t("configFactsTitle", "运行信息") }), /* @__PURE__ */ R("dl", {
+ class: "configfacts",
+ children: e.map((e) => /* @__PURE__ */ R(k, { children: [/* @__PURE__ */ R("dt", { children: e.term }), /* @__PURE__ */ R("dd", { children: e.value })] }))
+ })]
+ })
+ });
+}
+function et({ data: e, receipt: i }) {
+ let [a, o] = L(e.media_dirs.length ? e.media_dirs : [""]), [s, c] = L(String(e.port)), [l, u] = L(!1), [d, f] = L([]), [p, m] = L(""), [h, g] = L(""), [_, v] = L(null), [y, b] = L(null), x = Re(!1), S = Re(e.revision), C = Re([]), w = Re(null);
+ Le(() => {
+ y !== null && (C.current[y]?.focus(), b(null));
+ }, [y]), Ie(() => {
+ if (!_) return;
+ let e = setTimeout(() => location.assign(_.url), Xe);
+ return () => clearTimeout(e);
+ }, [_]);
+ let T = (e, t) => {
+ o((n) => n.map((n, r) => r === e ? t : n));
+ }, E = () => {
+ b(a.length), o((e) => [...e, ""]);
+ }, ee = (e) => {
+ o((t) => t.filter((t, n) => n !== e)), f((t) => t.filter((t, n) => n !== e));
+ }, D = (e, t) => {
+ f((n) => {
+ let r = [...n];
+ for (; r.length <= e;) r.push("");
+ return r[e] = t, r;
+ });
+ }, O = async (e, t) => {
+ if (t.getAttribute("aria-busy") !== "true") {
+ r(t, !0);
+ try {
+ let { path: t } = await Ce(Ye, { initial: a[e] ?? "" });
+ t && (T(e, t), D(e, ""));
+ } catch (t) {
+ D(e, N(t));
+ } finally {
+ r(t, !1);
+ }
+ }
+ };
+ return _ ? /* @__PURE__ */ R("div", {
+ class: "configsaved",
+ role: "status",
+ children: [/* @__PURE__ */ R(z, { html: n("配置已保存,Peach 正在重新启动。", {
+ variant: "success",
+ label: "已保存"
+ }) }), /* @__PURE__ */ R("p", {
+ class: "confighelp",
+ children: [
+ "几秒后自动打开新地址;没跳转就点 ",
+ /* @__PURE__ */ R("a", {
+ href: _.url,
+ children: "进入馆藏"
+ }),
+ "。"
+ ]
+ })]
+ }) : /* @__PURE__ */ R("form", {
+ class: "configfieldset",
+ "data-geist-fieldset": !0,
+ "aria-labelledby": "configTitle",
+ onSubmit: async (e) => {
+ if (e.preventDefault(), !x.current) {
+ x.current = !0, r(w.current, !0), g("");
+ try {
+ let e = await Ce(Je, {
+ revision: S.current,
+ media_dirs: a,
+ port: s,
+ scan_now: l
+ });
+ S.current = e.revision, f([]), m(""), i("已保存配置"), v(e);
+ } catch (e) {
+ let t = Qe(e);
+ t ? (f(t.media_dirs ?? []), m(t.port ?? "")) : (f([]), m(""), g(N(e)));
+ } finally {
+ x.current = !1, r(w.current, !1);
+ }
+ }
+ },
+ noValidate: !0,
+ children: [/* @__PURE__ */ R("div", {
+ class: "geist-fieldset-content",
+ children: [
+ /* @__PURE__ */ R(z, { html: t("configTitle", "这台电脑") }),
+ /* @__PURE__ */ R("div", {
+ class: "configfield",
+ children: [
+ /* @__PURE__ */ R("span", {
+ class: "configlabel",
+ id: "configDirsLabel",
+ children: "媒体文件夹"
+ }),
+ /* @__PURE__ */ R("div", {
+ class: "configdirs",
+ role: "group",
+ "aria-labelledby": "configDirsLabel",
+ children: a.map((e, t) => /* @__PURE__ */ R("div", {
+ class: "configdir",
+ children: [
+ /* @__PURE__ */ R("input", {
+ class: "geist-input",
+ type: "text",
+ value: e,
+ "aria-label": `媒体文件夹 ${t + 1}`,
+ "aria-invalid": d[t] ? "true" : void 0,
+ onInput: (e) => T(t, e.currentTarget.value),
+ ref: (e) => {
+ C.current[t] = e;
+ }
+ }),
+ /* @__PURE__ */ R("button", {
+ type: "button",
+ class: "geist-button configpick",
+ "aria-label": "选择文件夹",
+ onClick: (e) => O(t, e.currentTarget),
+ children: /* @__PURE__ */ R("svg", {
+ viewBox: "0 0 24 24",
+ "aria-hidden": "true",
+ children: /* @__PURE__ */ R("use", { href: "#i-folder-search" })
+ })
+ }),
+ a.length > 1 ? /* @__PURE__ */ R("button", {
+ type: "button",
+ class: "geist-button configrm",
+ "aria-label": "移除这个文件夹",
+ onClick: () => ee(t),
+ children: /* @__PURE__ */ R("svg", {
+ viewBox: "0 0 24 24",
+ "aria-hidden": "true",
+ children: /* @__PURE__ */ R("use", { href: "#i-x" })
+ })
+ }) : null,
+ d[t] ? /* @__PURE__ */ R("p", {
+ class: "configbad",
+ role: "alert",
+ children: d[t]
+ }) : null
+ ]
+ }, t))
+ }),
+ /* @__PURE__ */ R("button", {
+ type: "button",
+ class: "geist-button configadd",
+ onClick: E,
+ children: "添加文件夹"
+ }),
+ /* @__PURE__ */ R("p", {
+ class: "confighelp",
+ children: "Peach 从这些文件夹读取视频和图片。可以是外置硬盘上的文件夹,但必须已经存在。"
+ })
+ ]
+ }),
+ /* @__PURE__ */ R("div", {
+ class: "configfield",
+ children: [
+ /* @__PURE__ */ R("label", {
+ for: "configPort",
+ children: "本机访问端口"
+ }),
+ /* @__PURE__ */ R("input", {
+ id: "configPort",
+ class: "geist-input",
+ type: "text",
+ inputMode: "numeric",
+ value: s,
+ "aria-invalid": p ? "true" : void 0,
+ onInput: (e) => c(e.currentTarget.value)
+ }),
+ p ? /* @__PURE__ */ R("p", {
+ class: "configbad",
+ role: "alert",
+ children: p
+ }) : null,
+ /* @__PURE__ */ R("p", {
+ class: "confighelp",
+ children: "浏览器地址里冒号后面的数字,一般不用改。"
+ })
+ ]
+ }),
+ /* @__PURE__ */ R("label", {
+ class: "configcheck",
+ children: [/* @__PURE__ */ R("span", {
+ class: "pcheck",
+ children: [/* @__PURE__ */ R("input", {
+ type: "checkbox",
+ checked: l,
+ onChange: (e) => u(e.currentTarget.checked)
+ }), /* @__PURE__ */ R("span", {
+ "aria-hidden": "true",
+ children: /* @__PURE__ */ R("svg", {
+ viewBox: "0 0 24 24",
+ children: /* @__PURE__ */ R("use", { href: "#i-check" })
+ })
+ })]
+ }), /* @__PURE__ */ R("span", { children: "保存后扫描媒体文件夹" })]
+ }),
+ h ? /* @__PURE__ */ R(z, { html: n(h, {
+ variant: "error",
+ label: "没有保存"
+ }) }) : null
+ ]
+ }), /* @__PURE__ */ R("div", {
+ class: "geist-fieldset-footer",
+ "data-geist-fieldset-footer": !0,
+ children: [/* @__PURE__ */ R("p", { children: "保存后 Peach 会重新启动,端口改了就用新地址打开。" }), /* @__PURE__ */ R("button", {
+ type: "submit",
+ class: "geist-button primary",
+ ref: w,
+ children: "保存配置"
+ })]
+ })]
+ });
+}
+function tt({ receipt: e, data: t, error: r }) {
+ return r || !t ? /* @__PURE__ */ R(z, {
+ class: "configpage",
+ html: n(r || "没有读到配置", {
+ variant: "error",
+ label: "打不开配置"
+ })
+ }) : /* @__PURE__ */ R("div", {
+ class: "configpage",
+ children: [t.editable ? /* @__PURE__ */ R(et, {
+ data: t,
+ receipt: e
+ }) : /* @__PURE__ */ R(z, { html: n(t.notice, {
+ variant: "secondary",
+ label: "只读"
+ }) }), /* @__PURE__ */ R($e, { facts: t.facts })]
+ });
+}
//#endregion
//#region node_modules/@preact/signals-core/dist/signals-core.module.js
-var Ve = Symbol.for("preact-signals");
-function F() {
- if (z > 1) z--;
+var nt = Symbol.for("preact-signals");
+function B() {
+ if (G > 1) G--;
else {
var e, t = !1;
for ((function() {
- var e = V;
- for (V = void 0; e !== void 0;) {
+ var e = st;
+ for (st = void 0; e !== void 0;) {
var t = e.S;
if (t.v === e.v) for (var n = t.t; n !== void 0; n = n.x) n.i === e.i && (n.i = t.i);
e = e.o;
}
- })(); R !== void 0;) {
- var n = R;
- for (R = void 0, B++; n !== void 0;) {
+ })(); W !== void 0;) {
+ var n = W;
+ for (W = void 0, it++; n !== void 0;) {
var r = n.u;
- if (n.u = void 0, n.f &= -3, !(8 & n.f) && Je(n)) try {
+ if (n.u = void 0, n.f &= -3, !(8 & n.f) && dt(n)) try {
n.c();
} catch (n) {
t ||= (e = n, !0);
@@ -393,116 +736,116 @@ function F() {
n = r;
}
}
- if (B = 0, z--, t) throw e;
+ if (it = 0, G--, t) throw e;
}
}
-function He(e) {
- if (z > 0) return e();
- Ge = ++We, z++;
+function rt(e) {
+ if (G > 0) return e();
+ ot = ++at, G++;
try {
return e();
} finally {
- F();
+ B();
}
}
-var I, L = void 0;
-function Ue(e) {
- var t = L, n = I;
- L = void 0, I = void 0;
+var V, H = void 0;
+function U(e) {
+ var t = H, n = V;
+ H = void 0, V = void 0;
try {
return e();
} finally {
- L = t, I = n;
+ H = t, V = n;
}
}
-var R = void 0, z = 0, B = 0, We = 0, Ge = 0, V = void 0, H = 0;
-function Ke(e) {
- if (L !== void 0) {
+var W = void 0, G = 0, it = 0, at = 0, ot = 0, st = void 0, ct = 0;
+function lt(e) {
+ if (H !== void 0) {
var t = e.n;
- if (t === void 0 || t.t !== L) return t = {
+ if (t === void 0 || t.t !== H) return t = {
i: 0,
S: e,
- p: L.s,
+ p: H.s,
n: void 0,
- t: L,
+ t: H,
e: void 0,
x: void 0,
r: t
- }, L.s !== void 0 && (L.s.n = t), L.s = t, e.n = t, 32 & L.f && e.S(t), t;
- if (t.i === -1) return t.i = 0, t.n !== void 0 && (t.n.p = t.p, t.p !== void 0 && (t.p.n = t.n), t.p = L.s, t.n = void 0, L.s.n = t, L.s = t), t;
+ }, H.s !== void 0 && (H.s.n = t), H.s = t, e.n = t, 32 & H.f && e.S(t), t;
+ if (t.i === -1) return t.i = 0, t.n !== void 0 && (t.n.p = t.p, t.p !== void 0 && (t.p.n = t.n), t.p = H.s, t.n = void 0, H.s.n = t, H.s = t), t;
}
}
-function U(e, t) {
+function K(e, t) {
this.v = e, this.i = 0, this.n = void 0, this.t = void 0, this.l = 0, this.W = t?.watched, this.Z = t?.unwatched, this.name = t?.name;
}
-U.prototype.brand = Ve, U.prototype.h = function() {
+K.prototype.brand = nt, K.prototype.h = function() {
return !0;
-}, U.prototype.S = function(e) {
+}, K.prototype.S = function(e) {
var t = this, n = this.t;
- n !== e && e.e === void 0 && (e.x = n, this.t = e, n === void 0 ? Ue(function() {
+ n !== e && e.e === void 0 && (e.x = n, this.t = e, n === void 0 ? U(function() {
var e;
(e = t.W) == null || e.call(t);
}) : n.e = e);
-}, U.prototype.U = function(e) {
+}, K.prototype.U = function(e) {
var t = this;
if (this.t !== void 0) {
var n = e.e, r = e.x;
- n !== void 0 && (n.x = r, e.e = void 0), r !== void 0 && (r.e = n, e.x = void 0), e === this.t && (this.t = r, r === void 0 && Ue(function() {
+ n !== void 0 && (n.x = r, e.e = void 0), r !== void 0 && (r.e = n, e.x = void 0), e === this.t && (this.t = r, r === void 0 && U(function() {
var e;
(e = t.Z) == null || e.call(t);
}));
}
-}, U.prototype.subscribe = function(e) {
+}, K.prototype.subscribe = function(e) {
var t = this;
- return q(function() {
+ return X(function() {
var n = t.value;
- Ue(function() {
+ U(function() {
return e(n);
});
}, { name: "sub" });
-}, U.prototype.valueOf = function() {
+}, K.prototype.valueOf = function() {
return this.value;
-}, U.prototype.toString = function() {
+}, K.prototype.toString = function() {
return this.value + "";
-}, U.prototype.toJSON = function() {
+}, K.prototype.toJSON = function() {
return this.value;
-}, U.prototype.peek = function() {
+}, K.prototype.peek = function() {
var e = this;
- return Ue(function() {
+ return U(function() {
return e.value;
});
-}, Object.defineProperty(U.prototype, "value", {
+}, Object.defineProperty(K.prototype, "value", {
get: function() {
- var e = Ke(this);
+ var e = lt(this);
return e !== void 0 && (e.i = this.i), this.v;
},
set: function(e) {
if (e !== this.v) {
- if (B > 100) throw Error("Cycle detected");
+ if (it > 100) throw Error("Cycle detected");
(function(e) {
- z !== 0 && B === 0 && e.l !== Ge && (e.l = Ge, V = {
+ G !== 0 && it === 0 && e.l !== ot && (e.l = ot, st = {
S: e,
v: e.v,
i: e.i,
- o: V
+ o: st
});
- })(this), this.v = e, this.i++, H++, z++;
+ })(this), this.v = e, this.i++, ct++, G++;
try {
for (var t = this.t; t !== void 0; t = t.x) t.t.N();
} finally {
- F();
+ B();
}
}
}
});
-function qe(e, t) {
- return new U(e, t);
+function ut(e, t) {
+ return new K(e, t);
}
-function Je(e) {
+function dt(e) {
for (var t = e.s; t !== void 0; t = t.n) if (t.S.i !== t.i || !t.S.h() || t.S.i !== t.i) return !0;
return !1;
}
-function Ye(e) {
+function ft(e) {
for (var t = e.s; t !== void 0; t = t.n) {
var n = t.S.n;
if (n !== void 0 && (t.r = n), t.S.n = t, t.i = -1, t.n === void 0) {
@@ -511,81 +854,81 @@ function Ye(e) {
}
}
}
-function Xe(e) {
+function pt(e) {
for (var t = e.s, n = void 0; t !== void 0;) {
var r = t.p;
t.i === -1 ? (t.S.U(t), r !== void 0 && (r.n = t.n), t.n !== void 0 && (t.n.p = r)) : n = t, t.S.n = t.r, t.r !== void 0 && (t.r = void 0), t = r;
}
e.s = n;
}
-function W(e, t) {
- U.call(this, void 0, t), this.x = e, this.s = void 0, this.g = H - 1, this.f = 4;
+function q(e, t) {
+ K.call(this, void 0, t), this.x = e, this.s = void 0, this.g = ct - 1, this.f = 4;
}
-W.prototype = new U(), W.prototype.h = function() {
+q.prototype = new K(), q.prototype.h = function() {
if (this.f &= -3, 1 & this.f) return !1;
- if ((36 & this.f) == 32 || (this.f &= -5, this.g === H)) return !0;
- if (this.g = H, this.f |= 1, this.i > 0 && !Je(this)) return this.f &= -2, !0;
- var e = L;
+ if ((36 & this.f) == 32 || (this.f &= -5, this.g === ct)) return !0;
+ if (this.g = ct, this.f |= 1, this.i > 0 && !dt(this)) return this.f &= -2, !0;
+ var e = H;
try {
- Ye(this), L = this;
+ ft(this), H = this;
var t = this.x();
(16 & this.f || this.v !== t || this.i === 0) && (this.v = t, this.f &= -17, this.i++);
} catch (e) {
this.v = e, this.f |= 16, this.i++;
}
- return L = e, Xe(this), this.f &= -2, !0;
-}, W.prototype.S = function(e) {
+ return H = e, pt(this), this.f &= -2, !0;
+}, q.prototype.S = function(e) {
if (this.t === void 0) {
this.f |= 36;
for (var t = this.s; t !== void 0; t = t.n) t.S.S(t);
}
- U.prototype.S.call(this, e);
-}, W.prototype.U = function(e) {
- if (this.t !== void 0 && (U.prototype.U.call(this, e), this.t === void 0)) {
+ K.prototype.S.call(this, e);
+}, q.prototype.U = function(e) {
+ if (this.t !== void 0 && (K.prototype.U.call(this, e), this.t === void 0)) {
this.f &= -33;
for (var t = this.s; t !== void 0; t = t.n) t.S.U(t);
}
-}, W.prototype.N = function() {
+}, q.prototype.N = function() {
if (!(2 & this.f)) {
this.f |= 6;
for (var e = this.t; e !== void 0; e = e.x) e.t.N();
}
-}, Object.defineProperty(W.prototype, "value", { get: function() {
+}, Object.defineProperty(q.prototype, "value", { get: function() {
if (1 & this.f) throw Error("Cycle detected");
- var e = Ke(this);
+ var e = lt(this);
if (this.h(), e !== void 0 && (e.i = this.i), 16 & this.f) throw this.v;
return this.v;
} });
-function G(e, t) {
- return new W(e, t);
+function J(e, t) {
+ return new q(e, t);
}
-function Ze(e) {
+function mt(e) {
var t = e.m;
if (e.m = void 0, typeof t == "function") {
- z++;
- var n = L;
- L = void 0;
+ G++;
+ var n = H;
+ H = void 0;
try {
t();
} catch (t) {
- throw e.f &= -2, e.f |= 8, Qe(e), t;
+ throw e.f &= -2, e.f |= 8, ht(e), t;
} finally {
- L = n, F();
+ H = n, B();
}
}
}
-function Qe(e) {
+function ht(e) {
for (var t = e.s; t !== void 0; t = t.n) t.S.U(t);
- e.x = void 0, e.s = void 0, Ze(e);
+ e.x = void 0, e.s = void 0, mt(e);
}
-function $e(e) {
- if (L !== this) throw Error("Out-of-order effect");
- Xe(this), L = e, this.f &= -2, 8 & this.f && Qe(this), F();
+function gt(e) {
+ if (H !== this) throw Error("Out-of-order effect");
+ pt(this), H = e, this.f &= -2, 8 & this.f && ht(this), B();
}
-function K(e, t) {
- this.x = e, this.m = void 0, this.s = void 0, this.u = void 0, this.f = 32, this.name = t?.name, I && I.push(this);
+function Y(e, t) {
+ this.x = e, this.m = void 0, this.s = void 0, this.u = void 0, this.f = 32, this.name = t?.name, V && V.push(this);
}
-K.prototype.c = function() {
+Y.prototype.c = function() {
var e = this.S();
try {
if (8 & this.f || this.x === void 0) return;
@@ -594,20 +937,20 @@ K.prototype.c = function() {
} finally {
e();
}
-}, K.prototype.S = function() {
+}, Y.prototype.S = function() {
if (1 & this.f) throw Error("Cycle detected");
- this.f |= 1, this.f &= -9, Ze(this), Ye(this), z++;
- var e = L;
- return L = this, $e.bind(this, e);
-}, K.prototype.N = function() {
- 2 & this.f || (this.f |= 2, this.u = R, R = this);
-}, K.prototype.d = function() {
- this.f |= 8, 1 & this.f || Qe(this);
-}, K.prototype.dispose = function() {
+ this.f |= 1, this.f &= -9, mt(this), ft(this), G++;
+ var e = H;
+ return H = this, gt.bind(this, e);
+}, Y.prototype.N = function() {
+ 2 & this.f || (this.f |= 2, this.u = W, W = this);
+}, Y.prototype.d = function() {
+ this.f |= 8, 1 & this.f || ht(this);
+}, Y.prototype.dispose = function() {
this.d();
};
-function q(e, t) {
- var n = new K(e, t);
+function X(e, t) {
+ var n = new Y(e, t);
try {
n.c();
} catch (e) {
@@ -618,35 +961,35 @@ function q(e, t) {
}
//#endregion
//#region node_modules/@preact/signals/dist/signals.module.js
-var et, J, tt = typeof window < "u" && !!window.__PREACT_SIGNALS_DEVTOOLS__, nt = [];
-q(function() {
- et = this.N;
+var _t, vt, yt = typeof window < "u" && !!window.__PREACT_SIGNALS_DEVTOOLS__, bt = [];
+X(function() {
+ _t = this.N;
})();
-function Y(e, t) {
- o[e] = t.bind(null, o[e] || function() {});
+function Z(e, t) {
+ c[e] = t.bind(null, c[e] || function() {});
}
-function rt(e) {
- if (J) {
- var t = J;
- J = void 0, t();
+function xt(e) {
+ if (vt) {
+ var t = vt;
+ vt = void 0, t();
}
- J = e && e.S();
+ vt = e && e.S();
}
-function it(e) {
- var t = this, n = e.data, r = ot(n);
+function St(e) {
+ var t = this, n = e.data, r = wt(n);
r.name = "ReactiveDom", r.value = n;
- var i = Pe(function() {
+ var i = ze(function() {
for (var e = t, n = t.__v; n = n.__;) if (n.__c) {
n.__c.__$f |= 4;
break;
}
- var i = G(function() {
+ var i = J(function() {
var e = r.value.value;
return e === 0 ? 0 : !0 === e ? "" : e || "";
- }), a = G(function() {
- return !Array.isArray(i.value) && !c(i.value);
- }), o = q(function() {
- if (this.N = lt, a.value) {
+ }), a = J(function() {
+ return !Array.isArray(i.value) && !u(i.value);
+ }), o = X(function() {
+ if (this.N = Dt, a.value) {
var t = i.value;
e.__v && e.__v.__e && e.__v.__e.nodeType === 3 && (e.__v.__e.data = t);
}
@@ -657,14 +1000,14 @@ function it(e) {
}, []), a = i[0], o = i[1];
return a.value ? o.peek() : o.value;
}
-it.displayName = "ReactiveTextNode", Object.defineProperties(U.prototype, {
+St.displayName = "ReactiveTextNode", Object.defineProperties(K.prototype, {
constructor: {
configurable: !0,
value: void 0
},
type: {
configurable: !0,
- value: it
+ value: St
},
props: {
configurable: !0,
@@ -679,35 +1022,35 @@ it.displayName = "ReactiveTextNode", Object.defineProperties(U.prototype, {
configurable: !0,
value: 1
}
-}), Y("__b", function(e, t) {
+}), Z("__b", function(e, t) {
if (typeof t.type == "string") {
var n, r = t.props;
for (var i in r) if (i !== "children") {
var a = r[i];
- a instanceof U && (n || (t.__np = n = {}), n[i] = a, r[i] = a.peek());
+ a instanceof K && (n || (t.__np = n = {}), n[i] = a, r[i] = a.peek());
}
}
e(t);
-}), Y("__r", function(e, t) {
- if (e(t), t.type !== D) {
- rt();
+}), Z("__r", function(e, t) {
+ if (e(t), t.type !== k) {
+ xt();
var n, r = t.__c;
r && (r.__$f &= -2, (n = r.__$u) === void 0 && (r.__$u = n = function(e, t) {
var n;
- return q(function() {
+ return X(function() {
n = this;
}, { name: t }), n.c = e, n;
}(function(e) {
return function() {
var t;
- tt && ((t = this.y) == null || t.call(this)), e.__$f |= 1, e.setState({});
+ yt && ((t = this.y) == null || t.call(this)), e.__$f |= 1, e.setState({});
};
- }(r), typeof t.type == "function" ? t.type.displayName || t.type.name : ""))), rt(n);
+ }(r), typeof t.type == "function" ? t.type.displayName || t.type.name : ""))), xt(n);
}
-}), Y("__e", function(e, t, n, r) {
- rt(), e(t, n, r);
-}), Y("diffed", function(e, t) {
- rt();
+}), Z("__e", function(e, t, n, r) {
+ xt(), e(t, n, r);
+}), Z("diffed", function(e, t) {
+ xt();
var n;
if (typeof t.type == "string" && (n = t.__e)) {
var r = t.__np, i = t.props, a = n.U;
@@ -717,25 +1060,25 @@ it.displayName = "ReactiveTextNode", Object.defineProperties(U.prototype, {
}
if (r) for (var c in a || (a = {}, n.U = a), r) {
var l = a[c], u = r[c];
- l === void 0 ? (l = at(n, c, u, i), a[c] = l) : l.o(u, i);
+ l === void 0 ? (l = Ct(n, c, u, i), a[c] = l) : l.o(u, i);
}
}
e(t);
});
-function at(e, t, n, r) {
- var i = t in e && e.ownerSVGElement === void 0, a = qe(n);
+function Ct(e, t, n, r) {
+ var i = t in e && e.ownerSVGElement === void 0, a = ut(n);
return {
o: function(e, t) {
a.value = e, r = t;
},
- d: q(function() {
- this.N = lt;
+ d: X(function() {
+ this.N = Dt;
var n = a.value.value;
r[t] !== n && (r[t] = n, i ? e[t] = n : n != null && (!1 !== n || t[4] === "-") ? e.setAttribute(t, n) : e.removeAttribute(t));
})
};
}
-Y("unmount", function(e, t) {
+Z("unmount", function(e, t) {
if (typeof t.type == "string") {
var n = t.__e;
if (n) {
@@ -759,9 +1102,9 @@ Y("unmount", function(e, t) {
}
}
e(t);
-}), Y("__h", function(e, t, n, r) {
+}), Z("__h", function(e, t, n, r) {
r < 3 && (t.__$f |= 2), e(t, n, r);
-}), O.prototype.shouldComponentUpdate = function(e, t) {
+}), A.prototype.shouldComponentUpdate = function(e, t) {
if (this.__R) return !0;
var n = this.__$u, r = n && n.s !== void 0;
for (var i in t) return !0;
@@ -773,140 +1116,112 @@ Y("unmount", function(e, t) {
for (var s in this.props) if (!(s in e)) return !0;
return !1;
};
-function ot(e, t) {
- return Pe(function() {
- return qe(e, t);
+function wt(e, t) {
+ return ze(function() {
+ return ut(e, t);
}, []);
}
-var st = function(e) {
+var Tt = function(e) {
queueMicrotask(function() {
queueMicrotask(e);
});
};
-function ct() {
- He(function() {
- for (var e; e = nt.shift();) et.call(e);
+function Et() {
+ rt(function() {
+ for (var e; e = bt.shift();) _t.call(e);
});
}
-function lt() {
- nt.push(this) === 1 && (o.requestAnimationFrame || st)(ct);
+function Dt() {
+ bt.push(this) === 1 && (c.requestAnimationFrame || Tt)(Et);
}
//#endregion
//#region src/state/quality-goals.ts
-var ut = "/api/quality-goals?limit=200", dt = {
+var Ot = "/api/quality-goals?limit=200", kt = {
data: null,
error: ""
-}, X = qe(dt), Z = 0, ft = G(() => X.value);
-G(() => X.value.data?.total ?? null);
-function pt() {
- Z += 1, X.value = dt;
+}, Q = ut(kt), At = 0, jt = J(() => Q.value);
+J(() => Q.value.data?.total ?? null);
+function Mt() {
+ At += 1, Q.value = kt;
}
-async function mt(e) {
- let t = Z += 1;
+async function Nt(e) {
+ let t = At += 1;
try {
- let n = await xe(ut, e);
- return t === Z && (X.value = {
+ let n = await Se(Ot, e);
+ return t === At && (Q.value = {
data: n,
error: ""
}), n;
} catch (n) {
- throw !e?.aborted && t === Z && (X.value = {
+ throw !e?.aborted && t === At && (Q.value = {
data: null,
- error: be(n)
+ error: N(n)
}), n;
}
}
//#endregion
-//#region node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js
-var ht = 0;
-Array.isArray;
-function Q(e, t, n, r, i, a) {
- t ||= {};
- var s, c, l = t;
- if ("ref" in l) for (c in l = {}, t) c == "ref" ? s = t[c] : l[c] = t[c];
- var u = {
- type: e,
- props: l,
- key: n,
- ref: s,
- __k: null,
- __: null,
- __b: 0,
- __e: null,
- __c: null,
- constructor: void 0,
- __v: --ht,
- __i: -1,
- __u: 0,
- __source: i,
- __self: a
- };
- if (typeof e == "function" && (s = e.defaultProps)) for (c in s) l[c] === void 0 && (l[c] = s[c]);
- return o.vnode && o.vnode(u), u;
-}
-//#endregion
//#region src/islands/quality-goals.tsx
-var gt = (e, t) => mt(t), _t = (e) => e.has_cover ? `/cover?code=${encodeURIComponent(e.code ?? "")}` : `/poster?id=${e.id}&c=4`;
-function vt({ openItem: a, javTitleHtml: o, javDisplayName: s, srcBadge: c }) {
- let { data: l, error: u } = ft.value;
- if (u) return /* @__PURE__ */ Q("div", {
+var Pt = (e, t) => Nt(t), Ft = (e) => e.has_cover ? `/cover?code=${encodeURIComponent(e.code ?? "")}` : `/poster?id=${e.id}&c=4`;
+function It({ openItem: t, javTitleHtml: r, javDisplayName: s, srcBadge: c }) {
+ let { data: l, error: u } = jt.value;
+ if (u) return /* @__PURE__ */ R("div", {
class: "qualitylist",
- dangerouslySetInnerHTML: { __html: i(u, {
+ dangerouslySetInnerHTML: { __html: n(u, {
variant: "error",
label: "读取失败"
}) }
});
let d = l?.items ?? [];
- return d.length ? /* @__PURE__ */ Q("div", {
+ return d.length ? /* @__PURE__ */ R("div", {
class: "qualitylist",
- children: d.map((r) => /* @__PURE__ */ Q("article", {
+ children: d.map((e) => /* @__PURE__ */ R("article", {
class: "qualityitem",
- children: [/* @__PURE__ */ Q("button", {
+ children: [/* @__PURE__ */ R("button", {
class: "qualitycover",
type: "button",
- "aria-label": `打开 ${s(r)}`,
- onClick: () => a(r.id),
- children: /* @__PURE__ */ Q("img", {
- src: _t(r),
+ "aria-label": `打开 ${s(e)}`,
+ onClick: () => t(e.id),
+ children: /* @__PURE__ */ R("img", {
+ src: Ft(e),
alt: "",
loading: "lazy",
onError: (e) => e.currentTarget.remove()
})
- }), /* @__PURE__ */ Q("div", { children: [
- /* @__PURE__ */ Q("h3", { children: /* @__PURE__ */ Q("button", {
+ }), /* @__PURE__ */ R("div", { children: [
+ /* @__PURE__ */ R("h3", { children: /* @__PURE__ */ R("button", {
type: "button",
"data-middle-truncate": !0,
- onClick: () => a(r.id),
- dangerouslySetInnerHTML: { __html: o(r) }
+ onClick: () => t(e.id),
+ dangerouslySetInnerHTML: { __html: r(e) }
}) }),
- /* @__PURE__ */ Q("p", {
+ /* @__PURE__ */ R("p", {
class: "mono",
children: [
- /* @__PURE__ */ Q("span", {
+ /* @__PURE__ */ R("span", {
style: "display:contents",
- dangerouslySetInnerHTML: { __html: c(r.location, r.cost) }
+ dangerouslySetInnerHTML: { __html: c(e.location, e.cost) }
}),
- /* @__PURE__ */ Q("span", { children: e[r.location] ?? r.location }),
- /* @__PURE__ */ Q("span", { children: t(r.duration) }),
- /* @__PURE__ */ Q("span", { children: n(r.size ?? 0) })
+ /* @__PURE__ */ R("span", { children: i[e.location] ?? e.location }),
+ /* @__PURE__ */ R("span", { children: a(e.duration) }),
+ /* @__PURE__ */ R("span", { children: o(e.size ?? 0) })
]
}),
- r.reason ? /* @__PURE__ */ Q("p", { children: r.reason }) : null
+ e.reason ? /* @__PURE__ */ R("p", { children: e.reason }) : null
] })]
- }, r.id))
- }) : /* @__PURE__ */ Q("div", {
+ }, e.id))
+ }) : /* @__PURE__ */ R("div", {
class: "qualitylist",
- dangerouslySetInnerHTML: { __html: r("sparkles", "没有标记中的高清版目标", "现有版本都已满足条件,或还没有加入追踪。") }
+ dangerouslySetInnerHTML: { __html: e("sparkles", "没有标记中的高清版目标", "现有版本都已满足条件,或还没有加入追踪。") }
});
}
//#endregion
//#region src/state/index.ts
-var yt = { "quality-goals": {
- refresh: mt,
- reset: pt
-} }, bt = () => Object.keys(yt);
-async function xt(e) {
- let t = yt[e];
+var Lt = { "quality-goals": {
+ refresh: Nt,
+ reset: Mt
+} }, Rt = () => Object.keys(Lt);
+async function zt(e) {
+ let t = Lt[e];
if (!t) throw Error(`未登记的共享 store:${String(e)}`);
try {
return await t.refresh(), !0;
@@ -916,7 +1231,7 @@ async function xt(e) {
}
//#endregion
//#region src/jobs.ts
-async function St(e) {
+async function Bt(e) {
let t = e.pause || ((e) => new Promise((t) => setTimeout(t, e))), n = 0;
for (; e.active();) {
let r;
@@ -931,11 +1246,11 @@ async function St(e) {
await t(2e3);
}
}
-function Ct(e) {
+function Vt(e) {
let t = document.createElement("div");
e.host.hidden = !0, t.dataset.followJob = "", t.setAttribute("aria-live", "polite"), e.host.prepend(t);
let n = e.storageKey || "peach-follow-job", r = sessionStorage.getItem(n) || void 0, i = !1;
- St({
+ Bt({
read: e.read,
active: () => !i && e.active() && t.isConnected,
keepWatching: e.watchIdle !== !1,
@@ -961,7 +1276,7 @@ function Ct(e) {
}
//#endregion
//#region src/sidebar.ts
-function wt(e) {
+function Ht(e) {
return [
"/",
"/unseen",
@@ -971,24 +1286,30 @@ function wt(e) {
"/junk-files"
].includes(e) || /^\/(item|mix|parts|editions)\//.test(e) || /^\/playlists\/\d+\/\d+$/.test(e) || /^\/(performers|studios|creators|series|agencies)\/.+/.test(e);
}
-function Tt(e, t) {
+function Ut(e, t) {
return e.dataset.surface === t && e.querySelector(".dnav") ? !1 : (e.dataset.surface = t, e.replaceChildren(), !0);
}
-function Et(e) {
+function Wt(e) {
let t = /* @__PURE__ */ new Map();
for (let n of e) for (let e of new Set(n.tags || [])) t.set(e, (t.get(e) || 0) + 1);
return [...t].sort((e, t) => t[1] - e[1]).slice(0, 30);
}
//#endregion
//#region src/islands.ts
-var Dt = { "quality-goals": {
- load: gt,
- component: vt
-} }, Ot = () => Object.keys(Dt), $ = /* @__PURE__ */ new Map();
-async function kt(e, t, n, r = {}) {
- let i = Dt[e];
+var Gt = {
+ "quality-goals": {
+ load: Pt,
+ component: It
+ },
+ configuration: {
+ load: Ze,
+ component: tt
+ }
+}, Kt = () => Object.keys(Gt), $ = /* @__PURE__ */ new Map();
+async function qt(e, t, n, r = {}) {
+ let i = Gt[e];
if (!i) throw Error(`未注册的 island:${String(e)}`);
- At(t);
+ Jt(t);
let a = {
controller: new AbortController(),
painted: !1
@@ -1004,23 +1325,24 @@ async function kt(e, t, n, r = {}) {
if (a.controller.signal.aborted) return;
o = {
data: null,
- error: be(e)
+ error: N(e)
};
}
- if ($.get(t) === a) {
- if (r.isCurrent && !r.isCurrent()) {
- $.delete(t);
- return;
- }
- t.textContent = "", a.painted = !0, _e(T(i.component, {
- ...n,
- ...o
- }), t);
+ if ($.get(t) !== a) return;
+ if (r.isCurrent && !r.isCurrent()) {
+ $.delete(t);
+ return;
}
+ t.textContent = "", a.painted = !0;
+ let s = {
+ ...n,
+ ...o
+ };
+ ye(D(i.component, s), t);
}
-function At(e) {
+function Jt(e) {
let t = $.get(e);
- t && (t.controller.abort(), $.delete(e), t.painted && _e(null, e));
+ t && (t.controller.abort(), $.delete(e), t.painted && ye(null, e));
}
//#endregion
-export { Ct as followJobProgress, Ot as islandNames, kt as mountIsland, xt as refreshStore, wt as sidebarHasCatalogContent, Et as sidebarTagCounts, bt as storeNames, Tt as syncSidebarSurface, At as unmountIsland, St as watchJob };
+export { Vt as followJobProgress, Kt as islandNames, qt as mountIsland, zt as refreshStore, Ht as sidebarHasCatalogContent, Wt as sidebarTagCounts, Rt as storeNames, Ut as syncSidebarSurface, Jt as unmountIsland, Bt as watchJob };
diff --git a/web/index.html b/web/index.html
index 6af32280d..22589f4a0 100644
--- a/web/index.html
+++ b/web/index.html
@@ -36,7 +36,7 @@
<symbol id="i-arrow-up" viewBox="0 0 24 24"><path d="m5 12 7-7 7 7" /><path d="M12 19V5" /></symbol>
<symbol id="i-chart" viewBox="0 0 24 24"><path d="M5 21v-6" /><path d="M12 21V3" /><path d="M19 21V9" /></symbol>
<symbol id="i-settings" viewBox="0 0 24 24"><path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" /><circle cx="12" cy="12" r="3" /></symbol>
- <symbol id="i-monitor" viewBox="0 0 24 24"><rect width="20" height="14" x="2" y="3" rx="2" /><line x1="8" x2="16" y1="21" y2="21" /><line x1="12" x2="12" y1="17" y2="21" /></symbol>
+ <symbol id="i-monitor" viewBox="0 0 24 24"><rect width="20" height="14" x="2" y="3" rx="2" /><line x1="8" x2="16" y1="21" y2="21" /><line x1="12" x2="12" y1="17" y2="21" /></symbol><symbol id="i-computer" viewBox="0 0 24 24"><rect width="14" height="8" x="5" y="2" rx="2" /><rect width="20" height="8" x="2" y="14" rx="2" /><path d="M6 18h2" /><path d="M12 18h6" /></symbol><symbol id="i-folder-search" viewBox="0 0 24 24"><path d="M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1" /><path d="m21 21-1.9-1.9" /><circle cx="17" cy="17" r="3" /></symbol>
<symbol id="i-gauge" viewBox="0 0 24 24"><path d="m12 14 4-4" /><path d="M3.34 19a10 10 0 1 1 17.32 0" /></symbol>
<symbol id="i-theater-enter" viewBox="0 0 24 24"><rect x="2" y="3" width="20" height="18" rx="1.5"/><path d="M2 16h20M8.5 7 5.5 10l3 3M15.5 7l3 3-3 3"/></symbol>
<symbol id="i-theater-exit" viewBox="0 0 24 24"><rect x="2" y="3" width="20" height="18" rx="1.5"/><path d="M2 16h20M5.5 7l3 3-3 3M18.5 7l-3 3 3 3"/></symbol>
@@ -186,7 +186,6 @@
<div class="settingscard">
<div class="settingshead"><h2 id="settingsTitle">设置</h2><button id="settingsClose" aria-label="关闭设置"><svg viewBox="0 0 24 24"><use href="#i-x"/></svg></button></div>
<div class="settingsscroll">
- <section class="settinggroup"><h3>这台电脑</h3><a class="settingrow" href="/configuration">媒体文件夹与服务配置</a></section>
<section class="settinggroup"><h3>浏览</h3>
<label class="settingrow"><span><b>每批作品</b><small>首页每次加载的作品数量。</small></span><select id="batchSizeSetting"><option value="30">30 个</option><option value="60">60 个</option><option value="90">90 个</option></select></label>
<label class="settingrow"><span><b>默认排序</b><small>打开首页时使用的排序。</small></span><select id="defaultSortSetting"><option value="seed">随机</option><option value="rating">评分</option><option value="o">高潮计数</option><option value="plays">观看次数</option><option value="dur">时长</option><option value="size">体积</option><option value="new">入库时间</option><option value="played">观看时间</option></select></label>
diff --git a/web/vendor/lucide-ORIGIN.md b/web/vendor/lucide-ORIGIN.md
index b347f2bce..78aeca32b 100644
--- a/web/vendor/lucide-ORIGIN.md
+++ b/web/vendor/lucide-ORIGIN.md
@@ -3,7 +3,7 @@
- npm 包:`[email protected]`
- npm lock integrity:`sha512-/pRaHJceXrQyAMzWfwhWPMwZeiZEIejZ+Ko226AqI52QbLVgowyGAp7OzZIaQEf7XB+LuRGWqUGqTfu3LJ0CQQ==`
- 许可证:ISC;原文见 `lucide-LICENSE.txt`
-- 消费者:`web/index.html` 内联的 58 个 symbol
+- 消费者:`web/index.html` 内联的 60 个 symbol
雪碧图里另有 6 枚自绘 symbol(alert、pics、jav、theater-enter、theater-exit、brand-x)与 16 枚 player-* 前缀的播放器图标,都没有上游可对。
RSS 与拖动点保留填充修正,避免小圆点在全局描边样式下消失。