一分钟搭建影视站,支持Docker等部署方式
feat(search,subscription,settings): 搜索历史改下拉、订阅整体开关与一键发布订阅链接、点播源停用分级,版本 2.12.0
bestZwei482dd9468c6d
diff --git a/package.json b/package.jsonindex 09426ec..6b44940 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "libretv",- "version": "2.11.0",+ "version": "2.12.0","private": true,"description": "免费在线视频搜索与观看平台(Next.js 重构版)","license": "AGPL-3.0-or-later",diff --git a/src/app/api/publish/route.test.ts b/src/app/api/publish/route.test.tsnew file mode 100644index 0000000..1fed807--- /dev/null+++ b/src/app/api/publish/route.test.ts@@ -0,0 +1,107 @@+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { POST } from './route';+import { SESSION_COOKIE, signSession } from '@/lib/auth';++/**+ * 发布接口单测:登录守卫、字段白名单与条数上限。+ * 这里只验证「接口不成为任意内容上传通道」,真实上传逻辑由发布器自身测试覆盖。+ */++const state = vi.hoisted(() => ({+ /** 记录传给发布器的文本,用于断言白名单是否生效 */+ publishedText: null as string | null,+ fail: false,+}));++vi.mock('@/lib/source-list-publish', () => ({+ MAX_PUBLISH_BYTES: 256 * 1024,+ publishSourceList: vi.fn(async (text: string) => {+ if (state.fail) throw new Error('发布失败:paste.rs(HTTP 500)');+ state.publishedText = text;+ return { url: 'https://paste.rs/abc123', provider: 'paste.rs' };+ }),+}));++function makeRequest(body: unknown, options?: { authenticated?: boolean }): Request {+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };+ if (options?.authenticated !== false) {+ headers.cookie = `${SESSION_COOKIE}=${signSession().token}`;+ }+ return new Request('https://local.test/api/publish', {+ method: 'POST',+ headers,+ body: typeof body === 'string' ? body : JSON.stringify(body),+ });+}++beforeAll(() => {+ process.env.PASSWORD = 'test-password';+});++beforeEach(() => {+ state.publishedText = null;+ state.fail = false;+});++describe('POST /api/publish', () => {+ it('未登录直接被守卫拦下', async () => {+ const res = await POST(makeRequest({ sources: [] }, { authenticated: false }));+ expect(res.status).toBe(401);+ });++ it('请求体不是合法 JSON 时返回 400', async () => {+ const res = await POST(makeRequest('not json'));+ expect(res.status).toBe(400);+ });++ it('没有任何可用源时返回 400,且不触达粘贴板', async () => {+ const res = await POST(makeRequest({ sources: [], liveSources: [] }));+ expect(res.status).toBe(400);+ expect(state.publishedText).toBeNull();+ });++ it('只透出白名单字段:未知键与非 http 地址一律剔除', async () => {+ const res = await POST(+ makeRequest({+ name: '我的源',+ sources: [+ { name: 'A', url: 'https://a.example.com/api.php/provide/vod', evil: 'should-not-appear' },+ { name: 'B', url: 'file:///etc/passwd' },+ ],+ liveSources: [{ name: 'L', url: 'https://live.example.com/tv.m3u', epg: 'https://epg.example.com/e.xml' }],+ extraTopLevel: { secret: 1 },+ })+ );+ expect(res.status).toBe(200);+ const published = state.publishedText ?? '';+ expect(published).toContain('a.example.com');+ expect(published).toContain('live.example.com/tv.m3u');+ // 非 http 地址、未知字段都不能出现在发布内容里+ expect(published).not.toContain('etc/passwd');+ expect(published).not.toContain('evil');+ expect(published).not.toContain('secret');+ });++ it('成功时返回链接、来源与条数统计', async () => {+ const res = await POST(+ makeRequest({+ sources: [{ name: 'A', url: 'https://a.example.com/api.php/provide/vod' }],+ liveSources: [{ name: 'L', url: 'https://live.example.com/tv.m3u' }],+ })+ );+ expect(res.status).toBe(200);+ await expect(res.json()).resolves.toMatchObject({+ url: 'https://paste.rs/abc123',+ provider: 'paste.rs',+ sources: 1,+ liveSources: 1,+ });+ });++ it('发布器全部失败时返回 502 并透出原因', async () => {+ state.fail = true;+ const res = await POST(makeRequest({ sources: [{ name: 'A', url: 'https://a.example.com/x' }] }));+ expect(res.status).toBe(502);+ await expect(res.json()).resolves.toMatchObject({ error: expect.stringContaining('paste.rs') });+ });+});diff --git a/src/app/api/publish/route.ts b/src/app/api/publish/route.tsnew file mode 100644index 0000000..9d85562--- /dev/null+++ b/src/app/api/publish/route.ts@@ -0,0 +1,103 @@+import { NextResponse } from 'next/server';+import { guardRequest } from '@/lib/api-guard';+import { MAX_LIVE_SOURCES, MAX_VOD_SOURCES } from '@/lib/source-list';+import { MAX_PUBLISH_BYTES, publishSourceList } from '@/lib/source-list-publish';++export const runtime = 'nodejs';++/** 单个字段长度上限:源名与地址再长也不该超过这个量级 */+const MAX_FIELD_LEN = 2048;++interface VodOut {+ name: string;+ url: string;+}++interface LiveOut {+ name: string;+ url: string;+ epg?: string;+}++/**+ * 只抽取已知字段并重新序列化。+ * 本接口的语义是「发布源列表」,不是通用上传通道:白名单式取字段 + 条数上限,+ * 避免它被当作任意内容的中转(服务端会向固定第三方域名 POST,这一点必须守住)。+ */+function normalizePayload(raw: unknown): { name?: string; sources: VodOut[]; liveSources: LiveOut[] } | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const record = raw as Record<string, unknown>;++ const text = (v: unknown, max = MAX_FIELD_LEN) => (typeof v === 'string' ? v.trim().slice(0, max) : '');+ const url = (v: unknown) => {+ const s = text(v);+ return /^https?:\/\//i.test(s) ? s : '';+ };++ const sources = (Array.isArray(record.sources) ? record.sources : [])+ .slice(0, MAX_VOD_SOURCES)+ .map((item) => {+ const o = (item ?? {}) as Record<string, unknown>;+ return { name: text(o.name, 128), url: url(o.url) };+ })+ .filter((s) => s.url);++ const liveSources = (Array.isArray(record.liveSources) ? record.liveSources : [])+ .slice(0, MAX_LIVE_SOURCES)+ .map((item) => {+ const o = (item ?? {}) as Record<string, unknown>;+ const epg = url(o.epg);+ return { name: text(o.name, 128), url: url(o.url), ...(epg ? { epg } : {}) };+ })+ .filter((s) => s.url);++ if (sources.length === 0 && liveSources.length === 0) return null;+ return { name: text(record.name, 64) || undefined, sources, liveSources };+}++/** 把当前源列表发布到第三方粘贴板,返回可直接填入订阅框的 URL */+export async function POST(req: Request) {+ const guarded = guardRequest(req);+ if (guarded) return guarded;++ let raw: unknown;+ try {+ raw = JSON.parse(await req.text());+ } catch {+ return NextResponse.json({ error: '请求内容不是合法 JSON' }, { status: 400 });+ }++ const normalized = normalizePayload(raw);+ if (!normalized) {+ return NextResponse.json({ error: '没有可发布的源(当前没有已勾选启用的点播源或直播源)' }, { status: 400 });+ }++ // 与「导出数据源」保持同一种格式,发布出去的链接可以直接被本站或他人订阅+ const payload = JSON.stringify(+ {+ name: normalized.name ?? 'LibreTV-SourceList',+ version: 2,+ exportedAt: Date.now(),+ sources: normalized.sources,+ liveSources: normalized.liveSources,+ },+ null,+ 2+ );++ if (Buffer.byteLength(payload, 'utf8') > MAX_PUBLISH_BYTES) {+ return NextResponse.json({ error: '源列表体积超出公开粘贴板的限制,无法发布' }, { status: 413 });+ }++ try {+ const { url, provider } = await publishSourceList(payload);+ return NextResponse.json({+ url,+ provider,+ sources: normalized.sources.length,+ liveSources: normalized.liveSources.length,+ });+ } catch (err) {+ return NextResponse.json({ error: err instanceof Error ? err.message : '发布失败' }, { status: 502 });+ }+}diff --git a/src/app/globals.css b/src/app/globals.cssindex c29c310..c4afe96 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -16,9 +16,22 @@--c-line: 224 227 232; /* #e0e3e8 */--c-content: 26 26 26; /* #1a1a1a */--c-muted: 95 99 104; /* #5f6368 */- --c-faint: 138 143 152; /* #8a8f98 */+ --c-faint: 107 114 128; /* #6b7280(原 #8a8f98 对白底仅 3.2:1,加深后达到 AA 4.5:1) */--c-accent: 37 99 235; /* blue-600 */--c-accent-hover: 29 78 216; /* blue-700 */+ --c-on-accent: 255 255 255; /* accent 实心底上的文字色 */+ /* 语义状态色(亮色主题取偏深值,保证浅底上的对比度) */+ --c-danger: 220 38 38; /* red-600 */+ --c-danger-hover: 185 28 28; /* red-700 */+ --c-success: 22 163 74; /* green-600 */+ --c-warning: 217 119 6; /* amber-600 */+ --c-info: 37 99 235; /* blue-600 */+ --c-rating: 245 158 11; /* amber-500 */+ /* 实心状态底色(配白字):比「文字用」色更深一档,保证白字对比度 ≥ 4.5:1 */+ --c-danger-solid: 185 28 28; /* red-700 */+ --c-success-solid: 21 128 61; /* green-700 */+ --c-warning-solid: 180 83 9; /* amber-700 */+ --c-info-solid: 29 78 216; /* blue-700 */color-scheme: light;}@@ -36,6 +49,20 @@--c-faint: 107 127 153; /* #6b7f99 三级文本 */--c-accent: 0 184 230; /* #00b8e6 霓虹蓝主色(--primary-color 调深一档) */--c-accent-hover: 51 214 255; /* #33d6ff 霓虹蓝浅变体(--primary-light) */+ /* 霓虹蓝底亮度过高(对白字仅 2.35:1),暗色下实心底改用深色文字 */+ --c-on-accent: 8 19 31;+ /* 语义状态色(暗色主题取中等明度值,保证深蓝黑底上的对比度) */+ --c-danger: 239 68 68; /* red-500 */+ --c-danger-hover: 248 113 113; /* red-400 */+ --c-success: 34 197 94; /* green-500 */+ --c-warning: 245 158 11; /* amber-500 */+ --c-info: 59 130 246; /* blue-500 */+ --c-rating: 251 191 36; /* amber-400 */+ /* 实心状态底色(配白字):与亮色一致取深档,避免琥珀/绿色底白字对比度不足 */+ --c-danger-solid: 185 28 28; /* red-700 */+ --c-success-solid: 21 128 61; /* green-700 */+ --c-warning-solid: 180 83 9; /* amber-700 */+ --c-info-solid: 29 78 216; /* blue-700 */color-scheme: dark;}@@ -60,18 +87,29 @@ body {}.btn {@apply inline-flex items-center justify-center gap-1.5 rounded-md px-3 py-1.5 text-sm transition-colors disabled:opacity-40 disabled:cursor-not-allowed;+ /* 统一焦点环:键盘用户可见,与 .input 同一规格 */+ @apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40;}.btn-primary {- @apply btn bg-accent text-white hover:bg-accent-hover;+ @apply btn bg-accent text-on-accent hover:bg-accent-hover;}.btn-ghost {@apply btn bg-chip text-muted hover:bg-hover hover:text-content border border-line;}.input {- @apply bg-chip border border-line rounded-md px-3 py-2 text-sm text-content placeholder:text-faint focus:outline-none focus:ring-1 focus:ring-accent focus:border-accent;+ @apply bg-chip border border-line rounded-md px-3 py-2 text-sm text-content placeholder:text-faint;+ @apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 focus-visible:border-accent;}.tag {- @apply inline-block text-xs px-1.5 py-0.5 rounded-full;+ @apply inline-flex items-center text-xs px-1.5 py-0.5 rounded-full;+ }+ /* 小尺寸按钮:定义在 .btn-* 之后,确保尺寸覆盖生效(与 .btn-primary / .btn-ghost 组合使用) */+ .btn-sm {+ @apply btn px-2.5 py-1 text-xs;+ }+ /* 胶囊控件(筛选、分类标签):统一内边距与圆角 */+ .chip {+ @apply inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] transition-colors;}.scrollbar-thin::-webkit-scrollbar {width: 6px;@@ -91,7 +129,8 @@ body {.episode-active {background: rgb(var(--c-accent)) !important;border-color: rgb(var(--c-accent)) !important;- color: #fff;+ /* 暗色下霓虹蓝底对白字对比度不足,统一用 on-accent(亮色白 / 暗色深) */+ color: rgb(var(--c-on-accent)) !important;}/* 品牌渐变字(沿用旧版 LibreTV 的霓虹蓝→霓虹粉) */diff --git a/src/app/live/page.tsx b/src/app/live/page.tsxindex dd0b1d7..7150bb3 100644--- a/src/app/live/page.tsx+++ b/src/app/live/page.tsx@@ -8,6 +8,7 @@ import { Header } from '@/components/header';import { LivePlayer } from '@/components/live-player';import { LiveChannelList, type LiveChannelItem } from '@/components/live-channel-list';import { LiveEpgPanel } from '@/components/live-epg-panel';+import { Spinner } from '@/components/states';import { useAuth } from '@/components/auth';import { allLiveSources, useAppStore } from '@/lib/store';import { buildImageUrl, cn } from '@/lib/utils';@@ -329,10 +330,10 @@ function LiveContent() {<buttonclassName={cn('rounded-md p-2 transition-colors',- isFavorite ? 'text-amber-400' : 'text-muted hover:text-amber-400 hover:bg-hover'+ isFavorite ? 'text-warning' : 'text-muted hover:text-warning hover:bg-hover')}- aria-label="收藏"- title="收藏"+ aria-label={isFavorite ? '取消收藏' : '收藏'}+ title={isFavorite ? '取消收藏' : '收藏'}onClick={() => useAppStore.getState().toggleLiveFavorite(currentChannel.url)}><svg@@ -362,7 +363,7 @@ function LiveContent() {}}>{copied ? (- <span className="text-[10px] text-green-500">已复制</span>+ <span className="text-[10px] text-success">已复制</span>) : (<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path@@ -402,7 +403,7 @@ function LiveContent() {'bg-surface-raised border border-line flex-col overflow-hidden','fixed inset-x-0 bottom-0 z-40 h-[75vh] rounded-t-2xl shadow-2xl',listOpen ? 'flex' : 'hidden',- 'lg:sticky lg:top-20 lg:flex lg:h-[calc(100vh-6.5rem)] lg:rounded-lg lg:shadow-none'+ 'lg:sticky lg:top-20 lg:flex lg:h-[calc(100vh-6.5rem)] lg:rounded-xl lg:shadow-none')}>{/* 抽屉把手栏(仅移动端) */}@@ -421,7 +422,7 @@ function LiveContent() {<div className="flex-1 min-h-0 flex flex-col">{playlistsQuery.isLoading && channels.length === 0 ? (<div className="flex-1 flex items-center justify-center">- <div className="h-9 w-9 rounded-full border-4 border-line border-t-accent animate-spin" />+ <Spinner size="lg" /></div>) : (<LiveChannelList@@ -448,7 +449,7 @@ function LiveContent() {{/* 移动端呼出频道列表的悬浮按钮 */}{!listOpen && channels.length > 0 && (<button- className="fixed bottom-4 right-4 z-30 flex items-center gap-1.5 rounded-full bg-accent px-4 py-2.5 text-sm text-white shadow-lg lg:hidden"+ className="fixed bottom-4 right-4 z-30 flex items-center gap-1.5 rounded-full bg-accent px-4 py-2.5 text-sm text-on-accent shadow-lg lg:hidden"onClick={() => setListOpen(true)}><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">diff --git a/src/app/page.tsx b/src/app/page.tsxindex 07728a7..0c63cb5 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -7,18 +7,23 @@ import { Header } from '@/components/header';import { RecommendSection } from '@/components/douban-section';import { DetailModal } from '@/components/detail-modal';import { AggregatedCard, aggregateResults } from '@/components/video-card';-import { useAppStore, resolveSource, isSourceDisabled, SOURCE_DISABLE_TTL_MS } from '@/lib/store';+import { useAppStore, resolveSource, isInDisabledSubscription, isSourceDisabled } from '@/lib/store';import { api } from '@/lib/client-api';import type { SearchResultItem, SourceSearchOutcome } from '@/lib/types';-import { addSearchHistory, db, removeSearchHistory } from '@/lib/db';-import { cn, validateSourceUrl } from '@/lib/utils';+import { SearchHistoryDropdown, useSearchHistory } from '@/components/search-history';+import { cn, formatDisableTtl, validateSourceUrl } from '@/lib/utils';import { useToast } from '@/components/toast';import { useAuth } from '@/components/auth';+import { EmptyState } from '@/components/states';+import { Icon } from '@/components/icon';/*** 首页:搜索(URL ?s= 驱动,可后退/分享)+ 豆瓣推荐。* 搜索状态由 React Query 管理,失败源在结果区顶部以非阻塞方式展示。*/+/** 搜索结果分批渲染的批大小:一次挂载上千张卡片会明显掉帧 */+const RESULT_PAGE_SIZE = 60;+export default function HomePage() {return (<Suspense>@@ -62,12 +67,19 @@ function HomeContent() {return true;})// 自动停用期内的源不参与搜索(到期自动恢复)- .filter((s) => !isSourceDisabled(store, s.key));+ .filter((s) => !isSourceDisabled(store, s.key))+ // 所属订阅被整体停用的源同样跳过(无损:各源勾选状态保留,重新启用即恢复)+ .filter((s) => !isInDisabledSubscription(store, s.key));}, [store]);const disabledSources = useMemo(() => store.selectedKeys.filter((key) => isSourceDisabled(store, key)),[store]);+ // 来自已关闭订阅的源:勾选状态还在,但本次搜索用不到,必须明确告知+ const offSubscriptionSources = useMemo(+ () => store.selectedKeys.filter((key) => !isSourceDisabled(store, key) && isInDisabledSubscription(store, key)),+ [store]+ );const searchQuery = useQuery({queryKey: ['search', urlQuery, store.selectedKeys, store.yellowFilter],@@ -79,8 +91,13 @@ function HomeContent() {// 逐源结算即更新:结果边搜边渲染,同时滚动健康度onSource: (outcome) => {setStreamedOutcomes((prev) => [...prev, outcome]);- for (const key of store.recordSourceHealth([outcome])) {- toast(`「${sourceName(key)}」连续超时/失败,已临时停用 30 分钟`, 'warning');+ for (const ev of store.recordSourceHealth([outcome])) {+ toast(+ ev.permanent+ ? `「${sourceName(ev.key)}」多次失败,已停止参与搜索,可在设置中恢复`+ : `「${sourceName(ev.key)}」连续超时/失败,已停用 ${formatDisableTtl(ev.ttlMs ?? 0)}`,+ 'warning'+ );}},});@@ -90,10 +107,8 @@ function HomeContent() {staleTime: 300_000,});- const searchHistory = useQuery({- queryKey: ['searchHistory'],- queryFn: () => db.searchHistory.orderBy('timestamp').reverse().limit(10).toArray(),- });+ // 最近搜索改为搜索框下拉(聚焦展开、按输入过滤),不再常驻首屏+ const searchHistory = useSearchHistory(input);const runSearch = (q: string) => {const query = q.trim().slice(0, 100);@@ -107,7 +122,13 @@ function HomeContent() {return;}router.push(`/?s=${encodeURIComponent(query)}`, { scroll: false });- addSearchHistory(query).catch(() => {});+ searchHistory.record(query);+ };++ const pickHistory = (text: string) => {+ setInput(text);+ searchHistory.close();+ runSearch(text);};const isSearching = Boolean(urlQuery) && searchQuery.isFetching && !searchQuery.data;@@ -128,6 +149,11 @@ function HomeContent() {// 跨源同名聚合:同名影片合并为一张卡片,展开后可选择具体来源const groups = useMemo(() => aggregateResults(list), [list]);+ // 分批渲染:新一次搜索(groups 变化)时重置回首批+ const [visibleCount, setVisibleCount] = useState(RESULT_PAGE_SIZE);+ const visibleGroups = useMemo(() => groups.slice(0, visibleCount), [groups, visibleCount]);+ useEffect(() => setVisibleCount(RESULT_PAGE_SIZE), [groups]);+return (<div className="min-h-screen flex flex-col"><Header />@@ -146,77 +172,103 @@ function HomeContent() {)}{/* 搜索区 */}- <section className={cn('flex flex-col items-center', urlQuery ? 'mb-6' : 'mt-10 mb-14')}>+ <section className={cn('flex flex-col items-center', urlQuery ? 'mb-6' : 'mt-8 mb-8')}>{!urlQuery && (<header className="text-center mb-6"><h1 className="text-4xl sm:text-5xl font-bold brand-gradient">LibreTV</h1></header>)}{urlQuery && <h1 className="sr-only">LibreTV 视频搜索</h1>}- <form- className="w-full max-w-2xl flex gap-2"- onSubmit={(e) => {- e.preventDefault();- runSearch(input);- }}- >- <div className="relative flex-1">- <input- ref={inputRef}- className="input w-full h-11 pr-10"- placeholder="输入影片名称..."- value={input}- maxLength={100}- onChange={(e) => setInput(e.target.value)}- aria-label="搜索影片"- />- {input && (- <button- type="button"- className="absolute right-2.5 top-1/2 -translate-y-1/2 text-faint hover:text-content"- onClick={() => {- setInput('');- inputRef.current?.focus();+ {/* 定位容器比胶囊宽一圈:浮层按它的宽度对齐,接缝处不会与胶囊边框错位 1px */}+ <div ref={searchHistory.containerRef} className="relative w-full max-w-2xl">+ <form+ className="w-full"+ onSubmit={(e) => {+ e.preventDefault();+ runSearch(input);+ }}+ >+ {/* 输入框与搜索按钮合并为一个胶囊:内部无边框,焦点态由容器统一表达;+ 下拉展开时改为「上圆下直」并隐去底边,与下方浮层拼成同一个面板 */}+ <div+ className={cn(+ // 12px 圆角矩形(非胶囊):收起态与展开态共用同一组上圆角,+ // 展开时输入框这部分形状完全不发生变化,上下圆角也与下拉保持一致;+ // 右侧与上下不留内边距,由搜索按钮拉伸填满、与搜索框边缘贴合+ 'flex items-stretch min-h-12 pl-4 border',+ 'transition-[background-color,border-color,border-radius] duration-200',+ searchHistory.visible+ ? // 展开时:外框(含上圆角)沿用输入框的聚焦样式不变,只把底边改为内部分隔线,+ // 使输入区在展开状态下仍是边界清晰的独立输入框,而非与列表糊成一片+ 'rounded-t-xl rounded-b-none border-accent border-b-line bg-surface-raised'+ : 'rounded-xl border-line bg-chip focus-within:border-accent focus-within:ring-1 focus-within:ring-accent/40'+ )}+ >+ <input+ ref={inputRef}+ className="flex-1 min-w-0 pr-2 bg-transparent text-sm text-content placeholder:text-faint focus:outline-none"+ placeholder="输入影片名称..."+ value={input}+ maxLength={100}+ onChange={(e) => {+ setInput(e.target.value);+ searchHistory.resetActive();}}- aria-label="清空"- >- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />- </svg>- </button>- )}- </div>- <button type="submit" className="btn-primary h-11 px-5">- 搜索- </button>- </form>-- {/* 最近搜索 */}- {(searchHistory.data?.length ?? 0) > 0 && (- <div className="flex flex-wrap items-center gap-1.5 mt-3 justify-center">- <span className="text-xs text-faint">最近搜索:</span>- {searchHistory.data!.map((h) => (- <span key={h.text} className="inline-flex items-center bg-card rounded-full text-xs">+ onFocus={searchHistory.onFocus}+ onKeyDown={(e) => searchHistory.onKeyDown(e, pickHistory)}+ role="combobox"+ aria-label="搜索影片"+ aria-expanded={searchHistory.visible}+ aria-controls="home-search-history"+ aria-autocomplete="list"+ aria-activedescendant={+ searchHistory.visible && searchHistory.activeIndex >= 0+ ? `home-search-history-${searchHistory.activeIndex}`+ : undefined+ }+ />+ {input && (<button- className="pl-2.5 pr-1 py-1 text-content hover:text-accent"+ type="button"+ className="shrink-0 self-center mr-1 p-1.5 rounded-full text-faint hover:text-content hover:bg-hover transition-colors"onClick={() => {- setInput(h.text);- runSearch(h.text);+ setInput('');+ searchHistory.resetActive();+ inputRef.current?.focus();}}+ aria-label="清空">- {h.text}- </button>- <button- className="pr-2 py-1 text-faint hover:text-red-400"- aria-label={`删除搜索记录 ${h.text}`}- onClick={() => removeSearchHistory(h.text).then(() => searchHistory.refetch())}- >- ✕+ <Icon name="close" className="w-4 h-4" /></button>- </span>- ))}- </div>- )}+ )}+ {/* 主操作按钮:贴合搜索框右端——右侧圆角跟随容器、左侧直角,展开时右下角+ 跟着容器一起改直角;按压改用亮度反馈(缩放会让贴合边缘露出缝隙) */}+ <button+ type="submit"+ className={cn(+ 'btn-primary shrink-0 px-4 font-medium transition-[background-color,filter] active:brightness-90',+ '!rounded-l-none',+ searchHistory.visible ? '!rounded-tr-xl !rounded-br-none' : '!rounded-r-xl'+ )}+ >+ <Icon name="search" className="w-4 h-4" />+ 搜索+ </button>+ </div>+ </form>++ {/* 最近搜索:与输入框无缝拼接;浮层不占文档流,出现/消失不会顶动下方内容 */}+ {searchHistory.visible && (+ <SearchHistoryDropdown+ id="home-search-history"+ matches={searchHistory.matches}+ activeIndex={searchHistory.activeIndex}+ onPick={pickHistory}+ onRemove={searchHistory.remove}+ onClearAll={searchHistory.clearAll}+ />+ )}+ </div></section>{/* 搜索结果 */}@@ -243,7 +295,7 @@ function HomeContent() {<div className="mb-3 text-xs bg-chip rounded-lg px-3 py-2 flex flex-wrap gap-x-3 gap-y-1"><span className="text-faint">{isSearching ? '以下源暂时无响应:' : '部分点播源请求失败:'}</span>{failures.map((f) => (- <span key={f.sourceKey} className={f.timedOut ? 'text-amber-400' : 'text-faint'}>+ <span key={f.sourceKey} className={f.timedOut ? 'text-warning' : 'text-faint'}>{f.timedOut ? '⏱' : '✗'} {sourceName(f.sourceKey)}{f.timedOut ? ' 超时' : ''}</span>@@ -253,35 +305,51 @@ function HomeContent() {{disabledSources.length > 0 && (<div className="mb-3 text-xs text-faint bg-chip rounded-lg px-3 py-2">- {disabledSources.length} 个源因连续超时/失败已临时停用(- {Math.round(SOURCE_DISABLE_TTL_MS / 60000)} 分钟后自动恢复):- {disabledSources.map((key) => sourceName(key)).join('、')}+ {disabledSources.length} 个源因连续超时/失败已暂停参与搜索(临时停用的到期自动恢复,+ 长期停用的需在设置中手动恢复):{disabledSources.map((key) => sourceName(key)).join('、')}+ </div>+ )}++ {offSubscriptionSources.length > 0 && (+ <div className="mb-3 text-xs text-faint bg-chip rounded-lg px-3 py-2">+ {offSubscriptionSources.length} 个源所属的订阅已停用,未参与本次搜索(在设置 → 数据源订阅中可重新启用):+ {offSubscriptionSources.map((key) => sourceName(key)).join('、')}</div>)}{selectedSources.length === 0 ? (<NoSourceGuide hasSources={store.customAPIs.length > 0 || store.envSources.length > 0} />) : list.length > 0 ? (- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 items-start">- {groups.map((group) => (- <AggregatedCard- key={group.key}- group={group}- onOpen={(item) => setDetailItem(item)}- />- ))}- </div>+ <>+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 items-start">+ {visibleGroups.map((group) => (+ <AggregatedCard+ key={group.key}+ group={group}+ onOpen={(item) => setDetailItem(item)}+ />+ ))}+ </div>+ {groups.length > visibleCount && (+ <div className="flex justify-center mt-4">+ <button+ className="btn-ghost btn-sm"+ onClick={() => setVisibleCount((v) => v + RESULT_PAGE_SIZE)}+ >+ 加载更多(还有 {groups.length - visibleCount} 部)+ </button>+ </div>+ )}+ </>) : isSearching ? (<ResultsSkeleton />) : (- <div className="text-center py-16">- <svg className="mx-auto h-10 w-10 text-faint mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}- d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />- </svg>- <h3 className="text-base text-muted">没有找到匹配的结果</h3>- <p className="text-sm text-faint mt-1">请尝试其他关键词或更换点播源</p>- </div>+ <EmptyState+ icon="search"+ title="没有找到匹配的结果"+ description="请尝试其他关键词或更换点播源"+ className="!py-16"+ />)}</section>)}@@ -321,7 +389,15 @@ function ResultsSkeleton() {return (<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">{Array.from({ length: 6 }).map((_, i) => (- <div key={i} className="card h-28 animate-pulse bg-card" />+ // 结构对齐真实结果卡(左侧缩略图 + 右侧文字块),避免占位与真实卡片形状不符+ <div key={i} className="card flex h-28 overflow-hidden">+ <div className="w-[105px] sm:w-[120px] shrink-0 bg-chip animate-pulse" />+ <div className="flex-1 p-2.5 space-y-2">+ <div className="h-4 w-3/4 rounded bg-chip animate-pulse" />+ <div className="h-3 w-1/2 rounded bg-chip animate-pulse" />+ <div className="h-3 w-full rounded bg-chip animate-pulse" />+ </div>+ </div>))}</div>);diff --git a/src/app/watch/page.tsx b/src/app/watch/page.tsxindex f6c3b38..78e8452 100644--- a/src/app/watch/page.tsx+++ b/src/app/watch/page.tsx@@ -6,6 +6,7 @@ import Link from 'next/link';import { useQuery } from '@tanstack/react-query';import { api } from '@/lib/client-api';import { PlayerShell } from '@/components/player-shell';+import { EmptyState, LoadingState, Spinner } from '@/components/states';import { SwitchSourceModal } from '@/components/switch-source';import { useAuth } from '@/components/auth';import { resolveSource, useAppStore } from '@/lib/store';@@ -198,7 +199,7 @@ function WatchContent() {</p></div><div className="ml-auto flex items-center gap-2">- <button className="btn-ghost !py-1.5 text-xs" onClick={() => setSwitchOpen(true)}>+ <button className="btn-ghost btn-sm" onClick={() => setSwitchOpen(true)}>切换资源</button></div>@@ -223,7 +224,7 @@ function WatchContent() {) : (<div className="w-full h-full flex items-center justify-center">{detailQuery.isLoading ? (- <div className="h-9 w-9 rounded-full border-4 border-line border-t-accent animate-spin" />+ <Spinner size="lg" />) : (<p className="text-faint text-sm">{detailQuery.isError ? '视频加载失败,请尝试其他资源' : '无可用播放地址'}@@ -236,20 +237,20 @@ function WatchContent() {{/* 操作栏 */}<div className="flex flex-wrap items-center gap-2 mt-3"><button- className="btn-ghost !py-1.5 text-xs"+ className="btn-ghost btn-sm"disabled={currentIndex <= 0}onClick={() => goEpisode(currentIndex - 1)}>上一集</button><button- className="btn-ghost !py-1.5 text-xs"+ className="btn-ghost btn-sm"disabled={episodes.length === 0 || currentIndex >= episodes.length - 1}onClick={() => goEpisode(currentIndex + 1)}>下一集</button>- <button className="btn-ghost !py-1.5 text-xs" onClick={() => setReversed((v) => !v)}>+ <button className="btn-ghost btn-sm" onClick={() => setReversed((v) => !v)}>{reversed ? '正序排列' : '倒序排列'}</button><label className="flex items-center gap-1.5 text-xs text-muted ml-auto cursor-pointer">@@ -272,9 +273,11 @@ function WatchContent() {</h2></div>{episodes.length === 0 ? (- <p className="text-center text-xs text-faint py-8">- {detailQuery.isLoading ? '加载中...' : detailQuery.isError ? '获取剧集失败' : '暂无剧集信息'}- </p>+ detailQuery.isLoading ? (+ <LoadingState />+ ) : (+ <EmptyState variant="plain" title={detailQuery.isError ? '获取剧集失败' : '暂无剧集信息'} />+ )) : (<div className="grid grid-cols-5 lg:grid-cols-4 gap-1.5 max-h-[65vh] overflow-y-auto scrollbar-thin pr-1">{orderedEpisodes.map((realIndex) => (@@ -318,7 +321,7 @@ function EpisodeButton({ index, active, onClick }: { index: number; active: boolreturn (<buttonref={ref}- className={cn('btn !px-1 text-xs !py-1.5', active ? 'episode-active' : 'btn-ghost')}+ className={cn('btn btn-sm !px-1', active ? 'episode-active' : 'btn-ghost')}onClick={onClick}>{index + 1}diff --git a/src/components/auth.tsx b/src/components/auth.tsxindex 7aaf343..f8837d8 100644--- a/src/components/auth.tsx+++ b/src/components/auth.tsx@@ -2,7 +2,7 @@import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';import { useQueryClient } from '@tanstack/react-query';-import { api, onUnauthorized } from '@/lib/client-api';+import { api, onUnauthorized, STATUS_QUERY_KEY } from '@/lib/client-api';import { useToast } from './toast';/**@@ -46,17 +46,25 @@ export function AuthProvider({ children }: { children: ReactNode }) {const { toast } = useToast();const queryClient = useQueryClient();+ // 与 Providers 共用同一 query key 与缓存,避免 /api/status 被请求两次useEffect(() => {- api- .status()+ let cancelled = false;+ queryClient+ .fetchQuery({ queryKey: STATUS_QUERY_KEY, queryFn: () => api.status() }).then((s) => {+ if (cancelled) return;setVerified(s.verified);setSetupRequired(!s.passwordRequired);setVersion(s.version);setChecked(true);})- .catch(() => setChecked(true));- }, []);+ .catch(() => {+ if (!cancelled) setChecked(true);+ });+ return () => {+ cancelled = true;+ };+ }, [queryClient]);useEffect(() =>@@ -153,7 +161,12 @@ function LoginModal({if (e.target === e.currentTarget) onClose();}}>- <div className="bg-surface-raised rounded-xl p-6 w-full max-w-sm mx-4 shadow-2xl">+ <div+ className="bg-surface-raised rounded-xl p-6 w-full max-w-sm mx-4 shadow-2xl"+ role="dialog"+ aria-modal="true"+ aria-label={setupRequired ? '需要配置密码' : '访问验证'}+ >{setupRequired ? (<><h2 className="text-lg font-semibold text-content mb-3">需要配置密码</h2>@@ -181,7 +194,7 @@ function LoginModal({placeholder="密码"autoComplete="current-password"/>- {error && <p className="mt-2 text-sm text-red-400">{error}</p>}+ {error && <p className="mt-2 text-sm text-danger">{error}</p>}<button type="submit" className="btn-primary w-full mt-4" disabled={loading || !password.trim()}>{loading ? '验证中...' : '进入'}</button>diff --git a/src/components/confirm-dialog.tsx b/src/components/confirm-dialog.tsxindex 11d34fe..361af86 100644--- a/src/components/confirm-dialog.tsx+++ b/src/components/confirm-dialog.tsx@@ -79,7 +79,7 @@ export function ConfirmDialog({ref={confirmRef}className={cn('btn text-sm text-white',- danger ? 'bg-red-500 hover:bg-red-600' : 'bg-accent hover:bg-accent-hover'+ danger ? 'bg-danger hover:bg-danger-hover' : 'bg-accent hover:bg-accent-hover')}onClick={onConfirm}>diff --git a/src/components/detail-modal.tsx b/src/components/detail-modal.tsxindex 8e06c93..6eb19b7 100644--- a/src/components/detail-modal.tsx+++ b/src/components/detail-modal.tsx@@ -9,6 +9,8 @@ import { useAppStore, resolveSource } from '@/lib/store';import { useToast } from './toast';import { cn } from '@/lib/utils';import { addSearchHistory } from '@/lib/db';+import { EmptyState, ErrorState, LoadingState } from './states';+import { useFocusTrap } from './use-focus-trap';/*** 详情弹窗:剧集列表 + 排序 + 复制链接。@@ -25,8 +27,12 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;const [reversed, setReversed] = useState(false);const [posterFailed, setPosterFailed] = useState(false);const abortRef = useRef<AbortController | null>(null);+ const panelRef = useRef<HTMLDivElement>(null);const poster = buildImageUrl(item?.pic, store.imageProxyMode, store.customImageProxy);+ // 打开时把焦点移入弹窗、Tab 圈闭在弹窗内、关闭后归还焦点+ useFocusTrap(Boolean(item), panelRef);+useEffect(() => setPosterFailed(false), [poster]);// 弹窗打开期间锁定背景滚动@@ -124,7 +130,14 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;if (e.target === e.currentTarget) onClose();}}>- <div className="bg-surface-raised rounded-xl w-full max-w-3xl shadow-2xl animate-slide-up" role="dialog" aria-modal>+ <div+ ref={panelRef}+ tabIndex={-1}+ className="bg-surface-raised rounded-xl w-full max-w-3xl shadow-2xl animate-slide-up outline-none"+ role="dialog"+ aria-modal="true"+ aria-label={`${item.name} 详情`}+ ><div className="flex items-start justify-between gap-4 p-5 pb-3 border-b border-line"><div className="min-w-0"><h2 className="text-lg font-semibold text-content break-words">{item.name}</h2>@@ -142,19 +155,9 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;</div><div className="p-5 pt-4">- {loading && (- <div className="flex flex-col items-center py-10 gap-3">- <div className="h-8 w-8 rounded-full border-4 border-line border-t-accent animate-spin" />- <p className="text-sm text-muted">正在获取剧集信息...</p>- </div>- )}+ {loading && <LoadingState label="正在获取剧集信息..." />}- {!loading && error && (- <div className="text-center py-8">- <div className="text-red-400 mb-1.5">❌ 获取失败</div>- <div className="text-sm text-faint">{error}</div>- </div>- )}+ {!loading && error && <ErrorState message={error || '获取失败'} />}{!loading && !error && detail && (<>@@ -172,7 +175,7 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;{metaRows.length > 0 && (<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-1.5 text-sm">{metaRows.map(([k, v]) => (- <div key={k} className="truncate">+ <div key={k} className="truncate" title={`${k}: ${v}`}><span className="text-faint">{k}:</span>{' '}<span className="text-content">{v}</span></div>@@ -190,7 +193,7 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;<div className="flex flex-wrap items-center justify-between gap-2 mb-3"><div className="flex items-center gap-2"><button- className="btn-ghost !py-1.5 text-xs"+ className="btn-ghost btn-sm"onClick={() => setReversed((v) => !v)}aria-label={reversed ? '切换为正序' : '切换为倒序'}>@@ -201,7 +204,7 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;</button><span className="text-sm text-faint">共 {episodes.length} 集</span></div>- <button className="btn-primary !py-1.5 text-xs" onClick={copyLinks}>+ <button className="btn-primary btn-sm" onClick={copyLinks}>复制链接</button></div>@@ -211,7 +214,7 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;return (<buttonkey={realIndex}- className="btn-ghost !px-1 text-center"+ className="btn-ghost btn-sm !px-1 text-center"onClick={() => play(realIndex)}>{realIndex + 1}@@ -221,10 +224,11 @@ export function DetailModal({ item, onClose }: { item: SearchResultItem | null;</div></>) : (- <div className="text-center py-8">- <div className="text-red-400 mb-1.5">❌ 未找到播放资源</div>- <div className="text-sm text-faint">该视频可能暂时无法播放,请尝试其他视频</div>- </div>+ <EmptyState+ icon="alert"+ title="未找到播放资源"+ description="该视频可能暂时无法播放,请尝试其他视频"+ />)}</>)}diff --git a/src/components/douban-section.tsx b/src/components/douban-section.tsxindex 937e5c4..3a0c475 100644--- a/src/components/douban-section.tsx+++ b/src/components/douban-section.tsx@@ -23,11 +23,14 @@ export function RecommendSection({ onPick }: { onPick: (title: string) => void }return <DoubanView onPick={onPick} />;}-/** 豆瓣推荐:影视切换 + 标签筛选 + 分页加载 */+/**+ * 豆瓣推荐:影视切换 + 标签筛选。+ * 一次性渲染全部条目:数据本就一次拉全(50 条),卡片图片又是 lazy 加载,+ * 视口外的图不会请求,因此不需要「加载更多」这类本地切片分页来打断浏览。+ */function DoubanView({ onPick }: { onPick: (title: string) => void }) {const [type, setType] = useState<'movie' | 'tv'>('movie');const [tag, setTag] = useState('热门');- const [visibleCount, setVisibleCount] = useState(25);const query = useQuery({queryKey: ['douban', type, tag],@@ -36,13 +39,11 @@ function DoubanView({ onPick }: { onPick: (title: string) => void }) {const tags = type === 'movie' ? MOVIE_TAGS : TV_TAGS;const items = query.data?.items ?? [];- const shown = items.slice(0, visibleCount);const switchType = (t: 'movie' | 'tv') => {if (t === type) return;setType(t);- setTag(t === 'movie' ? '热门' : '热门');- setVisibleCount(25);+ setTag('热门');};return (@@ -66,12 +67,9 @@ function DoubanView({ onPick }: { onPick: (title: string) => void }) {key={t}className={cn('px-2.5 py-1 rounded-full text-xs transition-colors',- t === tag ? 'bg-accent text-white' : 'bg-chip text-muted hover:text-content hover:bg-hover'+ t === tag ? 'bg-accent text-on-accent' : 'bg-chip text-muted hover:text-content hover:bg-hover')}- onClick={() => {- setTag(t);- setVisibleCount(25);- }}+ onClick={() => setTag(t)}>{t}</button>@@ -82,27 +80,21 @@ function DoubanView({ onPick }: { onPick: (title: string) => void }) {<p className="text-center text-sm text-faint py-8">推荐内容加载失败,可稍后重试或在设置中关闭</p>) : query.isLoading ? (<GridSkeleton />+ ) : items.length === 0 ? (+ <p className="text-center text-sm text-faint py-8">该分类暂无推荐内容</p>) : (- <>- <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2.5">- {shown.map((item) => (- <DoubanCard key={item.id} item={item} onClick={() => onPick(item.title)} />- ))}- </div>- {visibleCount < items.length && (- <div className="text-center mt-4">- <button className="btn-ghost" onClick={() => setVisibleCount((v) => v + 25)}>- 加载更多- </button>- </div>- )}- </>+ <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2.5">+ {items.map((item) => (+ <DoubanCard key={item.id} item={item} onClick={() => onPick(item.title)} />+ ))}+ </div>)}</section>);}-/** Bangumi 每日放送:星期筛选,一次拉全量无分页 */function BangumiView({ onPick }: { onPick: (title: string) => void }) {+/** Bangumi 每日放送:星期筛选,一次拉全量无分页 */+function BangumiView({ onPick }: { onPick: (title: string) => void }) {const [weekday, setWeekday] = useState<number | 'all'>('all');const query = useQuery({@@ -208,7 +200,7 @@ function ChipButton({ active, onClick, children }: { active: boolean; onClick: (<buttonclassName={cn('px-2.5 py-1 rounded-full text-xs transition-colors',- active ? 'bg-accent text-white' : 'bg-chip text-muted hover:text-content hover:bg-hover'+ active ? 'bg-accent text-on-accent' : 'bg-chip text-muted hover:text-content hover:bg-hover')}onClick={onClick}>@@ -220,7 +212,7 @@ function ChipButton({ active, onClick, children }: { active: boolean; onClick: (function TypeButton({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {return (<button- className={cn('px-3.5 py-1.5 rounded-md text-sm transition-colors', active ? 'bg-accent text-white' : 'text-muted hover:text-content')}+ className={cn('px-3.5 py-1.5 rounded-md text-sm transition-colors', active ? 'bg-accent text-on-accent' : 'text-muted hover:text-content')}onClick={onClick}aria-pressed={active}>diff --git a/src/components/drawer.tsx b/src/components/drawer.tsxindex a2be510..3f12bc7 100644--- a/src/components/drawer.tsx+++ b/src/components/drawer.tsx@@ -154,7 +154,7 @@ export function Drawer({entered ? 'translate-x-0' : 'translate-x-full')}>- <div className="shrink-0 px-4 py-3.5 border-b border-line flex items-center justify-between">+ <div className="shrink-0 px-4 py-2.5 border-b border-line flex items-center justify-between"><h2 className="font-semibold text-content">{title}</h2><buttonclassName="p-1.5 rounded-md text-muted hover:text-content hover:bg-hover transition-colors"diff --git a/src/components/header.tsx b/src/components/header.tsxindex 02d1d86..3d9a2a9 100644--- a/src/components/header.tsx+++ b/src/components/header.tsx@@ -7,6 +7,7 @@ import { ThemeToggle } from './theme';import { SourceManagerDrawer } from './source-manager';import { HistoryPanel } from './history-panel';import { Icon } from './icon';+import { SearchHistoryDropdown, useSearchHistory } from './search-history';import { cn } from '@/lib/utils';/** 顶部导航:Logo、搜索框(首页外)、历史、设置 */@@ -16,6 +17,22 @@ export function Header({ showSearch = false }: { showSearch?: boolean }) {const [settingsOpen, setSettingsOpen] = useState(false);const [historyOpen, setHistoryOpen] = useState(false);const [query, setQuery] = useState('');+ // 与首页搜索框共用同一套「最近搜索」下拉逻辑+ const searchHistory = useSearchHistory(query);++ const submitSearch = (text: string) => {+ const q = text.trim().slice(0, 100);+ if (!q) return;+ searchHistory.close();+ router.push(`/?s=${encodeURIComponent(q)}`, { scroll: false });+ // 顶栏搜索一并写入最近搜索(此前只有首页会记录)+ searchHistory.record(q);+ };++ const pickHistory = (text: string) => {+ setQuery(text);+ submitSearch(text);+ };return (<>@@ -31,16 +48,48 @@ export function Header({ showSearch = false }: { showSearch?: boolean }) {className="flex-1 max-w-xl hidden sm:block"onSubmit={(e) => {e.preventDefault();- if (query.trim()) router.push(`/?s=${encodeURIComponent(query.trim())}`);+ submitSearch(query);}}>- <input- className="input w-full h-9"- placeholder="搜索影片..."- value={query}- maxLength={100}- onChange={(e) => setQuery(e.target.value)}- />+ <div ref={searchHistory.containerRef} className="relative">+ <input+ className={cn(+ 'input w-full h-9',+ // 展开时:上圆角与外框沿用聚焦样式,底边改为内部分隔线,与下拉拼成同一面板+ searchHistory.visible &&+ 'rounded-b-none border-accent border-b-line bg-surface-raised focus-visible:ring-0'+ )}+ aria-label="搜索影片"+ placeholder="搜索影片..."+ value={query}+ maxLength={100}+ onChange={(e) => {+ setQuery(e.target.value);+ searchHistory.resetActive();+ }}+ onFocus={searchHistory.onFocus}+ onKeyDown={(e) => searchHistory.onKeyDown(e, pickHistory)}+ role="combobox"+ aria-expanded={searchHistory.visible}+ aria-controls="header-search-history"+ aria-autocomplete="list"+ aria-activedescendant={+ searchHistory.visible && searchHistory.activeIndex >= 0+ ? `header-search-history-${searchHistory.activeIndex}`+ : undefined+ }+ />+ {searchHistory.visible && (+ <SearchHistoryDropdown+ id="header-search-history"+ matches={searchHistory.matches}+ activeIndex={searchHistory.activeIndex}+ onPick={pickHistory}+ onRemove={searchHistory.remove}+ onClearAll={searchHistory.clearAll}+ />+ )}+ </div></form>)}diff --git a/src/components/history-panel.tsx b/src/components/history-panel.tsxindex 7cbab5e..7c92a67 100644--- a/src/components/history-panel.tsx+++ b/src/components/history-panel.tsx@@ -5,6 +5,7 @@ import { useLiveQuery } from 'dexie-react-hooks';import Link from 'next/link';import { Drawer } from './drawer';import { ConfirmDialog } from './confirm-dialog';+import { EmptyState, LoadingState } from './states';import { db, clearAllHistory, removeHistory, upsertHistory, type HistoryEntry } from '@/lib/db';import { buildWatchUrl, buildImageUrl, cn, formatRelativeTime, formatTime } from '@/lib/utils';import { useToast } from './toast';@@ -24,14 +25,14 @@ export function HistoryPanel({ open, onClose }: { open: boolean; onClose: () =>return (<Drawer open={open} onClose={onClose} title="观看历史" width="max-w-lg">{!history ? (- <p className="text-center text-faint py-8 text-sm">加载中...</p>+ <LoadingState />) : history.length === 0 ? (- <p className="text-center text-faint py-8 text-sm">暂无观看记录</p>+ <EmptyState variant="plain" title="暂无观看记录" />) : (<><div className="flex justify-end mb-2"><button- className="text-xs text-faint hover:text-red-400 transition-colors"+ className="text-xs text-faint hover:text-danger transition-colors"onClick={() => setConfirmClear(true)}>清空历史@@ -63,10 +64,15 @@ export function HistoryPanel({ open, onClose }: { open: boolean; onClose: () =>}function HistoryItem({ item }: { item: HistoryEntry }) {- const store = useAppStore();+ // 精确订阅:整份 useAppStore() 会让每条历史在任意 store 变化(搜索健康度、测活写回等)时重渲染+ const imageProxyMode = useAppStore((s) => s.imageProxyMode);+ const customImageProxy = useAppStore((s) => s.customImageProxy);+ const customAPIs = useAppStore((s) => s.customAPIs);+ const envSources = useAppStore((s) => s.envSources);const { toast } = useToast();const [imgFailed, setImgFailed] = useState(false);- const pic = buildImageUrl(item.pic, store.imageProxyMode, store.customImageProxy);+ const source = resolveSource({ customAPIs, envSources }, item.sourceKey);+ const pic = buildImageUrl(item.pic, imageProxyMode, customImageProxy);const hasPercent =item.playbackPosition > 10 && item.duration > 0 && item.playbackPosition < item.duration * 0.95;@@ -77,8 +83,8 @@ function HistoryItem({ item }: { item: HistoryEntry }) {vodId: item.vodId,index: item.episodeIndex,title: item.title,- sourceUrl: resolveSource(store, item.sourceKey)?.url,- detail: resolveSource(store, item.sourceKey)?.detail,+ sourceUrl: source?.url,+ detail: source?.detail,});const remove = () => {@@ -150,7 +156,7 @@ function HistoryItem({ item }: { item: HistoryEntry }) {</Link><buttonclassName={cn(- 'absolute right-2 top-2 p-1.5 rounded-full text-faint hover:text-red-400',+ 'absolute right-2 top-2 p-2 rounded-full text-faint hover:text-danger','opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity')}aria-label="删除记录"diff --git a/src/components/live-channel-list.tsx b/src/components/live-channel-list.tsxindex 3aa1d3d..eccc8f6 100644--- a/src/components/live-channel-list.tsx+++ b/src/components/live-channel-list.tsx@@ -15,6 +15,7 @@ import {} from '@/lib/live-channel-filter';import { useLiveProbe, type ProbeResult } from './use-live-probe';import type { LiveChannel } from '@/lib/types';+import { EmptyState } from './states';/*** 直播频道侧栏:全部/收藏/最近三个视图 + 分组横向标签条 + 关键字搜索 + 排序。@@ -269,7 +270,7 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect, onFilt{/* 测活 + 可用性筛选工具条 */}<div className="flex items-center gap-1.5 px-3 pb-2 shrink-0 flex-wrap"><button- className="btn-ghost !py-1 !px-2 text-xs"+ className="btn-ghost btn-sm"disabled={isProbing || filtered.length === 0}onClick={() => void probe(filtered)}title="探测当前列表频道是否可播(分片级校验;量大时自动分批排队跑完,结果 6 小时内有效)"@@ -279,7 +280,7 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect, onFilt{/* 同一操作位按时机切换:测活中=取消(保留已完成结果);空闲且有结果=清除全部 */}{isProbing ? (<button- className="btn-ghost !py-1 !px-2 text-xs"+ className="btn-ghost btn-sm"onClick={cancelProbe}title="中止本次测活,已完成的结果会保留">@@ -288,7 +289,7 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect, onFilt) : (probeResults.size > 0 && (<button- className="btn-ghost !py-1 !px-2 text-xs"+ className="btn-ghost btn-sm"onClick={() => {clearProbe();setAliveFilter('off');@@ -313,7 +314,7 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect, onFiltclassName={cn('shrink-0 px-2 py-0.5 rounded-full text-[10px] whitespace-nowrap transition-colors border',aliveFilter === 'green'- ? 'bg-accent text-white border-accent'+ ? 'bg-accent text-on-accent border-accent': 'bg-chip text-muted border-line hover:text-content hover:bg-hover')}onClick={() => setAliveFilter((v) => (v === 'green' ? 'off' : 'green'))}@@ -325,7 +326,7 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect, onFiltclassName={cn('shrink-0 px-2 py-0.5 rounded-full text-[10px] whitespace-nowrap transition-colors border',aliveFilter === 'ok'- ? 'bg-accent text-white border-accent'+ ? 'bg-accent text-on-accent border-accent': 'bg-chip text-muted border-line hover:text-content hover:bg-hover')}onClick={() => setAliveFilter((v) => (v === 'ok' ? 'off' : 'ok'))}@@ -355,20 +356,24 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect, onFiltdata-channel-listtabIndex={0}onKeyDown={onListKeyDown}- className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-2 pb-2 focus:outline-none"+ className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-2 pb-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/40">{filtered.length === 0 ? (- <p className="text-center text-xs text-faint py-10">- {view === 'fav'- ? '暂无收藏频道,点击频道右侧星标即可收藏'- : view === 'recent'- ? '暂无观看记录'- : channels.length === 0- ? '暂无频道,请先在设置中添加直播源'- : aliveFilter !== 'off' && probeResults.size > 0- ? '没有匹配该可用性的频道,可放宽或清除筛选'- : '没有匹配的频道'}- </p>+ <EmptyState+ variant="plain"+ className="!py-10"+ title={+ view === 'fav'+ ? '暂无收藏频道,点击频道右侧星标即可收藏'+ : view === 'recent'+ ? '暂无观看记录'+ : channels.length === 0+ ? '暂无频道,请先在设置中添加直播源'+ : aliveFilter !== 'off' && probeResults.size > 0+ ? '没有匹配该可用性的频道,可放宽或清除筛选'+ : '没有匹配的频道'+ }+ />) : (<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>{virtualizer.getVirtualItems().map((vi) => (@@ -415,7 +420,7 @@ function GroupChip({ label, active, onClick }: { label: string; active: boolean;className={cn('shrink-0 px-2.5 py-1 rounded-full text-xs whitespace-nowrap transition-colors border',active- ? 'bg-accent text-white border-accent'+ ? 'bg-accent text-on-accent border-accent': 'bg-chip text-muted border-line hover:text-content hover:bg-hover')}onClick={onClick}@@ -452,7 +457,7 @@ const ChannelRow = memo(function ChannelRow({// 状态点语义:绿=分片级验证且吞吐达标;琥珀=限速/弱验证(直链/清单级)或超时;红=不可达const weakLevel = probe?.ok && probe.level !== 'segment';const amber = Boolean(probe && (weakLevel || (!probe.ok && probe.timedOut) || slow));- const dotClass = amber ? 'bg-amber-400' : probe?.ok ? 'bg-green-500' : 'bg-red-400';+ const dotClass = amber ? 'bg-warning' : probe?.ok ? 'bg-success' : 'bg-danger';const levelText =probe?.level === 'segment'? '分片可用'@@ -475,9 +480,9 @@ const ChannelRow = memo(function ChannelRow({return (<div data-url={channel.url}>+ {/* 不用 role="button":行内含收藏/删除等真实按钮,嵌套 button 角色语义非法;+ 键盘操作由外层列表容器的 ↑↓ 导航提供 */}<div- role="button"- tabIndex={-1}className={cn('group flex items-center gap-2.5 px-2 py-2 rounded-md cursor-pointer transition-colors relative',active ? 'bg-accent/10' : 'hover:bg-hover',@@ -522,7 +527,7 @@ const ChannelRow = memo(function ChannelRow({</span>{isHevc && (<span- className="shrink-0 rounded bg-amber-500/15 px-1 text-[9px] font-medium text-amber-500"+ className="shrink-0 rounded-full bg-warning/15 px-1.5 text-[10px] font-medium text-warning"title="H.265 编码:测活通过但 Chromium 内核通常无法解码,建议用 Edge/Safari">H.265@@ -538,7 +543,7 @@ const ChannelRow = memo(function ChannelRow({<buttonclassName={cn('shrink-0 p-1 rounded transition-colors',- 'text-faint/60 opacity-60 lg:opacity-0 lg:group-hover:opacity-100 hover:text-red-400'+ 'text-faint/60 opacity-60 lg:opacity-0 lg:group-hover:opacity-100 hover:text-danger')}aria-label="删除该观看记录"title="删除该观看记录"@@ -557,8 +562,8 @@ const ChannelRow = memo(function ChannelRow({className={cn('shrink-0 p-1 rounded transition-transform active:scale-125',isFav- ? 'text-amber-400'- : 'text-faint/60 opacity-60 lg:opacity-0 lg:group-hover:opacity-100 hover:text-amber-400'+ ? 'text-warning'+ : 'text-faint/60 opacity-60 lg:opacity-0 lg:group-hover:opacity-100 hover:text-warning')}aria-label={isFav ? '取消收藏' : '收藏'}title={isFav ? '取消收藏' : '收藏'}diff --git a/src/components/live-epg-panel.tsx b/src/components/live-epg-panel.tsxindex 1a2e8ba..24b329c 100644--- a/src/components/live-epg-panel.tsx+++ b/src/components/live-epg-panel.tsx@@ -5,6 +5,7 @@ import { useQuery } from '@tanstack/react-query';import { api } from '@/lib/client-api';import { cn } from '@/lib/utils';import type { EpgProgram } from '@/lib/types';+import { EmptyState, ErrorState, Spinner } from './states';/*** EPG 节目单面板:当前节目(含播放进度条)+ 接下来节目列表 + 简介展开。@@ -38,29 +39,24 @@ export function LiveEpgPanel({ epgUrl, tvgId }: { epgUrl?: string; tvgId?: strinif (!enabled) {return (- <p className="text-center text-xs text-faint py-4">- 该频道未配置节目单数据(需来源订阅提供 EPG 地址且频道带 tvg-id)- </p>+ <EmptyState+ variant="plain"+ title="该频道未配置节目单数据(需来源订阅提供 EPG 地址且频道带 tvg-id)"+ className="!py-4"+ />);}if (epgQuery.isLoading) {return (<div className="flex items-center justify-center py-6">- <div className="h-5 w-5 rounded-full border-[3px] border-line border-t-accent animate-spin" />+ <Spinner size="sm" /></div>);}if (epgQuery.isError) {- return (- <div className="text-center py-4">- <p className="text-xs text-faint mb-1.5">节目单加载失败</p>- <button className="btn-ghost !py-1 text-xs" onClick={() => epgQuery.refetch()}>- 重试- </button>- </div>- );+ return <ErrorState message="节目单加载失败" onRetry={() => epgQuery.refetch()} className="!py-4" />;}const data = epgQuery.data;@@ -74,7 +70,7 @@ export function LiveEpgPanel({ epgUrl, tvgId }: { epgUrl?: string; tvgId?: strin{current ? (<div className="bg-card border border-line rounded-lg p-3"><div className="flex items-center gap-2 mb-1.5">- <span className="text-[10px] font-semibold text-red-500 bg-red-500/10 px-1.5 py-0.5 rounded">+ <span className="text-[10px] font-semibold text-danger bg-danger/10 px-1.5 py-0.5 rounded-full">正在播出</span><span className="text-[10px] text-faint">@@ -82,7 +78,8 @@ export function LiveEpgPanel({ epgUrl, tvgId }: { epgUrl?: string; tvgId?: strin</span></div><button- className="text-sm font-medium text-content text-left w-full text-left"+ className="text-sm font-medium text-content w-full text-left"+ aria-expanded={expandedDesc}onClick={() => setExpandedDesc((v) => !v)}>{current.title}diff --git a/src/components/live-player.tsx b/src/components/live-player.tsxindex 6295706..5e1cfb5 100644--- a/src/components/live-player.tsx+++ b/src/components/live-player.tsx@@ -3,6 +3,7 @@import { useEffect, useRef, useState } from 'react';import Artplayer from 'artplayer';import Hls, { type HlsConfig } from 'hls.js';+import { Spinner } from './states';/*** 直播播放器:与点播 player-shell 完全独立。@@ -397,12 +398,12 @@ export function LivePlayer({ url, title, onPrevChannel, onNextChannel }: LivePla)}{loading && !error && (<div className="absolute inset-0 flex items-center justify-center bg-black/40 pointer-events-none">- <div className="h-9 w-9 rounded-full border-4 border-white/20 border-t-white animate-spin" />+ <Spinner size="lg" tone="onDark" /></div>)}{error && (<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-black/80">- <p className="text-red-400 text-sm px-4 text-center">{error}</p>+ <p className="text-danger text-sm px-4 text-center">{error}</p><buttonclassName="btn-ghost text-xs !bg-white/10 !text-white !border-white/20"onClick={() => {diff --git a/src/components/live-source-manager.tsx b/src/components/live-source-manager.tsxindex 472a1b1..bc299af 100644--- a/src/components/live-source-manager.tsx+++ b/src/components/live-source-manager.tsx@@ -5,7 +5,8 @@ import { useAppStore } from '@/lib/store';import { useToast } from './toast';import { api } from '@/lib/client-api';import { formatRelativeTime, hostnameOf, validateSourceUrl, cn } from '@/lib/utils';-import { EmptyState, SearchInput, SectionTitle, TestBadge, useSourceTests } from './settings-shared';+import { SearchInput, SectionTitle, TestBadge, useSourceTests } from './settings-shared';+import { EmptyState } from './states';import { Icon } from './icon';/**@@ -112,7 +113,7 @@ export function LiveSourceManager() {title="直播源"hint={empty ? 'M3U 订阅 · /live 页面播放' : `共 ${store.liveEnvSources.length + store.liveSubscriptions.length} 个 · 已启用 ${store.liveSelectedUrls.length}`}extra={- <button className="btn-primary !py-1 !px-2.5 text-xs" onClick={() => setAdding(true)}>+ <button className="btn-primary btn-sm" onClick={() => setAdding(true)}><Icon name="plus" className="w-3.5 h-3.5" />添加直播源</button>@@ -146,7 +147,7 @@ export function LiveSourceManager() {title="还没有添加任何直播源"description="添加 M3U 地址后即可在「直播」页按分组浏览与播放频道;也可在「数据源订阅」中一次导入点播源与直播源;部署者还可通过 DEFAULT_LIVE_SOURCES 环境变量预置。"action={- <button className="btn-primary text-xs" onClick={() => setAdding(true)}>+ <button className="btn-primary btn-sm" onClick={() => setAdding(true)}>添加第一个直播源</button>}@@ -160,7 +161,7 @@ export function LiveSourceManager() {<buttonkey={f.id}className={cn(- 'px-2 py-0.5 rounded-full text-[11px] transition-colors',+ 'chip',filter === f.id ? 'bg-accent/10 text-accent font-medium' : 'text-muted hover:text-content hover:bg-hover')}onClick={() => setFilter(f.id)}@@ -171,24 +172,31 @@ export function LiveSourceManager() {))}<span className="ml-auto text-[11px] text-faint">显示 {rows.length} 个</span></div>- <button className="btn-ghost !py-1 !px-2 text-[11px]" onClick={toggleAll} disabled={rows.length === 0}>+ <button className="btn-ghost btn-sm" onClick={toggleAll} disabled={rows.length === 0}>{allEnabled ? '全部停用' : '全部启用'}</button></div>{rows.length === 0 ? (- <p className="text-xs text-faint py-6 text-center">没有符合条件的源</p>+ <EmptyState variant="plain" title="没有符合条件的源" />) : (<ul className="space-y-2">{rows.map((row) => {const enabled = store.liveSelectedUrls.includes(row.url);const fromSubscription = row.fromSubscriptions.length > 0;return (- <li key={row.url} className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">+ <li+ key={row.url}+ className={cn(+ 'bg-card rounded-lg p-3 transition-colors hover:bg-hover/50',+ // 未勾选 = 不参与直播列表:淡显,与点播源面板保持同一套停用观感+ !enabled && 'opacity-70'+ )}+ ><div className="flex items-center gap-2"><inputtype="checkbox"- className="h-4 w-4 accent-[#2563eb] shrink-0"+ className="h-4 w-4 accent-accent shrink-0"checked={enabled}onChange={() => useAppStore.getState().toggleLiveSelected(row.url)}aria-label={enabled ? `停用 ${row.label}` : `启用 ${row.label}`}@@ -262,7 +270,7 @@ export function LiveSourceManager() {<Icon name="edit" className="w-4 h-4" /></button><button- className="rounded-md p-2 text-muted transition-colors hover:bg-hover hover:text-red-400 shrink-0"+ className="rounded-md p-2 text-muted transition-colors hover:bg-hover hover:text-danger shrink-0"onClick={() => removeWithUndo(row)}aria-label="删除直播源"title="移除(可在提示中撤销)"@@ -328,6 +336,7 @@ function LiveSourceForm({<div className="space-y-2 border border-line rounded-lg p-3 bg-chip mb-2"><inputclassName="input w-full disabled:opacity-60"+ aria-label="M3U 订阅地址"placeholder="M3U 订阅地址,如 https://example.com/list.m3u"value={url}maxLength={500}@@ -337,6 +346,7 @@ function LiveSourceForm({/><inputclassName="input w-full"+ aria-label="直播源名称(可选)"placeholder="名称(可选),如 我的频道列表"value={name}maxLength={50}@@ -344,16 +354,17 @@ function LiveSourceForm({/><inputclassName="input w-full"+ aria-label="EPG 节目单地址(可选)"placeholder="EPG 节目单地址(可选,XMLTV xml/xml.gz)"value={epg}maxLength={500}onChange={(e) => setEpg(e.target.value)}/><div className="flex gap-2 justify-end">- <button className="btn-ghost !py-1 text-xs" onClick={onCancel}>+ <button className="btn-ghost btn-sm" onClick={onCancel}>取消</button>- <button className="btn-primary !py-1 text-xs" onClick={submit}>+ <button className="btn-primary btn-sm" onClick={submit}>添加</button></div>diff --git a/src/components/player-shell.tsx b/src/components/player-shell.tsxindex 5585907..05ba73e 100644--- a/src/components/player-shell.tsx+++ b/src/components/player-shell.tsx@@ -231,7 +231,8 @@ export function PlayerShell({// —— 键盘快捷键(旧版 hotkey:false + 自定义逻辑的移植) ——const shortcuts = (e: KeyboardEvent) => {const target = e.target as HTMLElement;- if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') return;+ // 输入框或按钮获得焦点时不劫持按键:否则空格会吞掉按钮的默认激活+ if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.closest('button')) return;const current = artRef.current;if (!current) return;if (e.altKey && e.key === 'ArrowLeft') { e.preventDefault(); return; } // 由父层处理集数切换@@ -342,7 +343,7 @@ export function PlayerShell({)}{error && (<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-black/80">- <p className="text-red-400 text-sm">{error}</p>+ <p className="text-danger text-sm">{error}</p><button className="btn-ghost text-xs" onClick={() => location.reload()}>重新加载</button>diff --git a/src/components/providers.tsx b/src/components/providers.tsxindex 5fc4121..877d66d 100644--- a/src/components/providers.tsx+++ b/src/components/providers.tsx@@ -6,6 +6,7 @@ import { ToastProvider } from './toast';import { AuthProvider } from './auth';import { ThemeProvider } from './theme';import { useAppStore, hydrateLiveProbeResults } from '@/lib/store';+import { api, STATUS_QUERY_KEY } from '@/lib/client-api';import { syncEnvSubscriptions } from '@/lib/subscription-sync';export function Providers({ children }: { children: ReactNode }) {@@ -29,9 +30,9 @@ export function Providers({ children }: { children: ReactNode }) {// 与下方 /api/status 拉取互不依赖,失败静默void hydrateLiveProbeResults();// 拉取部署者通过 DEFAULT_SOURCES / DEFAULT_LIVE_SOURCES 预置的源(失败时静默忽略)- return fetch('/api/status');+ // 与 AuthProvider 共用同一 query key,/api/status 全站只发一次+ return queryClient.fetchQuery({ queryKey: STATUS_QUERY_KEY, queryFn: () => api.status() });})- .then((r) => (r && r.ok ? r.json() : null)).then((d) => {if (d && Array.isArray(d.defaultSources)) {useAppStore.getState().setEnvSources(d.defaultSources);@@ -45,7 +46,7 @@ export function Providers({ children }: { children: ReactNode }) {}}).catch(() => {});- }, []);+ }, [queryClient]);return (<QueryClientProvider client={queryClient}>diff --git a/src/components/search-history.tsx b/src/components/search-history.tsxnew file mode 100644index 0000000..e4967d0--- /dev/null+++ b/src/components/search-history.tsx@@ -0,0 +1,200 @@+'use client';++import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';+import { useQuery } from '@tanstack/react-query';+import { addSearchHistory, clearSearchHistory, db, removeSearchHistory, restoreSearchHistory } from '@/lib/db';+import { cn } from '@/lib/utils';+import { useToast } from './toast';+import { Icon } from './icon';++/** 下拉最多展示条数,与 db 层 MAX_SEARCH_HISTORY 保持一致 */+const HISTORY_LIMIT = 10;++/**+ * 「最近搜索」下拉的交互逻辑:聚焦展开、输入时按关键字过滤(浏览器地址栏式交互)。+ * 首页搜索框与顶栏搜索框共用本 hook 与下方 SearchHistoryDropdown,避免两处实现分叉。+ */+export function useSearchHistory(input: string) {+ const { toast } = useToast();+ const [open, setOpen] = useState(false);+ /** 键盘高亮项下标,-1 表示未选中 */+ const [activeIndex, setActiveIndex] = useState(-1);+ const containerRef = useRef<HTMLDivElement>(null);++ const history = useQuery({+ queryKey: ['searchHistory'],+ queryFn: () => db.searchHistory.orderBy('timestamp').reverse().limit(HISTORY_LIMIT).toArray(),+ });++ const matches = useMemo(() => {+ const all = history.data ?? [];+ const keyword = input.trim().toLowerCase();+ return keyword ? all.filter((h) => h.text.toLowerCase().includes(keyword)) : all;+ }, [history.data, input]);++ // 唯一命中项与输入内容完全一致时不展开:否则会盖住用户刚敲进去的内容+ const visible = open && matches.length > 0 && !(matches.length === 1 && matches[0].text === input.trim());++ // 点按下拉之外的任意位置收起+ useEffect(() => {+ if (!visible) return;+ const onPointerDown = (e: PointerEvent) => {+ if (!containerRef.current?.contains(e.target as Node)) setOpen(false);+ };+ document.addEventListener('pointerdown', onPointerDown);+ return () => document.removeEventListener('pointerdown', onPointerDown);+ }, [visible]);++ const close = () => {+ setOpen(false);+ setActiveIndex(-1);+ };++ /** 记录一次搜索;顺带刷新下拉数据(历史也会在播放页被写入) */+ const record = (text: string) => {+ addSearchHistory(text)+ .then(() => history.refetch())+ .catch(() => {});+ };++ const remove = (text: string) => {+ setActiveIndex(-1);+ removeSearchHistory(text).then(() => history.refetch());+ };++ const clearAll = async () => {+ const snapshot = history.data ?? [];+ if (snapshot.length === 0) return;+ close();+ await clearSearchHistory();+ await history.refetch();+ // 轻量破坏性操作:给一次撤销机会,不打断式弹确认+ toast('已清空搜索记录', 'info', {+ action: {+ label: '撤销',+ onClick: () => {+ restoreSearchHistory(snapshot).then(() => history.refetch());+ },+ },+ });+ };++ const onFocus = () => {+ setOpen(true);+ history.refetch();+ };++ const onKeyDown = (e: KeyboardEvent<HTMLInputElement>, onPick: (text: string) => void) => {+ if (e.key === 'Escape') {+ close();+ return;+ }+ if (!visible) return;+ if (e.key === 'ArrowDown') {+ e.preventDefault();+ setActiveIndex((i) => (i + 1) % matches.length);+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ setActiveIndex((i) => (i <= 0 ? matches.length - 1 : i - 1));+ } else if (e.key === 'Enter' && activeIndex >= 0) {+ // 有高亮项时 Enter 采用该条历史,不再提交输入框原文+ e.preventDefault();+ onPick(matches[activeIndex].text);+ }+ };++ return {+ visible,+ matches,+ activeIndex,+ containerRef,+ close,+ record,+ remove,+ clearAll,+ onFocus,+ onKeyDown,+ /** 输入变化时清掉键盘高亮,避免指向已过滤掉的项 */+ resetActive: () => setActiveIndex(-1),+ };+}++/**+ * 最近搜索浮层:紧贴输入框下方,与输入框「拼成同一个面板」。+ * - 不留间隙、不画上边框、上角为直角:上圆角与上边框由输入框容器补齐,+ * 因此接缝处既不会出现缝隙,也不会出现双线;+ * - 外框取 accent 色,与输入框的聚焦边框同色,避免拼接处「上半蓝、下半灰」断色;+ * - 左右内边距与输入框文字(pl-4)对齐,使下拉文字与输入内容在同一条竖线上;+ * - 作为浮层不占文档流,出现/消失不会引起下方内容跳动。+ */+export function SearchHistoryDropdown({+ id,+ matches,+ activeIndex,+ onPick,+ onRemove,+ onClearAll,+}: {+ /** 同时作为 listbox 的 id 前缀:外部输入框用 aria-controls 指向它 */+ id: string;+ matches: { text: string }[];+ activeIndex: number;+ onPick: (text: string) => void;+ onRemove: (text: string) => void;+ onClearAll: () => void;+}) {+ return (+ <div+ className={cn(+ 'absolute left-0 right-0 top-full z-40 overflow-hidden text-left',+ 'rounded-b-xl border-x border-b border-accent bg-surface-raised shadow-2xl animate-fade-in'+ )}+ >+ <div className="flex items-center justify-between pl-4 pr-2 py-2 border-b border-line">+ <span className="flex items-center gap-1.5 text-xs text-faint">+ <Icon name="clock" className="w-3.5 h-3.5" />+ 最近搜索+ </span>+ <button+ type="button"+ className="px-2 py-1 rounded-md text-xs text-faint hover:text-danger hover:bg-hover transition-colors"+ onClick={onClearAll}+ >+ 清空+ </button>+ </div>+ <ul+ id={id}+ role="listbox"+ aria-label="最近搜索"+ className="max-h-[min(70vh,400px)] overflow-y-auto scrollbar-thin py-1"+ >+ {matches.map((h, i) => (+ <li+ key={h.text}+ id={`${id}-${i}`}+ role="option"+ aria-selected={i === activeIndex}+ className={cn('flex items-center hover:bg-hover', i === activeIndex && 'bg-hover')}+ >+ <button+ type="button"+ className="flex-1 min-w-0 pl-4 pr-2 py-2.5 text-left text-sm text-content truncate"+ onClick={() => onPick(h.text)}+ >+ {h.text}+ </button>+ <button+ type="button"+ className="shrink-0 p-1.5 mr-2 rounded-md text-faint hover:text-danger hover:bg-chip transition-colors"+ aria-label={`删除搜索记录 ${h.text}`}+ onClick={() => onRemove(h.text)}+ >+ <Icon name="close" className="w-3.5 h-3.5" />+ </button>+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/src/components/settings-shared.tsx b/src/components/settings-shared.tsxindex 2d7f78f..4d60914 100644--- a/src/components/settings-shared.tsx+++ b/src/components/settings-shared.tsx@@ -1,10 +1,11 @@'use client';import { useCallback, useState, type ReactNode } from 'react';-import { cn } from '@/lib/utils';-import { useAppStore } from '@/lib/store';+import { cn, formatDisableTtl } from '@/lib/utils';+import { isInDisabledSubscription, useAppStore } from '@/lib/store';import { useToast } from './toast';-import { Icon, type IconName } from './icon';+import { Icon } from './icon';+import { Spinner } from './states';/*** 设置面板共享件:把此前点播源 / 直播源各自「抄一遍」的标题、开关、@@ -74,25 +75,43 @@ export function ToggleRow({<div className="text-sm text-content">{label}</div><div className="text-xs text-faint">{description}</div></div>- <button- role="switch"- aria-checked={checked}- aria-label={label}+ <Switch checked={checked} onChange={onChange} label={label} />+ </div>+ );+}++/** 开关本体:设置项与列表行(如订阅启停)共用,保证尺寸与动效一致 */+export function Switch({+ checked,+ onChange,+ label,+ title,+}: {+ checked: boolean;+ onChange: (v: boolean) => void;+ label: string;+ title?: string;+}) {+ return (+ <button+ role="switch"+ aria-checked={checked}+ aria-label={label}+ title={title ?? label}+ className={cn(+ 'relative h-[22px] w-10 shrink-0 rounded-full transition-colors duration-200',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40',+ checked ? 'bg-accent' : 'bg-chip ring-1 ring-inset ring-line'+ )}+ onClick={() => onChange(!checked)}+ >+ <spanclassName={cn(- 'relative h-[22px] w-10 shrink-0 rounded-full transition-colors duration-200',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40',- checked ? 'bg-accent' : 'bg-chip ring-1 ring-inset ring-line'+ 'absolute left-[2px] top-[2px] h-[18px] w-[18px] rounded-full bg-white shadow-sm transition-transform duration-200 ease-out',+ checked ? 'translate-x-[18px]' : 'translate-x-0')}- onClick={() => onChange(!checked)}- >- <span- className={cn(- 'absolute left-[2px] top-[2px] h-[18px] w-[18px] rounded-full bg-white shadow-sm transition-transform duration-200 ease-out',- checked ? 'translate-x-[18px]' : 'translate-x-0'- )}- />- </button>- </div>+ />+ </button>);}@@ -132,27 +151,6 @@ export function SelectRow({);}-export function EmptyState({- icon = 'link',- title,- description,- action,-}: {- icon?: IconName;- title: string;- description?: string;- action?: ReactNode;-}) {- return (- <div className="border border-dashed border-line rounded-lg p-6 text-center">- <Icon name={icon} className="w-6 h-6 mx-auto text-faint mb-2" />- <p className="text-sm text-muted">{title}</p>- {description && <p className="text-xs text-faint mt-1 leading-relaxed">{description}</p>}- {action && <div className="mt-3 flex items-center justify-center gap-2">{action}</div>}- </div>- );-}-export function SearchInput({value,onChange,@@ -170,6 +168,7 @@ export function SearchInput({/><inputclassName="input w-full !pl-8 !py-1.5 text-xs"+ aria-label={placeholder ?? '搜索'}value={value}onChange={(e) => onChange(e.target.value)}placeholder={placeholder}@@ -196,7 +195,7 @@ export function TestBadge({<spanclassName={cn('text-[10px] px-1.5 py-0.5 rounded',- state.ok ? 'bg-green-500/15 text-green-600 dark:text-green-400' : 'bg-red-500/15 text-red-500'+ state.ok ? 'bg-success/15 text-success' : 'bg-danger/15 text-danger')}title={state.ok ? `${state.ms}ms` : state.error}>@@ -206,20 +205,14 @@ export function TestBadge({<buttonclassName={cn('rounded-md p-2 transition-colors disabled:opacity-40',- state?.status === 'done' && !state.ok- ? 'text-red-400'- : 'text-muted hover:text-accent hover:bg-hover'+ state?.status === 'done' && !state.ok ? 'text-danger' : 'text-muted hover:text-accent hover:bg-hover')}disabled={state?.status === 'loading'}onClick={onTest}aria-label={title}title={title}>- {state?.status === 'loading' ? (- <span className="block w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />- ) : (- <Icon name="bolt" className="w-4 h-4" />- )}+ {state?.status === 'loading' ? <Spinner size="sm" /> : <Icon name="bolt" className="w-4 h-4" />}</button></span>);@@ -228,20 +221,43 @@ export function TestBadge({/** 点播源搜索健康度徽章(随搜索/批量测活滚动更新);被自动停用的源提供手动恢复入口 */export function HealthBadge({ sourceKey }: { sourceKey: string }) {const entry = useAppStore((s) => s.sourceHealth[sourceKey]);+ const inDisabledSub = useAppStore((s) => isInDisabledSubscription(s, sourceKey));const { toast } = useToast();++ // 订阅被整体关闭时优先说明原因:否则源看起来「勾选正常却搜不到」,用户会以为是源坏了+ if (inDisabledSub) {+ return (+ <span+ className="text-[10px] px-1.5 py-0.5 rounded bg-warning/15 text-warning shrink-0"+ title="所属订阅已被停用,该源暂不参与搜索;到「数据源订阅」重新启用即可"+ >+ 订阅已停用+ </span>+ );+ }+if (!entry) return null;- const disabled = !!entry.disabledUntil && entry.disabledUntil > Date.now();+ const permanent = entry.permanent === true;+ const disabled = permanent || (!!entry.disabledUntil && entry.disabledUntil > Date.now());if (disabled) {- const remainMin = Math.max(1, Math.ceil(((entry.disabledUntil ?? 0) - Date.now()) / 60000));+ // 长期停用(阶梯用尽)没有到期时间,展示为红色并提示需手动恢复+ const remainText = formatDisableTtl((entry.disabledUntil ?? 0) - Date.now());return (<span className="flex items-center gap-1 shrink-0"><span- className="inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-500"- title={`连续 ${entry.failStreak} 次超时/失败,${remainMin} 分钟后自动恢复`}+ className={cn(+ 'inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded',+ permanent ? 'bg-danger/15 text-danger' : 'bg-warning/15 text-warning'+ )}+ title={+ permanent+ ? `已第 ${entry.disableCount} 次被自动停用,暂停参与搜索;点「恢复」重新启用`+ : `连续 ${entry.failStreak} 次超时/失败,${remainText}后自动恢复`+ }><Icon name="clock" className="w-3 h-3" />- {remainMin} 分+ {permanent ? '已停用' : remainText}</span><buttonclassName="text-[10px] px-1.5 py-0.5 rounded text-muted hover:text-accent hover:bg-hover transition-colors"@@ -260,7 +276,7 @@ export function HealthBadge({ sourceKey }: { sourceKey: string }) {if (entry.ok) {return (- <span className="text-[10px] px-1.5 py-0.5 rounded bg-green-500/15 text-green-600 dark:text-green-400 shrink-0" title={`上次搜索 ${entry.ms}ms`}>+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-success/15 text-success shrink-0" title={`上次搜索 ${entry.ms}ms`}>✓ {entry.ms}ms</span>);@@ -269,7 +285,7 @@ export function HealthBadge({ sourceKey }: { sourceKey: string }) {<spanclassName={cn('text-[10px] px-1.5 py-0.5 rounded shrink-0',- entry.timedOut ? 'bg-amber-500/15 text-amber-500' : 'bg-red-500/15 text-red-500'+ entry.timedOut ? 'bg-warning/15 text-warning' : 'bg-danger/15 text-danger')}title={entry.error}>diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsxindex 412aed8..349aa71 100644--- a/src/components/source-manager.tsx+++ b/src/components/source-manager.tsx@@ -6,18 +6,19 @@ import { ConfirmDialog } from './confirm-dialog';import { Icon, type IconName } from './icon';import { LiveSourceManager } from './live-source-manager';import {- EmptyState,HealthBadge,SearchInput,SectionTitle,SelectRow,TestBadge,ToggleRow,+ Switch,useSourceTests,type TestState,} from './settings-shared';+import { EmptyState, Spinner } from './states';import { useSourceProbe } from './use-source-probe';-import { isSourceDisabled, keyBelongsToSubscription, subKeyPrefix, useAppStore } from '@/lib/store';+import { allLiveSources, isSourceDisabled, keyBelongsToSubscription, resolveSource, subKeyPrefix, useAppStore } from '@/lib/store';import type { SourceConfig } from '@/lib/types';import { useToast } from './toast';import { formatRelativeTime, hostnameOf, validateSourceUrl, cn } from '@/lib/utils';@@ -159,7 +160,7 @@ function TabRow<T extends string>({<divrole="tablist"aria-label={ariaLabel}- className={cn('flex gap-1', variant === 'primary' ? 'p-0.5 bg-chip rounded-lg' : 'overflow-x-auto scrollbar-thin')}+ className={cn('flex w-full gap-1', variant === 'primary' && 'p-0.5 bg-chip rounded-lg')}onKeyDown={(e) => {if (e.key === 'ArrowRight') {e.preventDefault();@@ -178,10 +179,11 @@ function TabRow<T extends string>({role="tab"aria-selected={active}className={cn(- 'shrink-0 inline-flex items-center justify-center gap-1 rounded-md transition-colors',+ // 两级导航都等宽撑满一行(原先二级按内容宽度、超宽才横滚,与一级不一致)+ 'flex-1 min-w-0 inline-flex items-center justify-center gap-1 whitespace-nowrap rounded-md transition-colors',variant === 'primary'? cn(- 'flex-1 px-2 py-1.5 text-xs',+ 'px-2 py-1.5 text-xs',active ? 'bg-surface-raised text-accent font-medium shadow-sm' : 'text-muted hover:text-content'): cn(@@ -281,7 +283,7 @@ function VodSourcesPanel() {title="点播源"hint={empty ? undefined : `共 ${all.length} 个 · 已启用 ${all.filter((s) => store.selectedKeys.includes(s.key)).length}`}extra={- <button className="btn-primary !py-1 !px-2.5 text-xs" onClick={() => setEditing('__new__')}>+ <button className="btn-primary btn-sm" onClick={() => setEditing('__new__')}><Icon name="plus" className="w-3.5 h-3.5" />添加 API</button>@@ -303,7 +305,7 @@ function VodSourcesPanel() {title="还没有添加任何点播源"description="添加一个 Apple CMS 采集站 API 即可开始搜索影片;也可到「数据源订阅」一次导入点播源与直播源"action={- <button className="btn-primary text-xs" onClick={() => setEditing('__new__')}>+ <button className="btn-primary btn-sm" onClick={() => setEditing('__new__')}>添加第一个点播源</button>}@@ -317,7 +319,7 @@ function VodSourcesPanel() {<buttonkey={f.id}className={cn(- 'px-2 py-0.5 rounded-full text-[11px] transition-colors',+ 'chip',filter === f.id ? 'bg-accent/10 text-accent font-medium' : 'text-muted hover:text-content hover:bg-hover')}onClick={() => setFilter(f.id)}@@ -329,11 +331,11 @@ function VodSourcesPanel() {<span className="ml-auto text-[11px] text-faint">显示 {filtered.length} 个</span></div><div className="flex flex-wrap items-center gap-2">- <button className="btn-ghost !py-1 !px-2 text-[11px]" onClick={toggleAll} disabled={filtered.length === 0}>+ <button className="btn-ghost btn-sm" onClick={toggleAll} disabled={filtered.length === 0}>{allSelected ? '全部停用' : '全部启用'}</button><button- className="btn-ghost !py-1 !px-2 text-[11px]"+ className="btn-ghost btn-sm"onClick={runAll}disabled={filtered.length === 0}>@@ -341,7 +343,7 @@ function VodSourcesPanel() {</button>{/* 查看「已停用」时提供一键恢复,省去逐个点击 */}{filter === 'disabled' && (- <button className="btn-ghost !py-1 !px-2 text-[11px]" onClick={restoreAll} disabled={filtered.length === 0}>+ <button className="btn-ghost btn-sm" onClick={restoreAll} disabled={filtered.length === 0}>全部恢复</button>)}@@ -358,7 +360,7 @@ function VodSourcesPanel() {{progress.done}/{progress.total} · 可用 {progress.ok}{formatEta(progress.done, progress.total, progress.startedAt)}</span>- <button className="btn-ghost !py-0.5 !px-2 !text-[10px] shrink-0" onClick={cancel}>+ <button className="btn-ghost btn-sm shrink-0" onClick={cancel}>取消</button></div>@@ -366,7 +368,7 @@ function VodSourcesPanel() {</div>{filtered.length === 0 ? (- <p className="text-xs text-faint py-6 text-center">没有符合条件的源</p>+ <EmptyState variant="plain" title="没有符合条件的源" />) : (<ul className="space-y-2">{filtered.map((source) => (@@ -459,11 +461,17 @@ function VodSourceRow({}return (- <li className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">+ <li+ className={cn(+ 'bg-card rounded-lg p-3 transition-colors hover:bg-hover/50',+ // 未勾选 = 不参与搜索:整行淡显,长列表里才能一眼扫出哪些没启用+ !selected && 'opacity-70'+ )}+ ><div className="flex items-center gap-2"><inputtype="checkbox"- className="h-4 w-4 accent-[#2563eb] shrink-0"+ className="h-4 w-4 accent-accent shrink-0"checked={selected}onChange={() => useAppStore.getState().toggleSourceSelected(api.key)}disabled={adultBlocked}@@ -529,7 +537,7 @@ function VodSourceRow({<Icon name="edit" className="w-4 h-4" /></button><button- className="rounded-md p-2 text-muted transition-colors hover:bg-hover hover:text-red-400 shrink-0"+ className="rounded-md p-2 text-muted transition-colors hover:bg-hover hover:text-danger shrink-0"onClick={remove}aria-label="删除"title="移除(可在提示中撤销)"@@ -584,20 +592,42 @@ function ImagePanel() {{ value: 'custom', label: '自定义代理' },]}/>- {store.imageProxyMode === 'custom' && (- <input- className="input w-full"- placeholder="代理模板,如 https://p.example.com/?url={url}"- value={store.customImageProxy}- onChange={(e) => store.updateSettings({ customImageProxy: e.target.value })}- />- )}+ {store.imageProxyMode === 'custom' && <CustomProxyInput />}<p className="text-xs text-faint">豆瓣封面在某些网络下直连会被拒绝,可切换为内置代理。</p></div></section>);}+/**+ * 自定义代理模板输入:本地即时回显 + 300ms 防抖写 store。+ * 直接每次按键写 store 会让全站封面 URL 重算并触发一轮图片重载(模板输入时缩略图持续闪烁)。+ */+function CustomProxyInput() {+ const value = useAppStore((s) => s.customImageProxy);+ const updateSettings = useAppStore((s) => s.updateSettings);+ const [draft, setDraft] = useState(value);++ // 外部值变化(如导入配置)时同步回显+ useEffect(() => setDraft(value), [value]);++ useEffect(() => {+ if (draft === value) return;+ const timer = setTimeout(() => updateSettings({ customImageProxy: draft }), 300);+ return () => clearTimeout(timer);+ }, [draft, value, updateSettings]);++ return (+ <input+ className="input w-full"+ aria-label="自定义代理模板"+ placeholder="代理模板,如 https://p.example.com/?url={url}"+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ />+ );+}+function HomePanel() {const store = useAppStore();return (@@ -676,6 +706,67 @@ function SourceSubscriptions() {void sync(url);};+ // 发布状态:进行中 + 上一次的发布结果(链接、粘贴板来源与条数)+ const [publishing, setPublishing] = useState(false);+ const [published, setPublished] = useState<{+ url: string;+ provider: string;+ sources: number;+ liveSources: number;+ } | null>(null);++ /**+ * 发布当前「已勾选启用」的源:只把真正在参与搜索的源发出去+ * (未勾选的、以及被自动停用的都排除)。注意这与「导出数据源」的全量语义不同。+ */+ const publish = async () => {+ const seen = new Set<string>();+ const sources = store.selectedKeys+ .map((key) => resolveSource(store, key))+ .filter((s): s is SourceConfig => !!s && validateSourceUrl(s.url) && !isSourceDisabled(store, s.key))+ .filter((s) => {+ const key = s.url.replace(/\/+$/, '');+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ })+ .map(({ name, url }) => ({ name, url }));++ const liveSeen = new Set<string>();+ const liveSources = allLiveSources(store)+ .filter((s) => store.liveSelectedUrls.includes(s.url))+ .filter((s) => {+ if (liveSeen.has(s.url)) return false;+ liveSeen.add(s.url);+ return true;+ })+ .map(({ name, url, epg }) => ({ name: name || hostnameOf(url), url, epg }));++ if (sources.length === 0 && liveSources.length === 0) {+ toast('没有已勾选启用的源可发布', 'warning');+ return;+ }++ setPublishing(true);+ try {+ const result = await api.publishSourceList({ name: 'LibreTV-SourceList', sources, liveSources });+ setPublished(result);+ toast(`已发布 ${result.sources} 个点播源、${result.liveSources} 个直播源到 ${result.provider}`, 'success');+ } catch (err) {+ toast(err instanceof Error ? err.message : '发布失败', 'error');+ } finally {+ setPublishing(false);+ }+ };++ const copyPublished = () => {+ if (!published) return;+ navigator.clipboard+ .writeText(published.url)+ .then(() => toast('订阅链接已复制', 'success'))+ .catch(() => toast('复制失败,请手动选中复制', 'warning'));+ };+const exportSources = () => {const all = [...store.envSources, ...store.customAPIs];const seen = new Set<string>();@@ -722,18 +813,60 @@ function SourceSubscriptions() {<SectionTitletitle="数据源订阅 / 分享"extra={- <button- className="btn-ghost !py-1 !px-2.5 text-xs"- onClick={exportSources}- disabled={- store.customAPIs.length + store.envSources.length + store.liveSubscriptions.length + store.liveEnvSources.length ===- 0- }- >- 导出数据源- </button>+ <div className="flex items-center gap-1.5 shrink-0">+ <button+ className="btn-ghost btn-sm"+ onClick={exportSources}+ disabled={+ store.customAPIs.length + store.envSources.length + store.liveSubscriptions.length + store.liveEnvSources.length ===+ 0+ }+ >+ 导出数据源+ </button>+ <button+ className="btn-ghost btn-sm"+ onClick={() => void publish()}+ disabled={publishing}+ title="把当前已勾选启用的源上传到公开粘贴板,生成可直接订阅的链接"+ >+ {publishing ? '发布中…' : '发布为链接'}+ </button>+ </div>}/>++ {/* 发布结果:链接公开可读、粘贴板也可能随时清理,这些风险直接写在这里而不是只在 toast 里闪一下 */}+ {published && (+ <div className="mb-3 rounded-lg border border-line bg-chip/60 p-2.5">+ <div className="flex items-center gap-1.5">+ <input+ readOnly+ value={published.url}+ className="input flex-1 min-w-0 !py-1.5 text-xs"+ aria-label="已发布的订阅地址"+ onFocus={(e) => e.currentTarget.select()}+ />+ <button className="btn-ghost btn-sm shrink-0" onClick={copyPublished}>+ 复制+ </button>+ <button+ className="btn-ghost btn-sm shrink-0"+ onClick={() => {+ setSubUrl(published.url);+ void sync(published.url);+ }}+ >+ 直接订阅+ </button>+ </div>+ <p className="mt-1.5 text-[11px] text-faint leading-relaxed">+ 已发布到 {published.provider}({published.sources} 个点播源、{published.liveSources} 个直播源)。+ 链接内容公开可读,粘贴板也可能随时清理——长期使用建议自行托管。+ </p>+ </div>+ )}+<div className="flex gap-2 mb-2"><inputclassName="input flex-1 min-w-0"@@ -745,7 +878,7 @@ function SourceSubscriptions() {}}/><button- className="btn-primary !py-1.5 text-xs shrink-0"+ className="btn-primary btn-sm shrink-0"disabled={!subUrl.trim() || syncing.size > 0}onClick={addAndSync}>@@ -764,7 +897,14 @@ function SourceSubscriptions() {const liveCount = store.liveSubscriptions.filter((s) => s.fromSubscriptions.includes(sub.url)).length;const isSyncing = syncing.has(sub.url);return (- <li key={sub.url} className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">+ <li+ key={sub.url}+ className={cn(+ 'bg-card rounded-lg p-3 transition-colors hover:bg-hover/50',+ // 与源列表的「未勾选」用同一套停用观感:淡显 + 徽章说明+ sub.enabled === false && 'opacity-70'+ )}+ ><div className="flex items-center gap-2"><div className="flex-1 min-w-0"><div className="text-sm font-medium text-content truncate">{sub.name || hostnameOf(sub.url)}</div>@@ -775,23 +915,36 @@ function SourceSubscriptions() {<div className="mt-1 flex items-center gap-1 flex-wrap"><span className="text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent">点播 {vodCount}</span><span className="text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent">直播 {liveCount}</span>+ {sub.enabled === false && (+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-warning/15 text-warning">已停用</span>+ )}{sub.lastStatus === 'error' ? (<span- className="text-[10px] px-1.5 py-0.5 rounded bg-red-500/15 text-red-500"+ className="text-[10px] px-1.5 py-0.5 rounded bg-danger/15 text-danger"title={sub.lastError}>上次同步失败</span>) : sub.lastStatus === 'ok' && sub.lastCounts ? (- <span className="text-[10px] px-1.5 py-0.5 rounded bg-green-500/15 text-green-600 dark:text-green-400">+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-success/15 text-success">上次导入 {sub.lastCounts.vod} 点播 / {sub.lastCounts.live} 直播</span>) : null}</div>{sub.lastStatus === 'error' && sub.lastError && (- <p className="text-[11px] text-red-400 mt-1 break-all">{sub.lastError}</p>+ <p className="text-[11px] text-danger mt-1 break-all">{sub.lastError}</p>)}</div>+ <Switch+ checked={sub.enabled !== false}+ onChange={(v) => store.setSubscriptionEnabled(sub.url, v)}+ label={sub.enabled === false ? '启用该订阅' : '停用该订阅'}+ title={+ sub.enabled === false+ ? '当前已停用(其源不参与搜索),点击启用'+ : '停用后该订阅下的源暂不参与搜索;已导入的数据与各源勾选状态都保留'+ }+ /><buttonclassName="rounded-md p-2 shrink-0 text-muted transition-colors hover:bg-hover hover:text-accent disabled:opacity-40"disabled={isSyncing}@@ -800,13 +953,13 @@ function SourceSubscriptions() {title="重新同步(以远端列表为准,整体替换该订阅名下的点播源与直播源)">{isSyncing ? (- <span className="block w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />+ <Spinner size="sm" />) : (<Icon name="refresh" className="w-4 h-4" />)}</button><button- className="rounded-md p-2 shrink-0 text-muted transition-colors hover:bg-hover hover:text-red-400"+ className="rounded-md p-2 shrink-0 text-muted transition-colors hover:bg-hover hover:text-danger"onClick={() => setPendingDelete(sub.url)}aria-label="删除订阅"title="删除订阅及其导入的点播源与直播源(保留收藏的频道)"@@ -1013,19 +1166,27 @@ function SourceForm({return (<div className="space-y-2 border border-line rounded-lg p-3 bg-chip mb-2">- <input className="input w-full" placeholder="名称" value={name} onChange={(e) => setName(e.target.value)} />- <input- className="input w-full"- placeholder="API 地址,如 https://example.com/api.php/provide/vod"- value={url}- onChange={(e) => setUrl(e.target.value)}- />- <input- className="input w-full"- placeholder="详情页地址(可选),如 https://example.com"- value={detail}- onChange={(e) => setDetail(e.target.value)}- />+ <input+ className="input w-full"+ aria-label="点播源名称"+ placeholder="名称"+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ <input+ className="input w-full"+ aria-label="API 地址"+ placeholder="API 地址,如 https://example.com/api.php/provide/vod"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ />+ <input+ className="input w-full"+ aria-label="详情页地址(可选)"+ placeholder="详情页地址(可选),如 https://example.com"+ value={detail}+ onChange={(e) => setDetail(e.target.value)}+ /><label className="flex items-center gap-2 text-xs text-muted"><inputtype="checkbox"@@ -1036,10 +1197,10 @@ function SourceForm({标记为成人内容源(受成人过滤控制)</label><div className="flex gap-2 justify-end">- <button className="btn-ghost !py-1 text-xs" onClick={onCancel}>+ <button className="btn-ghost btn-sm" onClick={onCancel}>取消</button>- <button className="btn-primary !py-1 text-xs" onClick={submit}>+ <button className="btn-primary btn-sm" onClick={submit}>{initial ? '更新' : '添加'}</button></div>diff --git a/src/components/states.tsx b/src/components/states.tsxnew file mode 100644index 0000000..f44cf3e--- /dev/null+++ b/src/components/states.tsx@@ -0,0 +1,110 @@+'use client';++import type { ReactNode } from 'react';+import { cn } from '@/lib/utils';+import { Icon, type IconName } from './icon';++/**+ * 全站统一的状态呈现:加载中 / 空态 / 错误态。+ * 此前各处以 h-5/h-8/h-9 × border-2/3/4 的多种 spinner、+ * 「图标+标题」/「虚线框」/`❌` emoji / 纯文字四种空态混用,这里收敛为三个组件。+ */++const SPINNER_SIZE = {+ sm: 'w-4 h-4 border-2',+ md: 'w-8 h-8 border-4',+ lg: 'w-9 h-9 border-4',+} as const;++export function Spinner({+ size = 'md',+ tone = 'default',+ className,+}: {+ size?: keyof typeof SPINNER_SIZE;+ /** onDark:播放器错误层等深色背景之上 */+ tone?: 'default' | 'onDark';+ className?: string;+}) {+ return (+ <span+ className={cn(+ 'inline-block rounded-full animate-spin shrink-0',+ SPINNER_SIZE[size],+ tone === 'onDark' ? 'border-white/30 border-t-white' : 'border-line border-t-accent',+ className+ )}+ aria-hidden+ />+ );+}++/** 加载中:spinner + 可选文案(替代各处「纯文字 加载中...」) */+export function LoadingState({ label, className }: { label?: string; className?: string }) {+ return (+ <div className={cn('flex flex-col items-center justify-center gap-3 py-10', className)}>+ <Spinner size="md" />+ {label && <p className="text-sm text-muted">{label}</p>}+ </div>+ );+}++export function EmptyState({+ icon = 'link',+ title,+ description,+ action,+ /** boxed:虚线框引导(列表为空);plain:单行文字(筛选无结果等) */+ variant = 'boxed',+ className,+}: {+ icon?: IconName;+ title: string;+ description?: string;+ action?: ReactNode;+ variant?: 'boxed' | 'plain';+ className?: string;+}) {+ if (variant === 'plain') {+ return <p className={cn('text-center text-xs text-faint py-6', className)}>{title}</p>;+ }+ return (+ <div className={cn('border border-dashed border-line rounded-lg p-6 text-center', className)}>+ <Icon name={icon} className="w-6 h-6 mx-auto text-faint mb-2" />+ <p className="text-sm text-muted">{title}</p>+ {description && <p className="text-xs text-faint mt-1 leading-relaxed">{description}</p>}+ {action && <div className="mt-3 flex items-center justify-center gap-2">{action}</div>}+ </div>+ );+}++export function ErrorState({+ message,+ onRetry,+ retryLabel = '重试',+ tone = 'default',+ className,+}: {+ message: string;+ onRetry?: () => void;+ retryLabel?: string;+ tone?: 'default' | 'onDark';+ className?: string;+}) {+ return (+ <div className={cn('flex flex-col items-center justify-center gap-3 py-8 text-center', className)}>+ <Icon name="alert" className={cn('w-6 h-6', tone === 'onDark' ? 'text-white/80' : 'text-danger')} />+ <p className={cn('text-sm break-words max-w-md', tone === 'onDark' ? 'text-white/80' : 'text-muted')}>+ {message}+ </p>+ {onRetry && (+ <button+ className={cn('btn-ghost btn-sm', tone === 'onDark' && '!bg-white/10 !text-white !border-white/20')}+ onClick={onRetry}+ >+ {retryLabel}+ </button>+ )}+ </div>+ );+}diff --git a/src/components/switch-source.tsx b/src/components/switch-source.tsxindex aba8385..8ad0c13 100644--- a/src/components/switch-source.tsx+++ b/src/components/switch-source.tsx@@ -1,12 +1,15 @@'use client';-import { useEffect, useMemo, useState } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';import { useRouter } from 'next/navigation';import { api } from '@/lib/client-api';import type { SourceConfig, SearchResultItem } from '@/lib/types';import { buildImageUrl, buildWatchUrl, cn } from '@/lib/utils';import { useAppStore, resolveSource } from '@/lib/store';import { useToast } from './toast';+import { Icon } from './icon';+import { EmptyState, LoadingState } from './states';+import { useFocusTrap } from './use-focus-trap';/*** 换源面板:跨源按标题搜索 → 匹配同名资源 → 并发测速(详情接口耗时)→ 按速度排序展示。@@ -39,6 +42,12 @@ export function SwitchSourceModal({const { toast } = useToast();const [candidates, setCandidates] = useState<Candidate[]>([]);const [phase, setPhase] = useState<'searching' | 'testing' | 'done'>('searching');+ /** 封面加载失败记录(按卡片 key);失败后降级为占位图标,避免破图 */+ const [imgFailed, setImgFailed] = useState<Record<string, boolean>>({});+ const panelRef = useRef<HTMLDivElement>(null);++ // 打开时把焦点移入弹窗、Tab 圈闭在弹窗内、关闭后归还焦点+ useFocusTrap(true, panelRef);const sources = useMemo(() => {// selectedKeys 可能含历史残留的重复 key:按 key 去重,避免同源重复搜索/测速与 React key 撞车@@ -53,22 +62,32 @@ export function SwitchSourceModal({}, [store]);useEffect(() => {- // 弹窗打开期间锁定背景滚动+ // 弹窗打开期间锁定背景滚动;Esc 关闭(与其它弹窗一致)const prev = document.body.style.overflow;document.body.style.overflow = 'hidden';+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', onKey);return () => {document.body.style.overflow = prev;+ window.removeEventListener('keydown', onKey);};- }, []);+ }, [onClose]);useEffect(() => {+ // 关闭弹窗时中止在途请求:否则 N 个源的搜索 + N 个详情测速会继续占用网络与后端+ const controller = new AbortController();let cancelled = false;(async () => {// 1) 并行搜索所有选中源setPhase('searching');try {- const { list } = await api.search(currentTitle, sources, false);+ const { list } = await api.search(currentTitle, sources, false, { signal: controller.signal });if (cancelled) return;// 每个源取完全同名结果,否则取第一个@@ -83,7 +102,7 @@ export function SwitchSourceModal({setPhase('testing');await Promise.all(matched.map(async (c) => {- const r = await api.detailSpeed(c.result.vodId, c.source);+ const r = await api.detailSpeed(c.result.vodId, c.source, controller.signal);if (cancelled) return;c.ok = r.ok;c.ms = r.ms;@@ -94,7 +113,9 @@ export function SwitchSourceModal({setCandidates(matched);setPhase('done');} catch (err) {- if (!cancelled) {+ // 主动中止不算失败,不提示+ const aborted = err instanceof DOMException && err.name === 'AbortError';+ if (!cancelled && !aborted) {toast(err instanceof Error ? err.message : '换源搜索失败', 'error');setPhase('done');}@@ -103,6 +124,7 @@ export function SwitchSourceModal({return () => {cancelled = true;+ controller.abort();};// eslint-disable-next-line react-hooks/exhaustive-deps}, [currentTitle]);@@ -142,12 +164,25 @@ export function SwitchSourceModal({if (e.target === e.currentTarget) onClose();}}>- <div className="bg-surface-raised rounded-xl w-full max-w-3xl shadow-2xl p-5 animate-slide-up" role="dialog" aria-modal>+ <div+ ref={panelRef}+ tabIndex={-1}+ className="bg-surface-raised rounded-xl w-full max-w-3xl shadow-2xl p-5 animate-slide-up outline-none"+ role="dialog"+ aria-modal="true"+ aria-label={`换源:${currentTitle}`}+ ><div className="flex items-center justify-between mb-4"><div className="min-w-0">- <h2 className="text-lg font-semibold text-content truncate">{currentTitle}</h2>+ <h2 className="text-lg font-semibold text-content truncate" title={currentTitle}>+ {currentTitle}+ </h2><p className="text-xs text-faint">- {phase === 'searching' ? '正在搜索各资源...' : phase === 'testing' ? '正在测试各资源速率...' : `共 ${sorted.length} 个可用资源`}+ {phase === 'searching'+ ? '正在搜索各资源...'+ : phase === 'testing'+ ? '正在测试各资源速率...'+ : `共 ${sorted.length} 个来源 · ${sorted.filter((c) => c.ok).length} 个可用`}</p></div><button className="p-1.5 rounded-md text-muted hover:text-content hover:bg-hover" onClick={onClose} aria-label="关闭">@@ -158,17 +193,16 @@ export function SwitchSourceModal({</div>{phase !== 'done' ? (- <div className="flex flex-col items-center py-10 gap-3">- <div className="h-8 w-8 rounded-full border-4 border-line border-t-accent animate-spin" />- <p className="text-sm text-muted">{phase === 'searching' ? '搜索各资源中...' : '测速中...'}</p>- </div>+ <LoadingState label={phase === 'searching' ? '搜索各资源中...' : '测速中...'} />) : sorted.length === 0 ? (- <p className="text-center text-sm text-faint py-8">其他点播源未找到同名资源</p>+ <EmptyState variant="plain" title="其他点播源未找到同名资源" />) : (<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">{sorted.map((c) => {const isCurrent = c.source.key === currentSourceKey && String(c.result.vodId) === String(currentVodId);+ const cardKey = `${c.source.key}_${c.result.vodId}`;const img = buildImageUrl(c.result.pic, store.imageProxyMode, store.customImageProxy);+ const coverFailed = imgFailed[cardKey] ?? false;return (<buttonkey={`${c.source.key}_${c.result.vodId}`}@@ -177,27 +211,37 @@ export function SwitchSourceModal({disabled={isCurrent}><div className="relative aspect-[2/3] bg-chip">- {img ? (+ {img && !coverFailed ? (// eslint-disable-next-line @next/next/no-img-element- <img src={img} alt={c.result.name} className="w-full h-full object-cover" loading="lazy" />+ <img+ src={img}+ alt={c.result.name}+ className="w-full h-full object-cover"+ loading="lazy"+ onError={() => setImgFailed((prev) => ({ ...prev, [cardKey]: true }))}+ />) : (- <div className="w-full h-full flex items-center justify-center text-faint text-xs">无封面</div>+ <div className="w-full h-full flex items-center justify-center text-faint">+ <Icon name="link" className="w-6 h-6" />+ </div>)}<spanclassName={cn('absolute top-1.5 right-1.5 tag',- !c.ok ? 'bg-red-500/80 text-white' : c.ms! > 2000 ? 'bg-yellow-600/80 text-white' : 'bg-green-600/80 text-white'+ !c.ok ? 'bg-danger-solid/85 text-white' : c.ms! > 2000 ? 'bg-warning-solid/85 text-white' : 'bg-success-solid/85 text-white')}>{!c.ok ? '失败' : `${c.ms}ms`}</span>{isCurrent && (- <span className="absolute inset-x-0 bottom-0 bg-accent/90 text-white text-xs text-center py-1">当前播放</span>+ <span className="absolute inset-x-0 bottom-0 bg-accent/90 text-on-accent text-xs text-center py-1">当前播放</span>)}</div><div className="p-2">- <div className="text-xs font-medium text-content truncate">{c.source.name}</div>- <div className="text-[10px] text-faint mt-0.5">{c.episodes ? `${c.episodes} 集` : '无资源'}</div>+ <div className="text-xs font-medium text-content truncate" title={c.source.name}>+ {c.source.name}+ </div>+ <div className="text-xs text-faint mt-0.5">{c.episodes ? `${c.episodes} 集` : '无资源'}</div></div></button>);diff --git a/src/components/toast.tsx b/src/components/toast.tsxindex 8c98cfb..fcdeac1 100644--- a/src/components/toast.tsx+++ b/src/components/toast.tsx@@ -37,11 +37,12 @@ export function useToast(): ToastContextValue {return useContext(ToastContext);}+// 用实心底色(-solid,深一档):保证白字对比度达标(普通语义色配白字仅 2-3:1)const TYPE_STYLES: Record<ToastType, string> = {- error: 'bg-red-500',- success: 'bg-green-600',- info: 'bg-blue-500',- warning: 'bg-yellow-600',+ error: 'bg-danger-solid',+ success: 'bg-success-solid',+ info: 'bg-info-solid',+ warning: 'bg-warning-solid',};export function ToastProvider({ children }: { children: ReactNode }) {@@ -81,6 +82,8 @@ export function ToastProvider({ children }: { children: ReactNode }) {{items.map((t) => (<divkey={t.id}+ // 读屏可见:错误用 alert(立即朗读),其余用 status(礼貌播报)+ role={t.type === 'error' ? 'alert' : 'status'}className={cn('px-4 py-2.5 rounded-lg shadow-lg text-white text-sm max-w-md animate-slide-up','flex items-center gap-3 pointer-events-auto',diff --git a/src/components/use-focus-trap.ts b/src/components/use-focus-trap.tsnew file mode 100644index 0000000..e210faf--- /dev/null+++ b/src/components/use-focus-trap.ts@@ -0,0 +1,63 @@+'use client';++import { useEffect, useRef, type RefObject } from 'react';++/** 弹窗内可聚焦元素选择器 */+const FOCUSABLE =+ 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';++/**+ * 弹窗焦点管理:打开时记忆来源并把焦点移入,Tab 在容器内循环(不逃逸到背景页面),+ * 关闭后归还焦点。Drawer 内联实现了同一套逻辑,此处抽出来供其它弹窗(详情 / 换源)复用。+ *+ * @param active 是否处于打开状态(常驻挂载的弹窗传 true 即可)+ * @param containerRef 弹窗面板的 ref(需可聚焦:加 tabIndex={-1})+ */+export function useFocusTrap(active: boolean, containerRef: RefObject<HTMLElement | null>) {+ const restoreRef = useRef<HTMLElement | null>(null);++ useEffect(() => {+ if (!active) return;+ restoreRef.current = document.activeElement as HTMLElement | null;+ const panel = containerRef.current;+ if (panel) {+ const first = panel.querySelector<HTMLElement>(FOCUSABLE);+ (first ?? panel).focus();+ }+ return () => {+ restoreRef.current?.focus?.();+ restoreRef.current = null;+ };+ }, [active, containerRef]);++ useEffect(() => {+ if (!active) return;+ const handler = (e: KeyboardEvent) => {+ if (e.key !== 'Tab') return;+ const panel = containerRef.current;+ if (!panel) return;+ const nodes = Array.from(panel.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(+ (el) => el.getClientRects().length > 0 || el === document.activeElement+ );+ if (nodes.length === 0) {+ e.preventDefault();+ panel.focus();+ return;+ }+ const first = nodes[0];+ const last = nodes[nodes.length - 1];+ const current = document.activeElement;+ if (e.shiftKey) {+ if (current === first || !panel.contains(current)) {+ e.preventDefault();+ last.focus();+ }+ } else if (current === last || !panel.contains(current)) {+ e.preventDefault();+ first.focus();+ }+ };+ window.addEventListener('keydown', handler);+ return () => window.removeEventListener('keydown', handler);+ }, [active, containerRef]);+}diff --git a/src/components/video-card.tsx b/src/components/video-card.tsxindex a15a449..90ce59e 100644--- a/src/components/video-card.tsx+++ b/src/components/video-card.tsx@@ -88,10 +88,10 @@ export function AggregatedCard({};return (- <div className={cn('card', multi && expanded && 'ring-1 ring-accent/40')}>+ <div className={cn('card', !multi && 'hover:scale-[1.02] hover:shadow-md', multi && expanded && 'ring-1 ring-accent/40')}>{/* 不用 h-full:展开面板需要撑高卡片,等高裁切会让面板不可见 */}<div- className={cn('flex h-full', multi ? 'cursor-pointer' : 'cursor-pointer hover:scale-[1.02]')}+ className="flex h-full cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60"role="button"tabIndex={0}aria-expanded={multi ? expanded : undefined}@@ -141,7 +141,7 @@ export function AggregatedCard({<div className="flex flex-wrap gap-1 mb-1.5">{group.typeName && <span className="tag bg-accent/15 text-accent">{group.typeName}</span>}{group.year && <span className="tag bg-purple-500/15 text-purple-600 dark:text-purple-300">{group.year}</span>}- {adult && <span className="tag bg-pink-500/15 text-pink-500">(18+)</span>}+ {adult && <span className="tag bg-pink-500/15 text-pink-600 dark:text-pink-400">(18+)</span>}</div><p className="text-xs text-muted line-clamp-2 mb-2">{group.remarks || '暂无介绍'}</p></div>@@ -214,17 +214,21 @@ export function VideoCard({ item, onClick }: { item: SearchResultItem; onClick:return (<div- className="card cursor-pointer hover:scale-[1.02] hover:shadow-md h-full"+ className="card cursor-pointer hover:scale-[1.02] hover:shadow-md h-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"role="button"tabIndex={0}onClick={onClick}onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') onClick();+ if (e.key === 'Enter' || e.key === ' ') {+ // 阻止空格触发页面滚动(AggregatedCard 已是此写法,此处对齐)+ e.preventDefault();+ onClick();+ }}}><div className="flex h-full">{showImg ? (- <div className="relative flex-shrink-0 w-[105px] sm:w-[120px] bg-chip">+ <div className="relative flex-shrink-0 w-[105px] sm:w-[120px] aspect-[2/3] bg-chip">{/* eslint-disable-next-line @next/next/no-img-element */}<imgsrc={primary}@@ -236,7 +240,7 @@ export function VideoCard({ item, onClick }: { item: SearchResultItem; onClick:<div className="absolute inset-0 bg-gradient-to-r from-black/30 to-transparent" /></div>) : (- <div className="flex-shrink-0 w-[105px] sm:w-[120px] bg-chip flex items-center justify-center">+ <div className="flex-shrink-0 w-[105px] sm:w-[120px] aspect-[2/3] bg-chip flex items-center justify-center"><svg className="w-8 h-8 text-faint" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 4v16m10-16v16M3 6a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1H4a1 1 0 01-1-1V6zm4 0a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1h-1a1 1 0 01-1-1V6zm8 0a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1h-1a1 1 0 01-1-1V6zm4 0a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1h-1a1 1 0 01-1-1V6z" /></svg>@@ -273,12 +277,16 @@ export function DoubanCard({ item, onClick }: { item: { title: string; cover: streturn (<div- className="card cursor-pointer hover:scale-[1.03] hover:shadow-md"+ className="card cursor-pointer hover:scale-[1.03] hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"role="button"tabIndex={0}onClick={onClick}onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') onClick();+ if (e.key === 'Enter' || e.key === ' ') {+ // 阻止空格触发页面滚动(AggregatedCard 已是此写法,此处对齐)+ e.preventDefault();+ onClick();+ }}}><div className="relative aspect-[2/3] bg-chip">@@ -293,13 +301,13 @@ export function DoubanCard({ item, onClick }: { item: { title: string; cover: st/>) : (<div className="w-full h-full flex items-center justify-center bg-chip">- <svg className="w-9 h-9 text-faint" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <svg className="w-8 h-8 text-faint" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 4v16m10-16v16M3 6a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1H4a1 1 0 01-1-1V6zm4 0a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1h-1a1 1 0 01-1-1V6zm8 0a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1h-1a1 1 0 01-1-1V6zm4 0a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1h-1a1 1 0 01-1-1V6z" /></svg></div>)}{item.rating && (- <span className={cn('absolute top-1.5 right-1.5 tag bg-black/70 text-amber-400 font-medium')}>+ <span className={cn('absolute top-1.5 right-1.5 tag bg-black/70 text-rating font-medium')}>★ {item.rating}</span>)}diff --git a/src/lib/client-api.ts b/src/lib/client-api.tsindex 37ec985..13a0dd3 100644--- a/src/lib/client-api.ts+++ b/src/lib/client-api.ts@@ -35,6 +35,9 @@ export interface LiveProbeResult {kbps?: number;}+/** /api/status 的 React Query key:Providers 与 AuthProvider 共用,避免同一页面重复请求 */+export const STATUS_QUERY_KEY = ['app-status'] as const;+export function onUnauthorized(handler: (event: CustomEvent) => void): () => void {const wrapped = (e: Event) => handler(e as CustomEvent);window.addEventListener(UNAUTHORIZED_EVENT, wrapped);@@ -123,11 +126,11 @@ export const api = {return request<DoubanResponse>(`/api/hot-list?${sp.toString()}`, { signal });},- /** 换源:按标题跨源搜索并取详情,附带接口耗时(测速) */- detailSpeed: async (id: string, source: SourceConfig) => {+ /** 换源:按标题跨源搜索并取详情,附带接口耗时(测速);支持 signal 以便关闭弹窗时中止在途请求 */+ detailSpeed: async (id: string, source: SourceConfig, signal?: AbortSignal) => {const start = performance.now();try {- const detail = await api.detail(id, source);+ const detail = await api.detail(id, source, signal);return { ok: true, ms: Math.round(performance.now() - start), detail };} catch (err) {return { ok: false, ms: Math.round(performance.now() - start), detail: undefined as VideoDetail | undefined, error: err instanceof Error ? err.message : '失败' };@@ -148,6 +151,18 @@ export const api = {return request<SourceListPayload>(`/api/source-list?${sp.toString()}`);},+ /** 把源列表发布到公开粘贴板换回订阅链接(走服务端代理:绕开 CORS,且目标域名固定不可控) */+ publishSourceList: (payload: {+ name?: string;+ sources: { name: string; url: string }[];+ liveSources: { name: string; url: string; epg?: string }[];+ }) =>+ request<{ url: string; provider: string; sources: number; liveSources: number }>('/api/publish', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ }),+/** —— 直播 / IPTV —— *//** 拉取并解析 M3U 订阅;force=1 跳过服务端缓存 */diff --git a/src/lib/db.ts b/src/lib/db.tsindex ee4c518..2d15f4b 100644--- a/src/lib/db.ts+++ b/src/lib/db.ts@@ -102,7 +102,8 @@ export async function removeHistory(sourceKey: string, vodId: string): Promise<v}export async function clearAllHistory(): Promise<void> {- await db.history.clear();+ // 一并清进度表:否则从历史重新打开时可能取到已清空的旧进度+ await Promise.all([db.history.clear(), db.progress.clear()]);}export function progressKeyOf(sourceKey: string, vodId: string, episodeIndex: number): string {@@ -142,6 +143,12 @@ export async function clearSearchHistory(): Promise<void> {await db.searchHistory.clear();}+/** 撤销「清空搜索记录」:按原时间戳回填,保持原有顺序 */+export async function restoreSearchHistory(entries: SearchHistoryEntry[]): Promise<void> {+ if (entries.length === 0) return;+ await db.searchHistory.bulkPut(entries);+}+// —— 直播测活缓存(TTL 过滤由调用方负责,本层只管存取) ——export async function loadLiveProbeResults(): Promise<Record<string, LiveProbeEntry>> {diff --git a/src/lib/source-list-publish.test.ts b/src/lib/source-list-publish.test.tsnew file mode 100644index 0000000..1143468--- /dev/null+++ b/src/lib/source-list-publish.test.ts@@ -0,0 +1,72 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { publishSourceList } from './source-list-publish';++/**+ * 发布器单测:多后端依次降级,以及「部分写入」这类必须当失败的边界。+ * fetch 全部 mock,不产生任何真实上传。+ */++const state = vi.hoisted(() => ({+ pasteRs: { status: 201, body: 'https://paste.rs/abc123' },+ zeroX0: { status: 200, body: 'https://0x0.st/xyz.json' },+ calls: [] as string[],+}));++vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ state.calls.push(url);+ if (url.startsWith('https://paste.rs')) {+ return new Response(state.pasteRs.body, { status: state.pasteRs.status });+ }+ if (url.startsWith('https://0x0.st')) {+ return new Response(state.zeroX0.body, { status: state.zeroX0.status });+ }+ return new Response('unexpected target', { status: 500 });+ })+);++beforeEach(() => {+ state.pasteRs = { status: 201, body: 'https://paste.rs/abc123' };+ state.zeroX0 = { status: 200, body: 'https://0x0.st/xyz.json' };+ state.calls = [];+});++describe('publishSourceList', () => {+ it('首选粘贴板成功即返回链接与来源', async () => {+ const result = await publishSourceList('{"a":1}');+ expect(result).toEqual({ url: 'https://paste.rs/abc123', provider: 'paste.rs' });+ // 成功后不应继续尝试后续后端+ expect(state.calls).toHaveLength(1);+ });++ it('206 表示内容被截断,必须当失败并降级到下一个后端', async () => {+ // paste.rs 超出体积上限时返回 206,只写入了一部分;若当成成功会发布出半个 JSON+ state.pasteRs = { status: 206, body: 'https://paste.rs/partial' };+ const result = await publishSourceList('{"a":1}');+ expect(result.provider).toBe('0x0.st');+ expect(result.url).toBe('https://0x0.st/xyz.json');+ expect(state.calls).toEqual(['https://paste.rs/', 'https://0x0.st']);+ });++ it('返回内容不是链接时同样降级', async () => {+ state.pasteRs = { status: 201, body: 'rate limited, try later' };+ const result = await publishSourceList('{"a":1}');+ expect(result.provider).toBe('0x0.st');+ });++ it('全部后端失败时抛出带各自原因的汇总错误', async () => {+ state.pasteRs = { status: 503, body: '' };+ state.zeroX0 = { status: 500, body: '' };+ await expect(publishSourceList('{"a":1}')).rejects.toThrow(/paste\.rs(HTTP 503)/);+ await expect(publishSourceList('{"a":1}')).rejects.toThrow(/0x0\.st(HTTP 500)/);+ });++ it('只向写死的第三方域名发请求', async () => {+ await publishSourceList('{"a":1}');+ for (const url of state.calls) {+ expect(url).toMatch(/^https:\/\/(paste\.rs|0x0\.st)/);+ }+ });+});diff --git a/src/lib/source-list-publish.ts b/src/lib/source-list-publish.tsnew file mode 100644index 0000000..6273553--- /dev/null+++ b/src/lib/source-list-publish.ts@@ -0,0 +1,86 @@+/**+ * 源列表发布:把本站源列表上传到第三方粘贴板,换回一个可直接当订阅地址用的 URL。+ *+ * 之所以必须走服务端:粘贴板的写接口普遍不带 CORS 头,浏览器直连会被拦;+ * 服务端还能顺带限制体积、把目标域名固定死(不给 SSRF 留口子)。+ *+ * 内容会落在公开可读的粘贴板上——这一点只能靠 UI 明确告知用户,技术上无法规避。+ */++export interface PublishResult {+ url: string;+ /** 实际生效的粘贴板名称,便于告知用户「发布到了哪里」 */+ provider: string;+}++/** 内容体积上限:粘贴板普遍限制在数百 KB,而源列表正常只有几 KB */+export const MAX_PUBLISH_BYTES = 256 * 1024;++/** 单个粘贴板的等待上限,避免某个服务卡住把整次发布拖死 */+const TIMEOUT_MS = 15_000;++const USER_AGENT = 'LibreTV/2.11 (+https://github.com/LibreSpark/LibreTV)';++interface Publisher {+ name: string;+ run(text: string, signal: AbortSignal): Promise<string>;+}++/**+ * 依次尝试的粘贴板,前一个失败自动换下一个。+ * 这些都是免费公共服务,随时可能收紧或失效,所以做成「多后端依次降级」而不是写死一家。+ */+const PUBLISHERS: Publisher[] = [+ {+ name: 'paste.rs',+ run: async (text, signal) => {+ const res = await fetch('https://paste.rs/', {+ method: 'POST',+ body: text,+ headers: { 'Content-Type': 'text/plain; charset=utf-8', 'User-Agent': USER_AGENT },+ signal,+ });+ // 201 = 完整写入;206 = 超出服务端体积上限被截断,必须当失败处理,否则会发布出半个 JSON+ if (res.status !== 201) throw new Error(`HTTP ${res.status}`);+ const url = (await res.text()).trim();+ if (!/^https:\/\/paste\.rs\/[\w-]+$/.test(url)) throw new Error('返回内容不是有效链接');+ return url;+ },+ },+ {+ name: '0x0.st',+ run: async (text, signal) => {+ const form = new FormData();+ form.append('file', new Blob([text], { type: 'application/json' }), 'libretv-source-list.json');+ const res = await fetch('https://0x0.st', {+ method: 'POST',+ body: form,+ headers: { 'User-Agent': USER_AGENT },+ signal,+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const url = (await res.text()).trim();+ if (!/^https:\/\/0x0\.st\/[\w.-]+$/.test(url)) throw new Error('返回内容不是有效链接');+ return url;+ },+ },+];++/** 依次尝试各粘贴板;全部失败时抛出带明细的错误,便于用户判断是网络问题还是服务挂了 */+export async function publishSourceList(text: string): Promise<PublishResult> {+ const errors: string[] = [];+ for (const publisher of PUBLISHERS) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);+ try {+ const url = await publisher.run(text, controller.signal);+ return { url, provider: publisher.name };+ } catch (err) {+ const reason = err instanceof Error ? (err.name === 'AbortError' ? '超时' : err.message) : '失败';+ errors.push(`${publisher.name}(${reason})`);+ } finally {+ clearTimeout(timer);+ }+ }+ throw new Error(`发布失败:${errors.join('、')}`);+}diff --git a/src/lib/store.test.ts b/src/lib/store.test.tsindex 7c202d7..9b3eb37 100644--- a/src/lib/store.test.ts+++ b/src/lib/store.test.ts@@ -8,7 +8,7 @@ vi.mock('./db', () => ({saveLiveProbeResults: vi.fn(async () => {}),}));-import { keyBelongsToSubscription, subKeyPrefix, useAppStore } from './store';+import { isInDisabledSubscription, isSourceDisabled, keyBelongsToSubscription, SOURCE_DISABLE_LADDER, subKeyPrefix, useAppStore } from './store';import type { SourceConfig } from './types';const store = () => useAppStore.getState();@@ -245,3 +245,122 @@ describe('可撤销删除与订阅同步状态', () => {expect(store().subscriptions[0].lastCounts).toEqual({ vod: 3, live: 1 });});});++describe('点播源自动停用阶梯', () => {+ const fail = (key: string) => ({ sourceKey: key, ok: false, error: '超时', list: [] });+ const okOutcome = (key: string) => ({ sourceKey: key, ok: true, ms: 12, list: [] });+ /** 连续两次搜索失败(每次搜索各记录一次),返回两次调用产生的停用事件合集 */+ const failTwice = (key: string) => [+ ...store().recordSourceHealth([fail(key)]),+ ...store().recordSourceHealth([fail(key)]),+ ];+ /** 模拟停用到期:把截止时间挪到过去 */+ const expire = (key: string) => {+ const entry = store().sourceHealth[key];+ useAppStore.setState({+ sourceHealth: { ...store().sourceHealth, [key]: { ...entry, disabledUntil: Date.now() - 1 } },+ });+ };++ beforeEach(() => useAppStore.setState({ sourceHealth: {} }));++ it('达到阈值才停用,首次为 30 分钟', () => {+ expect(store().recordSourceHealth([fail('a')])).toEqual([]);+ expect(isSourceDisabled(store(), 'a')).toBe(false);++ const events = failTwice('a');+ expect(events).toHaveLength(1);+ expect(events[0]).toMatchObject({ key: 'a', level: 1, permanent: false, ttlMs: SOURCE_DISABLE_LADDER[0] });+ expect(isSourceDisabled(store(), 'a')).toBe(true);+ });++ it('到期恢复后再次连续失败 → 升级为 24 小时', () => {+ failTwice('a');+ expire('a');+ // 到期即恢复参与搜索(懒判断,无需清理标记)+ expect(isSourceDisabled(store(), 'a')).toBe(false);++ const events = failTwice('a');+ expect(events[0]).toMatchObject({ level: 2, permanent: false, ttlMs: SOURCE_DISABLE_LADDER[1] });+ });++ it('阶梯用尽 → 长期停用,不随到期恢复,须手动清除', () => {+ failTwice('a');+ expire('a');+ failTwice('a');+ expire('a');+ const events = failTwice('a');+ expect(events[0]).toMatchObject({ level: 3, permanent: true });+ expect(events[0].ttlMs).toBeUndefined();++ // 即便把停用时间挪到过去也不会自动恢复+ expire('a');+ expect(isSourceDisabled(store(), 'a')).toBe(true);++ store().clearSourceHealth('a');+ expect(isSourceDisabled(store(), 'a')).toBe(false);+ });++ it('成功一次降一级:偶发抽风的源不会一路升到长期停用', () => {+ failTwice('a'); // 第 1 级+ expire('a');+ failTwice('a'); // 第 2 级+ expire('a');++ store().recordSourceHealth([okOutcome('a')]);+ expect(store().sourceHealth['a'].disableCount).toBe(1);++ const events = failTwice('a');+ expect(events[0]).toMatchObject({ level: 2, permanent: false });+ });++ it('成功后立即清除停用标记与失败连击', () => {+ failTwice('a');+ expect(isSourceDisabled(store(), 'a')).toBe(true);++ store().recordSourceHealth([okOutcome('a')]);+ expect(isSourceDisabled(store(), 'a')).toBe(false);+ expect(store().sourceHealth['a'].failStreak).toBe(0);+ });+});++describe('订阅整体开关', () => {+ const subUrl = 'https://sub.example.com/list.json';+ const otherUrl = 'https://other.example.com/list.json';++ beforeEach(() => {+ useAppStore.setState({ customAPIs: [], selectedKeys: [], subscriptions: [], sourceHealth: {} });+ });++ it('未设置 enabled 的订阅视为启用,不影响其源', () => {+ store().addSubscription(subUrl, 'S');+ expect(store().subscriptions[0].enabled).toBeUndefined();+ expect(isInDisabledSubscription(store(), `${subKeyPrefix(subUrl)}_0`)).toBe(false);+ });++ it('停用订阅仅影响搜索采用:源数据与勾选状态都保留,可无损恢复', () => {+ store().addSubscription(subUrl, 'S');+ const key = `${subKeyPrefix(subUrl)}_0`;+ store().addCustomApi({ key, name: 'A', url: 'https://a.example.com/api.php/provide/vod' });+ store().setSelectedKeys([key]);++ store().setSubscriptionEnabled(subUrl, false);+ expect(isInDisabledSubscription(store(), key)).toBe(true);+ // 关键:无损——源还在、勾选也还在+ expect(store().customAPIs.map((a) => a.key)).toContain(key);+ expect(store().selectedKeys).toContain(key);++ store().setSubscriptionEnabled(subUrl, true);+ expect(isInDisabledSubscription(store(), key)).toBe(false);+ });++ it('只影响本订阅名下的源,其他订阅与手动添加的源不受牵连', () => {+ store().addSubscription(subUrl, 'S');+ store().addSubscription(otherUrl, 'O');+ store().setSubscriptionEnabled(subUrl, false);++ expect(isInDisabledSubscription(store(), `${subKeyPrefix(subUrl)}_1`)).toBe(true);+ expect(isInDisabledSubscription(store(), `${subKeyPrefix(otherUrl)}_1`)).toBe(false);+ expect(isInDisabledSubscription(store(), 'manual_0')).toBe(false);+ });+});diff --git a/src/lib/store.ts b/src/lib/store.tsindex 11d80a8..7136a20 100644--- a/src/lib/store.ts+++ b/src/lib/store.ts@@ -1,7 +1,7 @@'use client';import { create } from 'zustand';-import { persist } from 'zustand/middleware';+import { createJSONStorage, persist, type StateStorage } from 'zustand/middleware';import type { SourceConfig, LiveSourceConfig, SourceSearchOutcome } from './types';import { clearLiveProbeResultsDb, loadLiveProbeResults, saveLiveProbeResults } from './db';@@ -45,6 +45,11 @@ export interface SourceSubscription {lastError?: string;/** 上次成功同步导入的数量统计 */lastCounts?: SubscriptionSyncCounts;+ /**+ * 整体开关:false 表示该订阅下的源暂不参与搜索。+ * 不改动各源自身的勾选状态、也不删除已导入的数据,因此随时可无损恢复。+ */+ enabled?: boolean;}/** 删除点播源后的撤销快照 */@@ -126,10 +131,26 @@ export function keyBelongsToSubscription(key: string, prefix: string): boolean {return key === prefix || key.startsWith(`${prefix}_`);}-/** 点播源自动停用阈值:连续失败/超时达到该次数即临时摘除 */+/** 点播源自动停用阈值:连续失败/超时达到该次数即暂停该源参与搜索 */export const SOURCE_DISABLE_THRESHOLD = 2;-/** 点播源自动停用时长:到期后自动恢复参与搜索 */-export const SOURCE_DISABLE_TTL_MS = 30 * 60 * 1000;+/**+ * 自动停用阶梯(毫秒),按「第几次被自动停用」逐级加重:+ * 固定时长的问题是,彻底挂掉的源会每隔 30 分钟被重新试一次、每次都要白等一轮超时;+ * 而偶发的网络抖动又不该被长期惩罚,所以第 1 级保持得很轻。+ * 下标 i 对应第 i+1 次停用;超出数组长度则进入长期停用(permanent)。+ */+export const SOURCE_DISABLE_LADDER = [30 * 60 * 1000, 24 * 60 * 60 * 1000];++/** 一次「源被自动停用」的事件,供调用方按级别提示 */+export interface SourceDisableEvent {+ key: string;+ /** 本次是第几次被自动停用(从 1 起) */+ level: number;+ /** 是否已进入长期停用(阶梯用尽,需手动恢复) */+ permanent: boolean;+ /** 本次停用时长(毫秒);长期停用时为 undefined */+ ttlMs?: number;+}/** 点播源健康度条目(按 sourceKey),随搜索结果滚动更新 */export interface SourceHealthEntry {@@ -139,8 +160,12 @@ export interface SourceHealthEntry {timedOut?: boolean;/** 连续失败/超时次数;成功时归零 */failStreak: number;- /** 命中阈值后的临时停用截止时间(epoch ms);恢复成功后清除 */+ /** 命中阈值后的停用截止时间(epoch ms);恢复成功后清除 */disabledUntil?: number;+ /** 累计的自动停用等级(决定惩罚时长);每成功一次降一级 */+ disableCount?: number;+ /** 阶梯用尽后的长期停用:不设到期时间,只能由用户手动恢复 */+ permanent?: boolean;timestamp: number;}@@ -180,6 +205,8 @@ interface AppState extends AppSettings {setEnvSources: (list: SourceConfig[]) => void;addSubscription: (url: string, name?: string) => void;removeSubscription: (url: string) => void;+ /** 整体启用/停用某个订阅(停用只影响搜索时是否采用,不动各源的勾选状态) */+ setSubscriptionEnabled: (url: string, enabled: boolean) => void;markSubscriptionSynced: (url: string, name?: string, counts?: SubscriptionSyncCounts) => void;/** 记录一次同步失败(保留该订阅与已导入的源,仅更新状态供列表展示) */markSubscriptionFailed: (url: string, error: string) => void;@@ -207,12 +234,14 @@ interface AppState extends AppSettings {setLiveProbeResults: (entries: Record<string, LiveProbeEntry>) => void;clearLiveProbeResults: () => void;/**- * 记录一次搜索的逐源健康度;连续失败/超时达到阈值即标记临时停用。+ * 记录一次搜索的逐源健康度;连续失败/超时达到阈值即暂停该源参与搜索。+ * 停用时长按阶梯逐级加重(30 分钟 → 24 小时 → 长期停用),且每成功一次降一级:+ * 偶发抽风的源会自行回落,从未成功过的死源才会升到长期停用。* 不直接改 selectedKeys(用户勾选意图保留,且避免变更引用触发搜索重发),- * 参与搜索与否由调用方经 isSourceDisabled 过滤;到期自动恢复。- * 返回本次新被自动停用的源 key 列表(供调用方 toast 提示)。+ * 参与搜索与否由调用方经 isSourceDisabled 过滤。+ * 返回本次「新进入停用」的事件列表(供调用方按级别 toast 提示)。*/- recordSourceHealth: (outcomes: SourceSearchOutcome[]) => string[];+ recordSourceHealth: (outcomes: SourceSearchOutcome[]) => SourceDisableEvent[];/** 清除单个源的健康度记录(手动恢复入口) */clearSourceHealth: (key: string) => void;markEnvSubsSeen: (urls: string[]) => void;@@ -231,6 +260,59 @@ function nextCustomKey(apiList: SourceConfig[]): string {return `custom_${i}`;}+/**+ * 节流写入的 localStorage 包装。+ * 搜索会逐源写健康度、测活每 200ms 合并写回,这些都会触发 persist 的整份序列化 + 写盘;+ * 这里把写入合并为 800ms 一次,并在页面隐藏/卸载时立即 flush,确保不丢最后一次修改。+ */+function createThrottledStorage(): StateStorage {+ let timer: ReturnType<typeof setTimeout> | null = null;+ let pending: [string, string] | null = null;++ const flush = () => {+ if (timer) {+ clearTimeout(timer);+ timer = null;+ }+ if (!pending) return;+ const [key, value] = pending;+ pending = null;+ try {+ localStorage.setItem(key, value);+ } catch {+ // 配额不足 / 隐私模式下静默放弃持久化,内存态仍可用+ }+ };++ if (typeof window !== 'undefined') {+ window.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'hidden') flush();+ });+ window.addEventListener('beforeunload', flush);+ }++ return {+ getItem: (name) => {+ try {+ return localStorage.getItem(name);+ } catch {+ return null;+ }+ },+ setItem: (name, value) => {+ pending = [name, value];+ if (!timer) timer = setTimeout(flush, 800);+ },+ removeItem: (name) => {+ try {+ localStorage.removeItem(name);+ } catch {+ // 忽略+ }+ },+ };+}+export const useAppStore = create<AppState>()(persist((set, get) => ({@@ -373,6 +455,12 @@ export const useAppStore = create<AppState>()(});},+ setSubscriptionEnabled: (url, enabled) => {+ set({+ subscriptions: get().subscriptions.map((s) => (s.url === url ? { ...s, enabled } : s)),+ });+ },+markSubscriptionFailed: (url, error) => {// 失败不清空已导入的源(旧数据保留),仅记录状态供列表展示set({@@ -576,34 +664,55 @@ export const useAppStore = create<AppState>()(if (outcomes.length === 0) return [];const now = Date.now();const health: Record<string, SourceHealthEntry> = {};- // 顺带清理陈旧条目(停用 TTL 早已过期的死记录)+ // 顺带清理陈旧条目:超过 7 天没再参与过搜索的源,其惩罚等级一并作废for (const [key, e] of Object.entries(get().sourceHealth)) {if (now - e.timestamp < 7 * 24 * 60 * 60 * 1000) health[key] = e;}- const newlyDisabled: string[] = [];+ const events: SourceDisableEvent[] = [];for (const o of outcomes) {const prev = health[o.sourceKey];- const failStreak = o.ok ? 0 : (prev?.failStreak ?? 0) + 1;- // entry 直接覆盖旧记录:成功时 disabledUntil 随之消失(立即恢复),- // 未达阈值时保留旧停用标记不动+ // 停用期已过 → 上一次的连续失败已被「停用 + 恢复」打断,重新从 1 开始累计+ const interrupted = !!prev?.disabledUntil && prev.disabledUntil <= now;+ const failStreak = o.ok ? 0 : interrupted ? 1 : (prev?.failStreak ?? 0) + 1;+ // 成功一次即降一级(而非清零):偶发抽风的源会自己降回来,+ // 从未成功过的死源才会一路升到长期停用+ const disableCount = o.ok+ ? Math.max(0, (prev?.disableCount ?? 0) - 1)+ : (prev?.disableCount ?? 0);+ // entry 覆盖旧记录:成功时停用标记随之消失(立即恢复)const entry: SourceHealthEntry = {ok: o.ok,ms: o.ms,error: o.error,timedOut: o.timedOut,failStreak,+ disableCount,timestamp: now,};if (!o.ok && failStreak >= SOURCE_DISABLE_THRESHOLD) {- entry.disabledUntil = now + SOURCE_DISABLE_TTL_MS;- if (!prev?.disabledUntil || prev.disabledUntil < now) {- newlyDisabled.push(o.sourceKey);+ const alreadyDisabled = prev?.permanent === true || (prev?.disabledUntil ?? 0) > now;+ if (alreadyDisabled) {+ // 已在停用期内(正常不会参与搜索,此处仅作防御):保持原等级与截止时间+ entry.disableCount = prev?.disableCount ?? disableCount;+ entry.disabledUntil = prev?.disabledUntil;+ entry.permanent = prev?.permanent;+ } else {+ // 第 N 次被停用 → 取阶梯第 N 级;阶梯用尽则进入长期停用+ const nextLevel = disableCount + 1;+ const ttlMs: number | undefined = SOURCE_DISABLE_LADDER[nextLevel - 1];+ entry.disableCount = nextLevel;+ if (ttlMs === undefined) {+ entry.permanent = true;+ } else {+ entry.disabledUntil = now + ttlMs;+ }+ events.push({ key: o.sourceKey, level: nextLevel, permanent: ttlMs === undefined, ttlMs });}}health[o.sourceKey] = entry;}set({ sourceHealth: health });- return newlyDisabled;+ return events;},clearSourceHealth: (key) => {@@ -637,6 +746,8 @@ export const useAppStore = create<AppState>()(}),{name: 'libretv-settings',+ // 节流写入:搜索 / 测活等高频 set 不再每次都整份序列化写盘+ storage: createJSONStorage(createThrottledStorage),// v1:直播源新增归属字段、最近观看新增 sourceUrl。// v2:直播源归属改为多引用(fromSubscription 单值 → fromSubscriptions 数组)。// 此前未声明 version 的存量数据会被视为 v0 并走 migrate 补齐。@@ -740,7 +851,8 @@ export function resolveSource(/*** 源当前是否处于自动停用期(连续超时/失败触发)。- * 停用到期后此判断自然翻转为 false,即「到期自动恢复参与搜索」的懒实现。+ * 临时停用到期后此判断自然翻转为 false,即「到期自动恢复参与搜索」的懒实现;+ * 长期停用(阶梯用尽)没有到期时间,只有手动恢复(clearSourceHealth)才能解除。*/export function isSourceDisabled(state: Pick<AppState, 'sourceHealth'>,@@ -748,5 +860,20 @@ export function isSourceDisabled(now = Date.now()): boolean {const e = state.sourceHealth[key];- return !!e?.disabledUntil && e.disabledUntil > now;+ if (!e) return false;+ return e.permanent === true || (!!e.disabledUntil && e.disabledUntil > now);+}++/**+ * 源是否来自一个被用户整体停用的订阅。+ * 与 isSourceDisabled 分开判断:一个是用户主动关的、一个是系统按连续失败关的,+ * 提示文案与恢复方式都不同,混在一起用户就看不懂源为什么不生效了。+ */+export function isInDisabledSubscription(+ state: Pick<AppState, 'subscriptions'>,+ key: string+): boolean {+ return state.subscriptions.some(+ (s) => s.enabled === false && keyBelongsToSubscription(key, subKeyPrefix(s.url))+ );}diff --git a/src/lib/utils.ts b/src/lib/utils.tsindex 297b32a..7f40d23 100644--- a/src/lib/utils.ts+++ b/src/lib/utils.ts@@ -23,6 +23,12 @@ export function formatRelativeTime(timestamp: number): string {return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;}+/** 停用时长的可读文案:不足 1 小时按分钟,超过按小时(按剩余时间展示时向上取整) */+export function formatDisableTtl(ms: number): string {+ const minutes = Math.max(1, Math.ceil(ms / 60_000));+ return minutes >= 60 ? `${Math.round(minutes / 60)} 小时` : `${minutes} 分钟`;+}+export async function sha256Hex(input: string): Promise<string> {const buffer = new TextEncoder().encode(input);const hash = await crypto.subtle.digest('SHA-256', buffer);diff --git a/tailwind.config.ts b/tailwind.config.tsindex 5981716..781300e 100644--- a/tailwind.config.ts+++ b/tailwind.config.ts@@ -26,6 +26,22 @@ const config: Config = {DEFAULT: 'rgb(var(--c-accent) / <alpha-value>)',hover: 'rgb(var(--c-accent-hover) / <alpha-value>)',},+ // 语义状态色:随亮/暗主题切换,替代直接使用 red/green/amber 等调色板+ danger: {+ DEFAULT: 'rgb(var(--c-danger) / <alpha-value>)',+ hover: 'rgb(var(--c-danger-hover) / <alpha-value>)',+ },+ success: 'rgb(var(--c-success) / <alpha-value>)',+ warning: 'rgb(var(--c-warning) / <alpha-value>)',+ info: 'rgb(var(--c-info) / <alpha-value>)',+ rating: 'rgb(var(--c-rating) / <alpha-value>)',+ // accent 实心底上的文字色:亮色=白、暗色=深(霓虹蓝底对白字对比度不足)+ 'on-accent': 'rgb(var(--c-on-accent) / <alpha-value>)',+ // 实心状态底色(配白字),比语义色更深一档保证对比度+ 'danger-solid': 'rgb(var(--c-danger-solid) / <alpha-value>)',+ 'success-solid': 'rgb(var(--c-success-solid) / <alpha-value>)',+ 'warning-solid': 'rgb(var(--c-warning-solid) / <alpha-value>)',+ 'info-solid': 'rgb(var(--c-info-solid) / <alpha-value>)',},keyframes: {'fade-in': { from: { opacity: '0' }, to: { opacity: '1' } },