Peach: Local-first video metadata scraper and media manager.
feat(frontend): island 挂载契约与高清版目标页组件
longmeidaoa170f6f83d04
diff --git a/frontend/src/islands.ts b/frontend/src/islands.tsnew file mode 100644index 000000000..d8849fba8--- /dev/null+++ b/frontend/src/islands.ts@@ -0,0 +1,104 @@+/* island 挂载契约(ADR-0022)。+ *+ * 遗留路由(`web/app.js`)仍然拥有整个外壳和每一个页面。一个页面被重写成 Preact+ * 之后,它的入口只做两件事:铺好加载占位,然后把一个容器交给这里。+ *+ * const ui = await import('/dist/peach-ui.js');+ * await ui.mountIsland('quality-goals', $('#stats'), props);+ *+ * `mountIsland` 是 async 且**取完数才画**:遗留层已经铺了骨架,island 若先画一个空+ * 容器再自己转圈,同一次进入就会出现两段等待态(`peach-web-ui` 明确禁止)。所以这里+ * 先 await `load()`,再一次性换掉骨架。+ *+ * 容器由遗留层拥有:它会在别的页面进入时直接 `innerHTML=`。因此 `mountIsland` 每次+ * 都先自我卸载,`unmountIsland` 也不假设 DOM 还在原处。 */+import { h, render } from 'preact';+import type { ComponentType } from 'preact';++import { QualityGoals, loadQualityGoals } from './islands/quality-goals';+import type { QualityGoalsData, QualityGoalsProps } from './islands/quality-goals';++/** 首屏取数的结果。`data` 与 `error` 恰有一个成立。 */+export interface IslandState<D> {+ data: D | null;+ error: string;+}++/** 每个 island 的 props 与首屏数据类型。新增 island 时在这里登记,注册表随之要求实现。 */+export interface IslandContracts {+ 'quality-goals': { props: QualityGoalsProps; data: QualityGoalsData };+}++export type IslandName = keyof IslandContracts;+type PropsOf<N extends IslandName> = IslandContracts[N]['props'];+type DataOf<N extends IslandName> = IslandContracts[N]['data'];++interface IslandDefinition<N extends IslandName> {+ /** 首屏取数。中止后抛 `AbortError`,`mountIsland` 会静默放弃。 */+ load(props: PropsOf<N>, signal: AbortSignal): Promise<DataOf<N>>;+ component: ComponentType<PropsOf<N> & IslandState<DataOf<N>>>;+}++const REGISTRY: { [N in IslandName]: IslandDefinition<N> } = {+ 'quality-goals': { load: loadQualityGoals, component: QualityGoals },+};++/** 已注册的 island 名字。遗留层与测试用它核对路由表,不必知道注册表结构。 */+export const islandNames = (): IslandName[] => Object.keys(REGISTRY) as IslandName[];++interface Mount {+ controller: AbortController;+ /** 是否已经真的画过。没画过就不许 `render(null, el)`:那会连遗留骨架一起清掉。 */+ painted: boolean;+}++const mounted = new Map<Element, Mount>();++/** 遗留层的换页判据。它的路由是「代」而不是 AbortSignal,所以这里收一个谓词:+ * 取数期间用户走开了,island 不能把数据画到别的页面上。 */+export interface MountOptions {+ isCurrent?: () => boolean;+}++/** 挂载一个 island 并等首屏数据落地。容器里原有的内容(遗留骨架)在这一刻被换掉。 */+export async function mountIsland<N extends IslandName>(+ name: N,+ el: Element,+ props: PropsOf<N>,+ options: MountOptions = {},+): Promise<void> {+ const island = REGISTRY[name] as IslandDefinition<N> | undefined;+ if (!island) throw new Error(`未注册的 island:${String(name)}`);+ unmountIsland(el);+ const mount: Mount = { controller: new AbortController(), painted: false };+ mounted.set(el, mount);+ let state: IslandState<DataOf<N>>;+ try {+ state = { data: await island.load(props, mount.controller.signal), error: '' };+ } catch (cause) {+ if (mount.controller.signal.aborted) return;+ state = { data: null, error: cause instanceof Error ? cause.message : String(cause) };+ }+ // 期间被卸载或重新挂载:这一次的结果已经过期,不许往新内容上盖。+ if (mounted.get(el) !== mount) return;+ // 遗留层已经换了页面:容器现在归别人,画上去就是把别的页面盖掉。+ if (options.isCurrent && !options.isCurrent()) {+ mounted.delete(el);+ return;+ }+ // 遗留骨架不是 Preact 画的,交给 diff 会按标签复用节点、留下 data-skeleton 之类的+ // 旧属性。整个清掉再画,一次替换,只有一次布局变化。+ el.textContent = '';+ mount.painted = true;+ render(h(island.component, { ...props, ...state }), el);+}++/** 卸载容器上的 island:中止在途取数并清空自己画过的内容。没挂过的容器是空操作。 */+export function unmountIsland(el: Element): void {+ const mount = mounted.get(el);+ if (!mount) return;+ mount.controller.abort();+ mounted.delete(el);+ // 只清自己画过的东西。还在取数时容器里是遗留骨架,那不属于 island。+ if (mount.painted) render(null, el);+}diff --git a/frontend/src/islands/quality-goals.tsx b/frontend/src/islands/quality-goals.tsxnew file mode 100644index 000000000..4762e3787--- /dev/null+++ b/frontend/src/islands/quality-goals.tsx@@ -0,0 +1,127 @@+/* 「高清版」管理页(`/quality-goals`)。第一个从 `web/app.js` 迁出来的页面。+ *+ * 选它是因为它的边界最干净:一个 GET(`/api/quality-goals`)、一个自己的容器、+ * 没有写入端点、没有轮询,样式在 `web/app.css` 里已经是独立的 `.qualitylist`/+ * `.qualityitem`。迁移它不需要动别的页面,也不需要动样式。+ *+ * 遗留层那几个返回 HTML 的助手(番号标题、来源徽标)由 props 传进来,不在这里重写:+ * 它们是全站语义契约的唯一实现,抄一份就会漂。等下一批页面迁移时再把它们提升成+ * TS 组件,那时 props 一起收窄。 */+import { LOC, fmtDur, fmtSize } from '@peach/legacy/core';+import { emptyStateHtml, noteHtml } from '@peach/legacy/ui';++import { apiGet } from '../api';+import type { IslandState } from '../islands';++/** `/api/quality-goals` 的单条目。字段与 `web_contract.q_quality_goals` 对齐。 */+export interface QualityGoal {+ id: number;+ name: string;+ code: string | null;+ location: string;+ size: number | null;+ duration: number | null;+ reason: string | null;+ cost: string;+ has_thumb: boolean;+ has_cover: boolean;+}++export interface QualityGoalsData {+ total: number;+ items: QualityGoal[];+ offset: number;+ has_more: boolean;+}++/** 仍由遗留层提供的能力。全是纯函数或导航,island 不持有它们的状态。 */+export interface QualityGoalsProps {+ /** 打开作品详情(遗留层的整页视图,含播放器与队列)。 */+ openItem(id: number): void;+ /** 番号 + 版次徽章 + 标题的 HTML。非 JAV 条目退化成转义后的文件名。 */+ javTitleHtml(item: QualityGoal): string;+ /** 同一条目的纯文本形态,用于无障碍名称。 */+ javDisplayName(item: QualityGoal): string;+ /** 来源徽标(含计费标记)的 HTML。 */+ srcBadge(location: string, cost: string): string;+}++/** 上限沿用遗留层的 200:服务端 `limit` 也钉在 200,再大只会被截。 */+export const QUALITY_GOALS_URL = '/api/quality-goals?limit=200';++export const loadQualityGoals = (+ _props: QualityGoalsProps,+ signal: AbortSignal,+): Promise<QualityGoalsData> => apiGet<QualityGoalsData>(QUALITY_GOALS_URL, signal);++/** 封面优先用番号封面,没有就退回第 4 张海报,两者都取不到时把 img 摘掉。 */+const previewUrl = (item: QualityGoal): string => item.has_cover+ ? `/cover?code=${encodeURIComponent(item.code ?? '')}`+ : `/poster?id=${item.id}&c=4`;++export function QualityGoals(+ { data, error, openItem, javTitleHtml, javDisplayName, srcBadge }:+ QualityGoalsProps & IslandState<QualityGoalsData>,+) {+ if (error) {+ return (+ <div+ class="qualitylist"+ dangerouslySetInnerHTML={{ __html: noteHtml(error, { variant: 'error', label: '读取失败' }) }}+ />+ );+ }+ const items = data?.items ?? [];+ if (!items.length) {+ return (+ <div+ class="qualitylist"+ dangerouslySetInnerHTML={{+ __html: emptyStateHtml('sparkles', '没有标记中的高清版目标',+ '现有版本都已满足条件,或还没有加入追踪。'),+ }}+ />+ );+ }+ return (+ <div class="qualitylist">+ {items.map(item => (+ <article class="qualityitem" key={item.id}>+ <button+ class="qualitycover"+ type="button"+ aria-label={`打开 ${javDisplayName(item)}`}+ onClick={() => openItem(item.id)}+ >+ <img+ src={previewUrl(item)}+ alt=""+ loading="lazy"+ onError={event => event.currentTarget.remove()}+ />+ </button>+ <div>+ <h3>+ <button+ type="button"+ data-middle-truncate+ onClick={() => openItem(item.id)}+ dangerouslySetInnerHTML={{ __html: javTitleHtml(item) }}+ />+ </h3>+ <p class="mono">+ {/* Preact 插原始 HTML 必须有个宿主元素,而 `.src` 在遗留版本里是这个+ flex 容器的直接子项(20×20 的 grid 盒)。`display:contents` 让宿主+ 从布局里消失,徽标的对齐与间距保持不变。 */}+ <span style="display:contents" dangerouslySetInnerHTML={{ __html: srcBadge(item.location, item.cost) }} />+ <span>{LOC[item.location] ?? item.location}</span>+ <span>{fmtDur(item.duration)}</span>+ <span>{fmtSize(item.size ?? 0)}</span>+ </p>+ {item.reason ? <p>{item.reason}</p> : null}+ </div>+ </article>+ ))}+ </div>+ );+}diff --git a/frontend/test/helpers.ts b/frontend/test/helpers.tsnew file mode 100644index 000000000..b0e36466d--- /dev/null+++ b/frontend/test/helpers.ts@@ -0,0 +1,57 @@+import { vi } from 'vitest';++import type { QualityGoal, QualityGoalsData, QualityGoalsProps } from '../src/islands/quality-goals';++export const goal = (overrides: Partial<QualityGoal> = {}): QualityGoal => ({+ id: 1,+ name: 'one.mp4',+ code: null,+ location: 'local',+ size: 2147483648,+ duration: 3725,+ reason: null,+ cost: 'free',+ has_thumb: true,+ has_cover: false,+ ...overrides,+});++export const payload = (items: QualityGoal[]): QualityGoalsData => ({+ total: items.length,+ items,+ offset: 0,+ has_more: false,+});++/** 遗留层传进来的那几个助手。测试里换成可辨认的最小实现,断言只看 island 是否用了它们。 */+export const legacyProps = () => {+ const openItem = vi.fn<(id: number) => void>();+ const props: QualityGoalsProps = {+ openItem,+ javTitleHtml: item => `<strong class="javcode">${item.name}</strong>`,+ javDisplayName: item => `名称 ${item.name}`,+ srcBadge: (location, cost) => `<span class="src ${cost}" data-location="${location}"></span>`,+ };+ return { ...props, openItem };+};++/** 一个可手动兑现的 fetch:island 的等待窗口本身就是被测行为,不能靠 setTimeout 猜。 */+export function deferredFetch(body: unknown) {+ let settle = (): void => {};+ let signal: AbortSignal | undefined;+ const fetched = vi.fn((_input: string, init?: RequestInit) => {+ signal = init?.signal ?? undefined;+ return new Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>((resolve, reject) => {+ settle = () => resolve({ ok: true, status: 200, json: async () => body });+ signal?.addEventListener('abort', () => {+ reject(new DOMException('已中止', 'AbortError'));+ });+ });+ });+ return {+ fetched,+ resolve: () => settle(),+ signal: () => signal,+ install: () => vi.stubGlobal('fetch', fetched),+ };+}diff --git a/frontend/test/islands.test.ts b/frontend/test/islands.test.tsnew file mode 100644index 000000000..f6adfd471--- /dev/null+++ b/frontend/test/islands.test.ts@@ -0,0 +1,114 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { islandNames, mountIsland, unmountIsland } from '../src/islands';++import { deferredFetch, goal, legacyProps, payload } from './helpers';++const container = () => {+ const el = document.createElement('div');+ // 遗留层进入页面时先铺骨架,island 接手的容器里已经有东西。+ el.innerHTML = '<div class="geist-skeleton" data-skeleton="cards">正在读取高清版目标</div>';+ document.body.append(el);+ return el;+};++afterEach(() => {+ document.body.innerHTML = '';+ vi.unstubAllGlobals();+});++describe('island 注册表', () => {+ it('登记的名字就是遗留路由能挂载的名字', () => {+ expect(islandNames()).toEqual(['quality-goals']);+ });++ it('未注册的名字立刻失败,不是静默什么都不画', async () => {+ const el = container();+ // @ts-expect-error 名字不在契约里:这条断言的目的就是运行期也要拦住。+ await expect(mountIsland('nope', el, {})).rejects.toThrow('未注册的 island:nope');+ });+});++describe('mountIsland', () => {+ it('取数期间保留遗留骨架,数据到位才一次性换掉', async () => {+ const fetch = deferredFetch(payload([goal()]));+ fetch.install();+ const el = container();+ const mounting = mountIsland('quality-goals', el, legacyProps());+ await Promise.resolve();+ expect(el.querySelector('[data-skeleton]'), '骨架被提前撤掉会出现第二段等待态').not.toBeNull();+ fetch.resolve();+ await mounting;+ expect(el.querySelector('[data-skeleton]')).toBeNull();+ expect(el.querySelectorAll('.qualityitem')).toHaveLength(1);+ });++ it('首屏取数失败时画出原因,不留在骨架上', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: false,+ status: 500,+ json: async () => ({ message: '账本当前只能浏览' }),+ })));+ const el = container();+ await mountIsland('quality-goals', el, legacyProps());+ expect(el.querySelector('.geist-note-error')?.textContent).toContain('账本当前只能浏览');+ });++ it('取数期间用户走开就不画:遗留层换页的判据是代,不是信号', async () => {+ const fetch = deferredFetch(payload([goal()]));+ fetch.install();+ const el = container();+ let current = true;+ const mounting = mountIsland('quality-goals', el, legacyProps(), {+ isCurrent: () => current,+ });+ await Promise.resolve();+ current = false;+ fetch.resolve();+ await mounting;+ expect(el.querySelector('.qualityitem'), '页面已经换掉,数据不能盖上去').toBeNull();+ expect(el.querySelector('[data-skeleton]')).not.toBeNull();+ });++ it('重新挂载时上一次的迟到响应不再写进容器', async () => {+ const stale = deferredFetch(payload([goal({ id: 7, name: 'stale.mp4' })]));+ stale.install();+ const el = container();+ const first = mountIsland('quality-goals', el, legacyProps());+ await Promise.resolve();++ const fresh = deferredFetch(payload([goal({ id: 9, name: 'fresh.mp4' })]));+ fresh.install();+ const second = mountIsland('quality-goals', el, legacyProps());+ fresh.resolve();+ await second;+ stale.resolve();+ await first;++ expect(el.querySelectorAll('.qualityitem')).toHaveLength(1);+ expect(el.textContent).toContain('fresh.mp4');+ expect(el.textContent).not.toContain('stale.mp4');+ });+});++describe('unmountIsland', () => {+ it('中止在途取数并清空容器', async () => {+ const fetch = deferredFetch(payload([goal()]));+ fetch.install();+ const el = container();+ const mounting = mountIsland('quality-goals', el, legacyProps());+ await Promise.resolve();+ unmountIsland(el);+ await mounting;+ expect(fetch.signal()?.aborted, '离开页面必须真的中止请求').toBe(true);+ expect(el.querySelector('.qualityitem')).toBeNull();+ expect(el.querySelector('[data-skeleton]'),+ '还没画过就卸载时容器里是遗留骨架,island 不该清掉不属于它的东西').not.toBeNull();+ });++ it('没挂载过的容器是空操作,不抛错也不动 DOM', () => {+ const el = container();+ unmountIsland(el);+ expect(el.querySelector('[data-skeleton]')).not.toBeNull();+ });+});diff --git a/frontend/test/quality-goals.test.tsx b/frontend/test/quality-goals.test.tsxnew file mode 100644index 000000000..126cc881f--- /dev/null+++ b/frontend/test/quality-goals.test.tsx@@ -0,0 +1,101 @@+import { render } from 'preact';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ QUALITY_GOALS_URL, QualityGoals, loadQualityGoals,+} from '../src/islands/quality-goals';+import type { QualityGoalsData } from '../src/islands/quality-goals';++import { goal, legacyProps, payload } from './helpers';++const mount = (data: QualityGoalsData | null, error = '') => {+ const el = document.createElement('div');+ document.body.append(el);+ const props = legacyProps();+ render(<QualityGoals {...props} data={data} error={error} />, el);+ return { el, props };+};++afterEach(() => {+ document.body.innerHTML = '';+ vi.unstubAllGlobals();+});++describe('高清版目标列表', () => {+ it('每条目标一张卡片,读数走遗留层同一套格式化口径', () => {+ const { el } = mount(payload([goal({+ id: 42, name: 'one.mp4', location: '115', cost: 'metered',+ duration: 3725, size: 2147483648, reason: '只有 720p',+ })]));+ const item = el.querySelector('.qualityitem');+ expect(item).not.toBeNull();+ const cells = [...item!.querySelectorAll('p.mono > span')].map(node => node.textContent);+ expect(cells).toEqual(['', '115', '1:02:05', '2.0 GB']);+ expect(item!.querySelector('.src')?.getAttribute('data-location')).toBe('115');+ expect(item!.querySelector('.src')?.classList.contains('metered')).toBe(true);+ expect(item!.querySelector('h3 .javcode')?.textContent).toBe('one.mp4');+ expect(item!.querySelector('h3 button')?.hasAttribute('data-middle-truncate')).toBe(true);+ expect([...item!.querySelectorAll('p')].at(-1)?.textContent).toBe('只有 720p');+ });++ it('探测失败的时长显示占位,不显示 0 也不显示负数', () => {+ const { el } = mount(payload([goal({ duration: -1, size: 0 })]));+ const cells = [...el.querySelectorAll('p.mono > span')].map(node => node.textContent);+ expect(cells).toEqual(['', '本地', '—', '0 MB']);+ });++ it('有番号封面就用番号封面,否则退回海报', () => {+ const withCover = mount(payload([goal({ has_cover: true, code: 'ABC-123' })]));+ expect(withCover.el.querySelector('img')?.getAttribute('src'))+ .toBe('/cover?code=ABC-123');+ const withoutCover = mount(payload([goal({ id: 7, has_cover: false })]));+ expect(withoutCover.el.querySelectorAll('img')[0]?.getAttribute('src'))+ .toBe('/poster?id=7&c=4');+ });++ it('封面取不到就把图摘掉,卡片其余部分照常显示', () => {+ const { el } = mount(payload([goal()]));+ const image = el.querySelector('img')!;+ image.dispatchEvent(new Event('error'));+ expect(el.querySelector('img')).toBeNull();+ expect(el.querySelector('.qualitycover')).not.toBeNull();+ });++ it('封面和标题都能打开详情,无障碍名称用纯文本形态', () => {+ const { el, props } = mount(payload([goal({ id: 42 })]));+ const cover = el.querySelector<HTMLButtonElement>('.qualitycover')!;+ expect(cover.getAttribute('aria-label')).toBe('打开 名称 one.mp4');+ cover.click();+ el.querySelector<HTMLButtonElement>('h3 button')!.click();+ expect(props.openItem.mock.calls).toEqual([[42], [42]]);+ });++ it('没有目标时用共享空态,不是一行灰字', () => {+ const { el } = mount(payload([]));+ expect(el.querySelector('[data-geist-empty-state]')).not.toBeNull();+ expect(el.querySelector('.es-copy h3')?.textContent).toBe('没有标记中的高清版目标');+ expect(el.querySelector('.qualityitem')).toBeNull();+ });++ it('读取失败时把原因留在原位,用 error Note', () => {+ const { el } = mount(null, '请求失败(500)');+ const note = el.querySelector('.geist-note-error');+ expect(note?.textContent).toContain('请求失败(500)');+ expect(el.querySelector('[data-geist-empty-state]')).toBeNull();+ });+});++describe('loadQualityGoals', () => {+ it('取的是遗留层同一个契约端点,并把中止信号带下去', async () => {+ const fetched = vi.fn(async (_input: string, _init?: RequestInit) => (+ { ok: true, status: 200, json: async () => payload([]) }+ ));+ vi.stubGlobal('fetch', fetched);+ const controller = new AbortController();+ await loadQualityGoals(legacyProps(), controller.signal);+ expect(QUALITY_GOALS_URL).toBe('/api/quality-goals?limit=200');+ expect(fetched.mock.calls[0]?.[0]).toBe(QUALITY_GOALS_URL);+ expect((fetched.mock.calls[0]?.[1] as RequestInit).signal).toBe(controller.signal);+ expect((fetched.mock.calls[0]?.[1] as RequestInit).credentials).toBe('same-origin');+ });+});diff --git a/frontend/test/stubs/legacy-core.ts b/frontend/test/stubs/legacy-core.tsnew file mode 100644index 000000000..4bc6ec3ad--- /dev/null+++ b/frontend/test/stubs/legacy-core.ts@@ -0,0 +1,29 @@+/* `/js/core.js` 在测试里的替身(vitest.config.ts 里做 alias)。+ *+ * 真实实现由 Peach 在浏览器里提供,node 里不存在。这里照抄它的**行为**而不是引用它:+ * 断言要能说明「island 用的是遗留层的格式化口径」,所以哨兵值(时长 0/负数 → `—`)+ * 必须一起复制过来,否则测试会放过一个把 `-1` 画成 `0:-1` 的回归。 */+export const LOC: Record<string, string> = {+ local: '本地',+ '115': '115',+ pikpak: 'PikPak',+ online: '在线',+};++export const fmtDur = (seconds: number | null | undefined): string => {+ const total = Number(seconds);+ if (!Number.isFinite(total) || total <= 0) return '—';+ const value = Math.round(total);+ const hours = Math.floor(value / 3600);+ const minutes = Math.floor((value % 3600) / 60);+ const rest = value % 60;+ const pad = (part: number) => String(part).padStart(2, '0');+ return hours ? `${hours}:${pad(minutes)}:${pad(rest)}` : `${minutes}:${pad(rest)}`;+};++export const fmtSize = (bytes: number | null | undefined): string => {+ const value = Number(bytes) || 0;+ if (value >= 1099511627776) return `${(value / 1099511627776).toFixed(2)} TB`;+ if (value >= 1073741824) return `${(value / 1073741824).toFixed(1)} GB`;+ return `${Math.floor(value / 1048576)} MB`;+};diff --git a/frontend/test/stubs/legacy-ui.ts b/frontend/test/stubs/legacy-ui.tsnew file mode 100644index 000000000..3c88d29e2--- /dev/null+++ b/frontend/test/stubs/legacy-ui.ts@@ -0,0 +1,18 @@+/* `/js/ui-components.js` 在测试里的替身(vitest.config.ts 里做 alias)。+ *+ * 只保留断言真正依赖的结构标记(`data-geist-empty-state`、`geist-note-error`)。+ * 完整的 Geist 结构由 `tests/test_web_ui.py` 直接对 `web/js/ui-components.js` 断言,+ * 这里再抄一遍只会多一处要维护的副本。 */+export const emptyStateHtml = (+ iconName: string,+ title: string,+ description: string,+): string => `<div class="emptystate" data-geist-empty-state role="status">`+ + `<div class="es-icon" data-icon="${iconName}"></div>`+ + `<div class="es-copy"><h3>${title}</h3><p>${description}</p></div></div>`;++export const noteHtml = (+ message: string,+ options: { variant?: string; label?: string } = {},+): string => `<div class="geist-note geist-note-${options.variant ?? 'secondary'}" role="note">`+ + `<b>${options.label ?? ''}</b><span>${message}</span></div>`;diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.jsnew file mode 100644index 000000000..fe4dfb8c9--- /dev/null+++ b/web/dist/peach-ui.js@@ -0,0 +1,410 @@+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";+//#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 = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, S = Array.isArray;+function C(e, t) {+ for (var n in t) e[n] = t[n];+ return e;+}+function w(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 E(e, t, n, r, i) {+ var a = {+ type: e,+ props: t,+ key: n,+ ref: r,+ __k: null,+ __: null,+ __b: 0,+ __e: null,+ __c: null,+ constructor: void 0,+ __v: i ?? ++s,+ __i: -1,+ __u: 0+ };+ return i == null && o.vnode != null && o.vnode(a), a;+}+function D(e) {+ return e.children;+}+function O(e, t) {+ this.props = e, this.context = t;+}+function k(e, t) {+ if (t == null) return e.__ ? k(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;+}+function A(e) {+ if (e.__P && e.__d) {+ var t = e.__v, n = t.__e, r = [], i = [], a = C({}, t);+ a.__v = t.__v + 1, o.vnode && o.vnode(a), V(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, U(r, a, i), t.__e = t.__ = null, a.__e != n && j(a);+ }+}+function j(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;+ }), j(e);+}+function M(e) {+ (!e.__d && (e.__d = !0) && c.push(e) && !N.__r++ || l != o.debounceRendering) && ((l = o.debounceRendering) || u)(N);+}+function N() {+ try {+ for (var e, t = 1; c.length;) c.length > t && c.sort(d), e = c.shift(), t = c.length, A(e);+ } finally {+ c.length = N.__r = 0;+ }+}+function P(e, t, n, r, i, a, o, s, c, l, u) {+ var d, f, p, m, h, g, _ = r && r.__k || b, v = t.length;+ for (c = F(n, t, _, c, v), d = 0; d < v; d++) (p = n.__k[d]) != null && (f = p.__i != -1 && _[p.__i] || y, p.__i = d, g = V(e, p, f, i, a, o, s, c, l, u), m = p.__e, p.ref && f.ref != p.ref && (f.ref && K(f.ref, null, p), u.push(p.ref, p.__c || m, p)), h == null && m != null && (h = m), 4 & p.__u ? (c = I(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 F(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) : S(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 = L(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)), q(s, s));+ return r;+}+function I(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 = I(r[i], t, n));+ return t;+ }+ e.__e != t && (t && e.type && !t.parentNode && (t = k(e)), t = n.insertBefore(e.__e, t || null));+ do+ t &&= t.nextSibling;+ while (t != null && t.nodeType == 8);+ return t;+}+function L(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) {+ for (i = n - 1, a = n + 1; i >= 0 || a < t.length;) if ((l = t[o = i >= 0 ? i-- : a++]) != null && !(2 & l.__u) && s == l.key && c == l.type) return o;+ }+ return -1;+}+function R(e, t, n) {+ t[0] == "-" ? e.setProperty(t, n ?? "") : e[t] = n == null ? "" : typeof n != "number" || x.test(t) ? n : n + "px";+}+function z(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 || R(e.style, t, "");+ if (n) for (t in n) r && n[t] == r[t] || R(e.style, t, n[t]);+ }+ } else if (t[0] == "o" && t[1] == "n") a = t != (t = t.replace(h, "$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[m] = r[m] : (n[m] = g, e.addEventListener(t, a ? v : _, a)) : e.removeEventListener(t, a ? v : _, 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 {+ e[t] = n ?? "";+ break n;+ } catch {}+ typeof n == "function" || (n == null || !1 === n && t[4] != "-" ? e.removeAttribute(t) : e.setAttribute(t, t == "popover" && n == 1 ? "" : n));+ }+}+function B(e) {+ return function(t) {+ if (this.l) {+ var n = this.l[t.type + e];+ if (t[p] == null) t[p] = g++;+ else if (t[p] < n[m]) return;+ return n(o.event ? o.event(t) : t);+ }+ };+}+function V(e, t, n, r, i, a, s, c, l, u) {+ var d, f, p, m, h, g, _, v, y, x, T, E, A, j, M, N, F = 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);+ n: if (typeof F == "function") {+ f = s.length;+ try {+ if (y = t.props, x = F.prototype && F.prototype.render, T = (d = F.contextType) && r[d.__c], E = d ? T ? T.props.value : d.__ : r, n.__c ? v = (p = t.__c = n.__c).__ = p.__E : (x ? t.__c = p = new F(y, E) : (t.__c = p = new O(y, E), p.constructor = F, p.render = J), T && T.sub(p), p.state || (p.state = {}), p.__n = r, m = p.__d = !0, p.__h = [], p._sb = []), x && p.__s == null && (p.__s = p.state), x && F.getDerivedStateFromProps != null && (p.__s == p.state && (p.__s = C({}, p.__s)), C(p.__s, F.getDerivedStateFromProps(y, p.__s))), h = p.props, g = p.state, p.__v = t, m) x && F.getDerivedStateFromProps == null && p.componentWillMount != null && p.componentWillMount(), x && p.componentDidMount != null && p.__h.push(p.componentDidMount);+ else {+ if (x && F.getDerivedStateFromProps == null && y !== h && p.componentWillReceiveProps != null && p.componentWillReceiveProps(y, E), t.__v == n.__v || !p.__e && p.shouldComponentUpdate != null && !1 === p.shouldComponentUpdate(y, p.__s, E)) {+ 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);+ }), b.push.apply(p.__h, p._sb), p._sb = [], p.__h.length && s.push(p), c = k(n);+ break n;+ }+ p.componentWillUpdate != null && p.componentWillUpdate(y, p.__s, E), x && p.componentDidUpdate != null && p.__h.push(function() {+ p.componentDidUpdate(h, g, _);+ });+ }+ if (p.context = E, p.props = y, p.__P = e, p.__e = !1, A = o.__r, j = 0, x) p.state = p.__s, p.__d = !1, A && A(t), d = p.render(p.props, p.state, p.context), b.push.apply(p.__h, p._sb), p._sb = [];+ else do+ p.__d = !1, A && A(t), d = p.render(p.props, p.state, p.context), p.state = p.__s;+ while (p.__d && ++j < 25);+ p.state = p.__s, p.getChildContext != null && (r = C(C({}, r), p.getChildContext())), x && !m && p.getSnapshotBeforeUpdate != null && (_ = p.getSnapshotBeforeUpdate(h, g)), M = d != null && d.type === D && d.key == null ? W(d.props.children) : d, c = P(e, S(M) ? M : [M], 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);+ } catch (e) {+ if (s.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 (N = a.length; N--;) w(a[N]);+ } else t.__e = n.__e;+ t.__k ??= n.__k || [], e.then || H(t), o.__e(e, t, n);+ }+ } else a == null && t.__v == n.__v ? (t.__k = n.__k, t.__e = n.__e) : c = t.__e = G(n.__e, t, n, r, i, a, s, l, u);+ return (d = o.diffed) && d(t), 128 & t.__u ? void 0 : c;+}+function H(e) {+ e && (e.__c && (e.__c.__e = !0), e.__k && e.__k.some(H));+}+function U(e, t, n) {+ for (var r = 0; r < n.length; r++) K(n[r], n[++r], n[++r]);+ o.__c && o.__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);+ }+ });+}+function W(e) {+ return typeof e != "object" || !e || e.__b > 0 ? e : S(e) ? e.map(W) : e.constructor === void 0 ? C({}, e) : null;+}+function G(e, t, n, r, i, s, c, l, u) {+ var d, f, p, m, h, g, _, v = n.props || y, b = 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;+ break;+ }+ }+ if (e == null) {+ if (x == null) return document.createTextNode(b);+ e = document.createElementNS(i, x, b.is && b), l &&= (o.__m && o.__m(t, s), !1), s = null;+ }+ if (x == null) v === b || l && e.data == b || (e.data = b);+ else {+ if (s = x == "textarea" && b.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 b || d == "value" && "defaultValue" in b || d == "checked" && "defaultChecked" in b || z(e, d, null, h, i);+ for (d in b) h = b[d], d == "children" ? m = h : d == "dangerouslySetInnerHTML" ? f = h : d == "value" ? g = h : d == "checked" ? _ = h : l && typeof h != "function" || v[d] === h || z(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 = ""), P(t.type == "template" ? e.content : e, S(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--;) w(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]) && z(e, d, g, v[d], i), d = "checked", _ != null && _ != e[d] && z(e, d, _, v[d], i));+ }+ return e;+}+function K(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);+ }+}+function q(e, t, n) {+ var r, i;+ if (o.unmount && o.unmount(e), (r = e.ref) && (r.current && r.current != e.__e || K(r, null, t)), (r = e.__c) != null) {+ if (r.componentWillUnmount) try {+ r.componentWillUnmount();+ } catch (e) {+ o.__e(e, t);+ }+ r.base = r.__P = r.__n = null;+ }+ if (r = e.__k) for (i = 0; i < r.length; i++) r[i] && q(r[i], t, n || typeof e.type != "function");+ n || w(e.__e), e.__c = e.__ = e.__e = void 0;+}+function J(e, t, n) {+ return this.constructor(e, n);+}+function Y(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 = [], V(t, e = (!r && n || t).__k = T(D, null, [e]), i || y, y, 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), U(s, e, c), e.props.children = null;+}+a = b.slice, o = { __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, O.prototype.setState = function(e, t) {+ var n = this.__s != null && this.__s != this.state ? this.__s : this.__s = C({}, this.state);+ typeof e == "function" && (e = e(C({}, n), this.props)), e && C(n, e), e != null && this.__v && (t && this._sb.push(t), M(this));+}, O.prototype.forceUpdate = function(e) {+ this.__v && (this.__e = !0, e && this.__h.push(e), M(this));+}, O.prototype.render = D, c = [], u = typeof Promise == "function" ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, d = function(e, t) {+ return e.__v.__b - t.__v.__b;+}, N.__r = 0, f = Math.random().toString(8), p = "__d" + f, m = "__a" + f, h = /(PointerCapture)$|Capture$/i, g = 0, _ = B(!1), v = B(!0);+//#endregion+//#region src/api.ts+var ee = class extends Error {+ status;+ constructor(e, t) {+ super(e), this.name = "ApiError", this.status = t;+ }+}, te = (e) => {+ if (!e || typeof e != "object") return "";+ let t = e;+ for (let e of [+ "message",+ "detail",+ "error"+ ]) {+ let n = t[e];+ if (typeof n == "string" && n) return n;+ }+ return "";+};+async function ne(e, t) {+ let n = await fetch(e, {+ headers: { Accept: "application/json" },+ credentials: "same-origin",+ ...t ? { signal: t } : {}+ }), r = null;+ try {+ r = await n.json();+ } catch {}+ if (!n.ok) throw new ee(te(r) || `请求失败(${n.status})`, n.status);+ return r;+}+//#endregion+//#region node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js+var re = 0;+Array.isArray;+function X(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: --re,+ __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 ie = "/api/quality-goals?limit=200", ae = (e, t) => ne(ie, t), oe = (e) => e.has_cover ? `/cover?code=${encodeURIComponent(e.code ?? "")}` : `/poster?id=${e.id}&c=4`;+function se({ data: a, error: o, openItem: s, javTitleHtml: c, javDisplayName: l, srcBadge: u }) {+ if (o) return /* @__PURE__ */ X("div", {+ class: "qualitylist",+ dangerouslySetInnerHTML: { __html: i(o, {+ variant: "error",+ label: "读取失败"+ }) }+ });+ let d = a?.items ?? [];+ return d.length ? /* @__PURE__ */ X("div", {+ class: "qualitylist",+ children: d.map((r) => /* @__PURE__ */ X("article", {+ class: "qualityitem",+ children: [/* @__PURE__ */ X("button", {+ class: "qualitycover",+ type: "button",+ "aria-label": `打开 ${l(r)}`,+ onClick: () => s(r.id),+ children: /* @__PURE__ */ X("img", {+ src: oe(r),+ alt: "",+ loading: "lazy",+ onError: (e) => e.currentTarget.remove()+ })+ }), /* @__PURE__ */ X("div", { children: [+ /* @__PURE__ */ X("h3", { children: /* @__PURE__ */ X("button", {+ type: "button",+ "data-middle-truncate": !0,+ onClick: () => s(r.id),+ dangerouslySetInnerHTML: { __html: c(r) }+ }) }),+ /* @__PURE__ */ X("p", {+ class: "mono",+ children: [+ /* @__PURE__ */ X("span", {+ style: "display:contents",+ dangerouslySetInnerHTML: { __html: u(r.location, r.cost) }+ }),+ /* @__PURE__ */ X("span", { children: e[r.location] ?? r.location }),+ /* @__PURE__ */ X("span", { children: t(r.duration) }),+ /* @__PURE__ */ X("span", { children: n(r.size ?? 0) })+ ]+ }),+ r.reason ? /* @__PURE__ */ X("p", { children: r.reason }) : null+ ] })]+ }, r.id))+ }) : /* @__PURE__ */ X("div", {+ class: "qualitylist",+ dangerouslySetInnerHTML: { __html: r("sparkles", "没有标记中的高清版目标", "现有版本都已满足条件,或还没有加入追踪。") }+ });+}+//#endregion+//#region src/islands.ts+var Z = { "quality-goals": {+ load: ae,+ component: se+} }, ce = () => Object.keys(Z), Q = /* @__PURE__ */ new Map();+async function le(e, t, n, r = {}) {+ let i = Z[e];+ if (!i) throw Error(`未注册的 island:${String(e)}`);+ $(t);+ let a = {+ controller: new AbortController(),+ painted: !1+ };+ Q.set(t, a);+ let o;+ try {+ o = {+ data: await i.load(n, a.controller.signal),+ error: ""+ };+ } catch (e) {+ if (a.controller.signal.aborted) return;+ o = {+ data: null,+ error: e instanceof Error ? e.message : String(e)+ };+ }+ if (Q.get(t) === a) {+ if (r.isCurrent && !r.isCurrent()) {+ Q.delete(t);+ return;+ }+ t.textContent = "", a.painted = !0, Y(T(i.component, {+ ...n,+ ...o+ }), t);+ }+}+function $(e) {+ let t = Q.get(e);+ t && (t.controller.abort(), Q.delete(e), t.painted && Y(null, e));+}+//#endregion+export { ce as islandNames, le as mountIsland, $ as unmountIsland };