Skip to content

一分钟搭建影视站,支持Docker等部署方式

feat(settings): 设置抽屉两级导航与源管理统一重构(搜索/批量/筛选/批量测活/撤销/分级确认),版本 2.11.0

bestZwei1bc705021c62
diff --git a/README.md b/README.md
index 04ed08b..e357e6d 100644
--- a/README.md
+++ b/README.md
@@ -91,15 +91,15 @@ PASSWORD=your-password npm start # 监听 8080
## 使用说明
-1. **添加点播源**:设置 → 点播源 → 添加 API,填入 Apple CMS 采集站地址(如 `https://example.com/api.php/provide/vod`),可选填详情页地址(部分源需要爬详情页提取播放地址)。
+1. **添加点播源**:设置 → 源管理 → 点播源 → 添加 API,填入 Apple CMS 采集站地址(如 `https://example.com/api.php/provide/vod`),可选填详情页地址(部分源需要爬详情页提取播放地址)。
2. **搜索**:勾选点播源后输入片名;搜索通过服务端聚合,个别源失败不影响整体结果。
3. **播放**:详情弹窗选择剧集进入 `/watch`;支持快捷键(空格/←→/↑↓/F/Alt+←→)、移动端长按 3 倍速、自动连播、换源测速。
4. **进度与历史**:自动保存在本设备 IndexedDB,仅定位信息入库,播放时自动同步最新剧集。
-5. **配置迁移**:设置 → 导出/导入配置(兼容旧版 LibreTV-Settings JSON 的历史记录迁移)。
+5. **配置迁移**:设置 → 数据 → 配置导入导出(兼容旧版 LibreTV-Settings JSON 的历史记录迁移)。
## 直播 / IPTV
-1. **添加直播源**:设置 → 直播源 → 填入 M3U/M3U8 地址(可选填 XMLTV 节目单地址),添加后自动探活并显示频道数量;也可在「订阅与配置 → 数据源订阅」中与点播源一起订阅导入;部署者还可用 `DEFAULT_LIVE_SOURCES` 环境变量预置。
+1. **添加直播源**:设置 → 源管理 → 直播源 → 填入 M3U/M3U8 地址(可选填 XMLTV 节目单地址),添加后自动探活并显示频道数量;也可在「源管理 → 数据源订阅」中与点播源一起订阅导入;部署者还可用 `DEFAULT_LIVE_SOURCES` 环境变量预置。
2. **观看**:进入「直播」页,按分组标签筛选或搜索频道,点击即播;支持 HLS(m3u8)与 HTTP-FLV 两种直播流,直连失败自动走代理通道重试。
3. **节目单**:频道带 `tvg-id` 且订阅配置了 EPG 地址时,展示当前/接下来节目与播放进度。
4. **收藏与导出**:频道可收藏;订阅可一键导出为标准 M3U 文件,供 PotPlayer / VLC 等外部播放器使用。
@@ -108,7 +108,7 @@ PASSWORD=your-password npm start # 监听 8080
## 数据源订阅 / 分享
-数据源(点播源 + 直播源)可以 **导出为一份 JSON → 托管到公开 URL → 他人在「设置 → 订阅与配置 → 数据源订阅」里填入该 URL 订阅**。
+数据源(点播源 + 直播源)可以 **导出为一份 JSON → 托管到公开 URL → 他人在「设置 → 源管理 → 数据源订阅」里填入该 URL 订阅**。
托管地址没有特殊要求,可用 [npoint.io](https://www.npoint.io/) 免费托管 JSON(粘贴内容即可得到一个公开 URL),Gist、对象存储、任意静态托管同样可用。
@@ -145,10 +145,10 @@ PASSWORD=your-password npm start # 监听 8080
### 订阅行为
-- **订阅**:设置 → 订阅与配置 → 数据源订阅 → 填入订阅地址 → 「订阅」,导入的点播源自动勾选、直播源自动启用,均带「订阅」标识,条目上显示「点播 N · 直播 M」;
+- **订阅**:设置 → 源管理 → 数据源订阅 → 填入订阅地址 → 「订阅」,导入的点播源自动勾选、直播源自动启用,均带「订阅」标识,条目上显示「点播 N · 直播 M」;
- **同步**:订阅条目上的 **⟳** 手动强制同步,整体替换该订阅名下的点播源与直播源;
- **管理边界**:订阅源以远端列表为准,单独编辑会在下次同步时被覆盖,单独移除会在重新同步时恢复;如需调整请改远端列表,或直接删除整个订阅。删除订阅时点播源全部移除;直播源为**多归属共享**——同一 M3U 可被多个订阅引用(名称/EPG 以首次导入为准),删除只移除自己的引用,仅当不再被任何订阅引用时才移除该源,**收藏的频道始终保留**;
-- **导出分享**:设置 → 订阅与配置 → 数据源订阅 → 「导出数据源」,把当前全部点播源与直播源(预置 + 手动 + 订阅,按 URL 去重)导出为上述 JSON。
+- **导出分享**:设置 → 源管理 → 数据源订阅 → 「导出数据源」,把当前全部点播源与直播源(预置 + 手动 + 订阅,按 URL 去重)导出为上述 JSON。
> 订阅由服务端拉取(经过 SSRF 校验),因此订阅地址无需配置 CORS。完整说明见 [数据源文档](https://github.com/bestZwei/LibreTV-Next/wiki/Data-Sources)。
diff --git a/package.json b/package.json
index 3672f6f..09426ec 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "libretv",
- "version": "2.10.2",
+ "version": "2.11.0",
"private": true,
"description": "免费在线视频搜索与观看平台(Next.js 重构版)",
"license": "AGPL-3.0-or-later",
diff --git a/src/components/confirm-dialog.tsx b/src/components/confirm-dialog.tsx
new file mode 100644
index 0000000..11d34fe
--- /dev/null
+++ b/src/components/confirm-dialog.tsx
@@ -0,0 +1,92 @@
+'use client';
+
+import { useEffect, useRef, type ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+
+/**
+ * 破坏性操作确认弹窗(分级确认中的「重操作」):
+ * 删除整个订阅、导入配置覆盖全部数据、清空观看历史等不可逆或影响面大的操作,
+ * 先弹出确认并说明影响面;轻操作(删单个源/单条历史)改用 Toast 撤销(Undo)。
+ */
+
+export function ConfirmDialog({
+ open,
+ title,
+ message,
+ confirmLabel = '确认',
+ cancelLabel = '取消',
+ danger = false,
+ onConfirm,
+ onCancel,
+}: {
+ open: boolean;
+ title: string;
+ message?: ReactNode;
+ confirmLabel?: string;
+ cancelLabel?: string;
+ /** 危险操作:确认按钮用红色,且默认焦点落在取消上,避免误回车 */
+ danger?: boolean;
+ onConfirm: () => void;
+ onCancel: () => void;
+}) {
+ const confirmRef = useRef<HTMLButtonElement>(null);
+ const cancelRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ // 危险操作默认聚焦「取消」,回车不会误触破坏性动作
+ (danger ? cancelRef : confirmRef).current?.focus();
+ const handler = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ onCancel();
+ } else if (e.key === 'Enter' && !danger) {
+ e.preventDefault();
+ onConfirm();
+ }
+ };
+ window.addEventListener('keydown', handler);
+ return () => window.removeEventListener('keydown', handler);
+ }, [open, danger, onCancel, onConfirm]);
+
+ useEffect(() => {
+ if (!open) return;
+ const prev = document.body.style.overflow;
+ document.body.style.overflow = 'hidden';
+ return () => {
+ document.body.style.overflow = prev;
+ };
+ }, [open]);
+
+ if (!open) return null;
+
+ return (
+ <div className="fixed inset-0 z-[80] flex items-center justify-center p-4">
+ <div className="absolute inset-0 bg-black/70 animate-fade-in" onClick={onCancel} aria-hidden />
+ <div
+ role="alertdialog"
+ aria-modal="true"
+ aria-label={title}
+ className="relative bg-surface-raised rounded-xl w-full max-w-sm shadow-2xl p-5 animate-slide-up"
+ >
+ <h2 className="text-base font-semibold text-content mb-2">{title}</h2>
+ {message && <div className="text-sm text-muted leading-relaxed">{message}</div>}
+ <div className="flex gap-2 justify-end mt-5">
+ <button ref={cancelRef} className="btn-ghost text-sm" onClick={onCancel}>
+ {cancelLabel}
+ </button>
+ <button
+ ref={confirmRef}
+ className={cn(
+ 'btn text-sm text-white',
+ danger ? 'bg-red-500 hover:bg-red-600' : 'bg-accent hover:bg-accent-hover'
+ )}
+ onClick={onConfirm}
+ >
+ {confirmLabel}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/drawer.tsx b/src/components/drawer.tsx
new file mode 100644
index 0000000..a2be510
--- /dev/null
+++ b/src/components/drawer.tsx
@@ -0,0 +1,175 @@
+'use client';
+
+import { useEffect, useRef, useState, type ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+import { Icon } from './icon';
+
+/**
+ * 通用右侧抽屉骨架:
+ * - 布局为 flex 纵向三段(标题栏 / 可选副标题栏 / 内容区),只有内容区滚动,
+ * 调用方无需再用 sticky + 魔法数字偏移去贴标题栏;
+ * - 打开时锁定 body 滚动,关闭后归还焦点,Tab 键在抽屉内循环(focus trap);
+ * - 带进入/退出过渡(水平滑入 + 遮罩淡入),退出动画结束后才卸载内容。
+ */
+
+/** 退出过渡时长,需与下方 duration-200 保持一致 */
+const EXIT_MS = 200;
+
+/** 抽屉内可聚焦元素选择器 */
+const FOCUSABLE =
+ 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
+
+export function Drawer({
+ open,
+ onClose,
+ title,
+ children,
+ width = 'max-w-md',
+ subheader,
+ closeOnOverlay = true,
+ resetScrollKey,
+}: {
+ open: boolean;
+ onClose: () => void;
+ title: string;
+ children: ReactNode;
+ /** 抽屉最大宽度类(如 max-w-lg) */
+ width?: string;
+ /** 固定在标题栏下方的非滚动区(如 Tab 条),随抽屉一起保持可见 */
+ subheader?: ReactNode;
+ /** 点击遮罩是否关闭(默认 true) */
+ closeOnOverlay?: boolean;
+ /** 该值变化时内容区滚回顶部(如切换设置分组 / 面板) */
+ resetScrollKey?: string;
+}) {
+ const [mounted, setMounted] = useState(open);
+ const [entered, setEntered] = useState(false);
+ const panelRef = useRef<HTMLDivElement>(null);
+ const contentRef = useRef<HTMLDivElement>(null);
+ const restoreFocusRef = useRef<HTMLElement | null>(null);
+
+ // 切换面板时滚回顶部:新面板不应继承上一个面板的滚动位置
+ useEffect(() => {
+ if (contentRef.current) contentRef.current.scrollTop = 0;
+ }, [resetScrollKey]);
+
+ // 进入:先挂载(保持 slide-out 初态)再于下一帧切换为进入态,触发过渡
+ // 退出:先回到初态,过渡结束后卸载并归还焦点
+ useEffect(() => {
+ if (open) {
+ restoreFocusRef.current = document.activeElement as HTMLElement | null;
+ setMounted(true);
+ const raf = requestAnimationFrame(() => requestAnimationFrame(() => setEntered(true)));
+ return () => cancelAnimationFrame(raf);
+ }
+ setEntered(false);
+ const timer = setTimeout(() => {
+ setMounted(false);
+ restoreFocusRef.current?.focus?.();
+ restoreFocusRef.current = null;
+ }, EXIT_MS);
+ return () => clearTimeout(timer);
+ }, [open]);
+
+ // 打开期间锁定背景滚动(移动端可避免滚动穿透)
+ useEffect(() => {
+ if (!mounted) return;
+ const prev = document.body.style.overflow;
+ document.body.style.overflow = 'hidden';
+ return () => {
+ document.body.style.overflow = prev;
+ };
+ }, [mounted]);
+
+ // 打开后把焦点移入抽屉,保证键盘用户不从背景页开始
+ useEffect(() => {
+ if (!mounted) return;
+ const panel = panelRef.current;
+ if (!panel) return;
+ const first = panel.querySelector<HTMLElement>(FOCUSABLE);
+ (first ?? panel).focus();
+ }, [mounted]);
+
+ // Esc 关闭 + Tab 循环(焦点不逃逸到背景页面)
+ useEffect(() => {
+ if (!mounted) return;
+ const handler = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ // 抽屉内若有确认弹窗等上层对话框(role=alertdialog),Esc 交给它处理,避免一并关闭抽屉
+ if (document.querySelector('[role="alertdialog"]')) return;
+ e.stopPropagation();
+ onClose();
+ return;
+ }
+ if (e.key !== 'Tab') return;
+ const panel = panelRef.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 active = document.activeElement;
+ if (e.shiftKey) {
+ if (active === first || !panel.contains(active)) {
+ e.preventDefault();
+ last.focus();
+ }
+ } else if (active === last || !panel.contains(active)) {
+ e.preventDefault();
+ first.focus();
+ }
+ };
+ window.addEventListener('keydown', handler);
+ return () => window.removeEventListener('keydown', handler);
+ }, [mounted, onClose]);
+
+ if (!mounted) return null;
+
+ return (
+ <div className="fixed inset-0 z-50">
+ <div
+ className={cn(
+ 'absolute inset-0 bg-black/60 transition-opacity duration-200',
+ entered ? 'opacity-100' : 'opacity-0'
+ )}
+ onClick={closeOnOverlay ? onClose : undefined}
+ aria-hidden
+ />
+ <div
+ ref={panelRef}
+ role="dialog"
+ aria-modal="true"
+ aria-label={title}
+ tabIndex={-1}
+ className={cn(
+ 'absolute right-0 top-0 h-full w-full bg-surface-raised border-l border-line flex flex-col outline-none',
+ 'transition-transform duration-200 ease-out',
+ width,
+ 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">
+ <h2 className="font-semibold text-content">{title}</h2>
+ <button
+ className="p-1.5 rounded-md text-muted hover:text-content hover:bg-hover transition-colors"
+ onClick={onClose}
+ aria-label="关闭"
+ >
+ <Icon name="close" />
+ </button>
+ </div>
+ {subheader && <div className="shrink-0 px-4 py-2.5 border-b border-line bg-surface-raised">{subheader}</div>}
+ {/* 唯一滚动区:内容再长也只在这一层滚动,避免与列表内滚形成嵌套滚动 */}
+ <div ref={contentRef} className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-4 pt-4 pb-6">
+ {children}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/header.tsx b/src/components/header.tsx
index 376d7a8..02d1d86 100644
--- a/src/components/header.tsx
+++ b/src/components/header.tsx
@@ -1,11 +1,12 @@
'use client';
import Link from 'next/link';
-import { useEffect, useRef, useState } from 'react';
+import { useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { ThemeToggle } from './theme';
import { SourceManagerDrawer } from './source-manager';
import { HistoryPanel } from './history-panel';
+import { Icon } from './icon';
import { cn } from '@/lib/utils';
/** 顶部导航:Logo、搜索框(首页外)、历史、设置 */
@@ -54,15 +55,10 @@ export function Header({ showSearch = false }: { showSearch?: boolean }) {
</HeaderLink>
<ThemeToggle />
<IconButton label="观看历史" onClick={() => setHistoryOpen(true)}>
- <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
- </svg>
+ <Icon name="clock" />
</IconButton>
<IconButton label="设置" onClick={() => setSettingsOpen(true)}>
- <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
- </svg>
+ <Icon name="gear" />
</IconButton>
</nav>
</div>
@@ -100,58 +96,3 @@ function IconButton({ label, onClick, children }: { label: string; onClick: () =
</button>
);
}
-
-/** 面板通用骨架:右侧抽屉 */
-export function Drawer({
- open,
- onClose,
- title,
- children,
- width = 'max-w-md',
-}: {
- open: boolean;
- onClose: () => void;
- title: string;
- children: React.ReactNode;
- width?: string;
-}) {
- const ref = useRef<HTMLDivElement>(null);
- useEffect(() => {
- if (!open) return;
- const handler = (e: KeyboardEvent) => {
- if (e.key === 'Escape') onClose();
- };
- window.addEventListener('keydown', handler);
- return () => window.removeEventListener('keydown', handler);
- }, [open, onClose]);
-
- if (!open) return null;
- return (
- <div className="fixed inset-0 z-50">
- <div className="absolute inset-0 bg-black/60 animate-fade-in" onClick={onClose} />
- <div
- ref={ref}
- className={cn(
- 'absolute right-0 top-0 h-full w-full bg-surface-raised border-l border-line overflow-y-auto scrollbar-thin animate-slide-up',
- width
- )}
- role="dialog"
- aria-label={title}
- >
- <div className="sticky top-0 bg-surface-raised px-4 py-3.5 border-b border-line flex items-center justify-between z-10">
- <h2 className="font-semibold text-content">{title}</h2>
- <button
- className="p-1.5 rounded-md text-muted hover:text-content hover:bg-hover"
- onClick={onClose}
- aria-label="关闭"
- >
- <svg className="w-5 h-5" 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>
- <div className="p-4">{children}</div>
- </div>
- </div>
- );
-}
diff --git a/src/components/history-panel.tsx b/src/components/history-panel.tsx
index bbded92..7cbab5e 100644
--- a/src/components/history-panel.tsx
+++ b/src/components/history-panel.tsx
@@ -3,7 +3,8 @@
import { useState } from 'react';
import { useLiveQuery } from 'dexie-react-hooks';
import Link from 'next/link';
-import { Drawer } from './header';
+import { Drawer } from './drawer';
+import { ConfirmDialog } from './confirm-dialog';
import { db, clearAllHistory, removeHistory, upsertHistory, type HistoryEntry } from '@/lib/db';
import { buildWatchUrl, buildImageUrl, cn, formatRelativeTime, formatTime } from '@/lib/utils';
import { useToast } from './toast';
@@ -12,11 +13,13 @@ import { resolveSource, useAppStore } from '@/lib/store';
/**
* 观看历史面板(IndexedDB 实时查询)。
* 与旧版的区别:播放前按需重新拉取剧集详情,不再依赖历史记录里冗余存储的全集 URL。
+ * 破坏性操作分级:清空全部走确认弹窗,删除单条支持撤销。
*/
export function HistoryPanel({ open, onClose }: { open: boolean; onClose: () => void }) {
const history = useLiveQuery(() => db.history.orderBy('timestamp').reverse().limit(50).toArray(), [open]);
const { toast } = useToast();
+ const [confirmClear, setConfirmClear] = useState(false);
return (
<Drawer open={open} onClose={onClose} title="观看历史" width="max-w-lg">
@@ -29,9 +32,7 @@ export function HistoryPanel({ open, onClose }: { open: boolean; onClose: () =>
<div className="flex justify-end mb-2">
<button
className="text-xs text-faint hover:text-red-400 transition-colors"
- onClick={() => {
- clearAllHistory().then(() => toast('观看历史已清空', 'success'));
- }}
+ onClick={() => setConfirmClear(true)}
>
清空历史
</button>
@@ -43,6 +44,20 @@ export function HistoryPanel({ open, onClose }: { open: boolean; onClose: () =>
</ul>
</>
)}
+
+ {/* 重操作:清空不可撤销,先确认并说明数量 */}
+ <ConfirmDialog
+ open={confirmClear}
+ danger
+ title="清空全部观看历史?"
+ message={history ? `将删除 ${history.length} 条观看记录,此操作不可撤销。` : undefined}
+ confirmLabel="清空"
+ onCancel={() => setConfirmClear(false)}
+ onConfirm={() => {
+ void clearAllHistory().then(() => toast('观看历史已清空', 'success'));
+ setConfirmClear(false);
+ }}
+ />
</Drawer>
);
}
@@ -66,6 +81,31 @@ function HistoryItem({ item }: { item: HistoryEntry }) {
detail: resolveSource(store, item.sourceKey)?.detail,
});
+ const remove = () => {
+ void removeHistory(item.sourceKey, item.vodId).then(() => {
+ // 轻操作:给撤销窗口,恢复时写回原记录
+ toast('已删除该记录', 'info', {
+ action: {
+ label: '撤销',
+ onClick: () => {
+ void upsertHistory({
+ sourceKey: item.sourceKey,
+ sourceUrl: item.sourceUrl,
+ vodId: item.vodId,
+ title: item.title,
+ pic: item.pic,
+ episodeIndex: item.episodeIndex,
+ totalEpisodes: item.totalEpisodes,
+ playbackPosition: item.playbackPosition,
+ duration: item.duration,
+ timestamp: item.timestamp,
+ }).then(() => toast('已恢复', 'success'));
+ },
+ },
+ });
+ });
+ };
+
return (
<li className="relative group">
<Link
@@ -114,10 +154,8 @@ function HistoryItem({ item }: { item: HistoryEntry }) {
'opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity'
)}
aria-label="删除记录"
- title="删除记录"
- onClick={() => {
- removeHistory(item.sourceKey, item.vodId).then(() => toast('已删除该记录', 'success'));
- }}
+ title="删除记录(可在提示中撤销)"
+ onClick={remove}
>
<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" />
diff --git a/src/components/icon.tsx b/src/components/icon.tsx
new file mode 100644
index 0000000..3e2e4fe
--- /dev/null
+++ b/src/components/icon.tsx
@@ -0,0 +1,139 @@
+import type { ReactNode } from 'react';
+
+/**
+ * 统一图标集(Heroicons outline 风格,24×24 线性)。
+ * 替代此前散落在各处的 Unicode 符号(✎ ✕ ⟳ ⚡ ⇩):同一笔画粗细与网格,
+ * 不会因字体/平台不同而粗细不一,与顶部导航的图标风格保持一致。
+ */
+
+export type IconName =
+ | 'close'
+ | 'edit'
+ | 'refresh'
+ | 'bolt'
+ | 'download'
+ | 'chevronDown'
+ | 'plus'
+ | 'search'
+ | 'clock'
+ | 'check'
+ | 'undo'
+ | 'trash'
+ | 'filter'
+ | 'link'
+ | 'alert'
+ | 'gear';
+
+const PATHS: Record<IconName, ReactNode> = {
+ close: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />,
+ edit: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L6.832 19.82a4.5 4.5 0 0 1-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 0 1 1.13-1.897L16.863 4.487Zm0 0L19.5 7.125"
+ />
+ ),
+ refresh: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99"
+ />
+ ),
+ bolt: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="m3.75 13.5 10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75Z"
+ />
+ ),
+ download: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"
+ />
+ ),
+ chevronDown: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="m19.5 8.25-7.5 7.5-7.5-7.5" />,
+ plus: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.5v15m7.5-7.5h-15" />,
+ search: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"
+ />
+ ),
+ clock: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
+ />
+ ),
+ check: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="m4.5 12.75 6 6 9-13.5" />,
+ undo: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M9 15 3 9m0 0 6-6M3 9h12a6 6 0 0 1 0 12h-3"
+ />
+ ),
+ trash: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"
+ />
+ ),
+ filter: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 3c2.755 0 5.455.232 8.083.678.533.09.917.556.917 1.096v1.044a2.25 2.25 0 0 1-.659 1.591l-5.432 5.432a2.25 2.25 0 0 0-.659 1.591v2.927a2.25 2.25 0 0 1-1.244 2.013L9.75 21v-6.568a2.25 2.25 0 0 0-.659-1.591L3.659 7.409A2.25 2.25 0 0 1 3 5.818V4.774c0-.54.384-1.006.917-1.096A48.32 48.32 0 0 1 12 3Z"
+ />
+ ),
+ link: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244"
+ />
+ ),
+ alert: (
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z"
+ />
+ ),
+ gear: (
+ <>
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 0 0-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 0 0-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 0 0-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 0 0-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 0 0 1.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065Z"
+ />
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
+ </>
+ ),
+};
+
+export function Icon({ name, className = 'w-5 h-5' }: { name: IconName; className?: string }) {
+ return (
+ <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
+ {PATHS[name]}
+ </svg>
+ );
+}
diff --git a/src/components/live-source-manager.tsx b/src/components/live-source-manager.tsx
index 9659566..472a1b1 100644
--- a/src/components/live-source-manager.tsx
+++ b/src/components/live-source-manager.tsx
@@ -1,235 +1,362 @@
'use client';
-import { useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { useAppStore } from '@/lib/store';
import { useToast } from './toast';
import { api } from '@/lib/client-api';
-import { formatRelativeTime, validateSourceUrl, cn } from '@/lib/utils';
+import { formatRelativeTime, hostnameOf, validateSourceUrl, cn } from '@/lib/utils';
+import { EmptyState, SearchInput, SectionTitle, TestBadge, useSourceTests } from './settings-shared';
+import { Icon } from './icon';
/**
- * 直播源管理(嵌入设置抽屉):M3U 订阅的添加 / 探活 / 同步 / 移除 / 导出,
- * 以及部署者预置源展示。模式对齐采集站的 SourceSubscriptions。
+ * 直播源管理(嵌入设置抽屉):M3U 订阅的添加 / 探活 / 移除 / 导出,
+ * 以及部署者预置源展示。工具条、徽章、空态与撤销语义与点播源面板保持一致。
*/
-type TestState =
- | { status: 'loading' }
- | { status: 'done'; ok: boolean; ms?: number; count?: number; error?: string };
-
-/** 取 hostname 作为名称兜底;地址非法时原样返回 */
-function hostnameOf(url: string): string {
- try {
- return new URL(url).hostname;
- } catch {
- return url;
- }
+type LiveFilter = 'all' | 'enabled' | 'disabled' | 'sub' | 'manual';
+
+// 与点播源面板保持同一组筛选项与顺序:先状态(已启用 / 已停用),后来源(来自订阅 / 手动添加)
+const LIVE_FILTERS: { id: LiveFilter; label: string }[] = [
+ { id: 'all', label: '全部' },
+ { id: 'enabled', label: '已启用' },
+ { id: 'disabled', label: '已停用' },
+ { id: 'sub', label: '来自订阅' },
+ { id: 'manual', label: '手动添加' },
+];
+
+interface LiveRow {
+ url: string;
+ label: string;
+ epgUrl?: string;
+ preset: boolean;
+ lastSync?: number;
+ fromSubscriptions: string[];
}
export function LiveSourceManager() {
const store = useAppStore();
const { toast } = useToast();
- const [name, setName] = useState('');
- const [subUrl, setSubUrl] = useState('');
- const [epg, setEpg] = useState('');
- const [tests, setTests] = useState<Record<string, TestState>>({});
+ const [adding, setAdding] = useState(false);
+ /** 正在编辑的手动源 URL(与「添加」共用同一表单) */
+ const [editing, setEditing] = useState<string | null>(null);
+ const [query, setQuery] = useState('');
+ const [filter, setFilter] = useState<LiveFilter>('all');
+ const { tests, runTest } = useSourceTests();
- const addAndTest = () => {
- const url = subUrl.trim();
- if (!validateSourceUrl(url)) {
- toast('订阅地址需以 http:// 或 https:// 开头', 'warning');
- return;
- }
- store.addLiveSubscription(url, name.trim() || undefined, epg.trim() || undefined);
- void runTest(url, url);
- setSubUrl('');
- setName('');
- setEpg('');
- };
-
- const runTest = async (key: string, url: string) => {
- setTests((prev) => ({ ...prev, [key]: { status: 'loading' } }));
- const r = await api.liveTest(url);
- setTests((prev) => ({
- ...prev,
- [key]: r.ok
- ? { status: 'done', ok: true, ms: r.ms, count: r.count }
- : { status: 'done', ok: false, error: r.error },
+ const rows = useMemo<LiveRow[]>(() => {
+ const preset: LiveRow[] = store.liveEnvSources.map((s) => ({
+ url: s.url,
+ label: s.name || hostnameOf(s.url),
+ epgUrl: s.epg,
+ preset: true,
+ fromSubscriptions: [],
}));
- };
+ const subs: LiveRow[] = store.liveSubscriptions.map((s) => ({
+ url: s.url,
+ label: s.name || hostnameOf(s.url),
+ epgUrl: s.epg,
+ preset: false,
+ lastSync: s.lastSync,
+ fromSubscriptions: s.fromSubscriptions,
+ }));
+ const all = [...preset, ...subs];
+ const q = query.trim().toLowerCase();
+ return all.filter((r) => {
+ if (filter === 'enabled' && !store.liveSelectedUrls.includes(r.url)) return false;
+ if (filter === 'disabled' && store.liveSelectedUrls.includes(r.url)) return false;
+ if (filter === 'sub' && r.fromSubscriptions.length === 0) return false;
+ if (filter === 'manual' && !(r.fromSubscriptions.length === 0 && !r.preset)) return false;
+ if (!q) return true;
+ return r.label.toLowerCase().includes(q) || r.url.toLowerCase().includes(q);
+ });
+ }, [store.liveEnvSources, store.liveSubscriptions, store.liveSelectedUrls, query, filter]);
+
+ // 编辑中的手动源(与「添加」共用同一表单)
+ const editingSource = editing ? store.liveSubscriptions.find((s) => s.url === editing) : undefined;
const exportM3u = (url: string) => {
window.open(api.liveExportUrl(url), '_blank', 'noopener');
};
- const testBadge = (key: string, url: string) => {
- const t = tests[key];
- return (
- <span className="flex items-center gap-1 shrink-0">
- {t?.status === 'done' && (
- <span
- className={cn(
- 'text-[10px] px-1.5 py-0.5 rounded',
- t.ok ? 'bg-green-500/15 text-green-600 dark:text-green-400' : 'bg-red-500/15 text-red-500'
- )}
- title={t.ok ? `解析 ${t.ms}ms,共 ${t.count ?? 0} 个频道` : t.error}
- >
- {t.ok ? `✓ ${t.count ?? 0} 频道` : `✗ ${t.error?.slice(0, 12) || '失败'}`}
- </span>
- )}
- <button
- className={cn(
- 'rounded-md p-1.5 transition-colors disabled:opacity-40',
- t?.status === 'done' && !t.ok ? 'text-red-400' : 'text-muted hover:text-accent hover:bg-hover'
- )}
- disabled={t?.status === 'loading'}
- onClick={() => runTest(key, url)}
- aria-label="测试此直播源"
- title="拉取解析并测速(频道数量与耗时)"
- >
- {t?.status === 'loading' ? '…' : '⚡'}
- </button>
- </span>
- );
+ const allEnabled = rows.length > 0 && rows.every((r) => store.liveSelectedUrls.includes(r.url));
+ const toggleAll = () => {
+ // 单次事件内的多次 set 会被 React 批处理合并;用 getState 保证基于最新状态切换
+ if (allEnabled) {
+ rows.filter((r) => store.liveSelectedUrls.includes(r.url)).forEach((r) => useAppStore.getState().toggleLiveSelected(r.url));
+ return;
+ }
+ rows.filter((r) => !store.liveSelectedUrls.includes(r.url)).forEach((r) => useAppStore.getState().toggleLiveSelected(r.url));
};
- const renderRow = ({
- url,
- label,
- epgUrl,
- preset = false,
- lastSync,
- fromSubscriptions,
- }: {
- url: string;
- label: string;
- epgUrl?: string;
- preset?: boolean;
- lastSync?: number;
- /** 引用该直播源的订阅 URL 列表(多归属);非空时由订阅统一管理,不可单独删除 */
- fromSubscriptions?: string[];
- }) => (
- <li key={url} className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">
- <div className="flex items-center gap-2">
- <input
- type="checkbox"
- className="h-4 w-4 accent-[#2563eb] shrink-0"
- checked={store.liveSelectedUrls.includes(url)}
- onChange={() => store.toggleLiveSelected(url)}
- aria-label={store.liveSelectedUrls.includes(url) ? `停用 ${label}` : `启用 ${label}`}
- title={store.liveSelectedUrls.includes(url) ? '已启用,取消勾选可停用' : '已停用,勾选后生效'}
- />
- <div className="flex-1 min-w-0">
- <div className="text-sm font-medium text-content truncate">
- {label}
- {preset && (
- <span className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-chip text-faint align-middle">
- 部署者预置
- </span>
- )}
- {(fromSubscriptions?.length ?? 0) > 0 && (
- <span
- className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent align-middle"
- title={`来自 ${fromSubscriptions?.length ?? 0} 个数据源订阅;删除单个订阅不影响此源,仅当不再被任何订阅引用时才会移除`}
- >
- 订阅
- </span>
- )}
- </div>
- <div className="text-xs text-faint truncate">
- {url}
- {epgUrl && ' · 已配置节目单'}
- {lastSync && ` · 同步于 ${formatRelativeTime(lastSync)}`}
- </div>
- </div>
- {testBadge(url, url)}
- <button
- className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-accent"
- onClick={() => exportM3u(url)}
- aria-label="导出 M3U"
- title="导出为标准 M3U 文件"
- >
- ⇩
- </button>
- {(fromSubscriptions?.length ?? 0) > 0 ? (
- <button
- className="rounded-md p-1.5 text-muted/40"
- onClick={() => toast('该直播源来自数据源订阅;请到「订阅与配置 → 数据源订阅」中删除整个订阅', 'info')}
- aria-label="订阅源不可单独删除"
- title="该源来自订阅,单独删除会在下次同步时恢复;如需移除请删除整个订阅"
- >
- ✕
- </button>
- ) : (
- !preset && (
- <button
- className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-red-400"
- onClick={() => store.removeLiveSubscription(url)}
- aria-label="删除直播源"
- >
- ✕
- </button>
- )
- )}
- </div>
- </li>
- );
+ const removeWithUndo = (row: LiveRow) => {
+ const snapshot = useAppStore.getState().removeLiveSubscription(row.url);
+ if (!snapshot) return;
+ // 正在编辑的条目被移除时收起表单,避免表单悬空
+ if (editing === row.url) setEditing(null);
+ toast(`已移除「${row.label}」`, 'info', {
+ action: {
+ label: '撤销',
+ onClick: () => {
+ useAppStore.getState().restoreLiveSubscription(snapshot);
+ toast('已恢复', 'success');
+ },
+ },
+ });
+ };
+
+ const empty = store.liveEnvSources.length === 0 && store.liveSubscriptions.length === 0;
return (
- <section className="mb-6 pt-5">
- <div className="flex items-center justify-between mb-2.5">
- <h3 className="text-sm font-semibold text-content">直播源</h3>
- <span className="text-[10px] text-faint">M3U 订阅 · /live 页面播放</span>
- </div>
- <div className="space-y-2 mb-2.5">
- <input
- className="input w-full"
- placeholder="M3U 订阅地址,如 https://example.com/list.m3u"
- value={subUrl}
- maxLength={500}
- onChange={(e) => setSubUrl(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') addAndTest();
- }}
+ <section>
+ <SectionTitle
+ 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)}>
+ <Icon name="plus" className="w-3.5 h-3.5" />
+ 添加直播源
+ </button>
+ }
+ />
+
+ {/* 与点播源一致:由「+ 添加 / 编辑」按钮展开同一表单,而非常驻占位 */}
+ <LiveSourceForm
+ visible={adding || editingSource !== undefined}
+ initial={editingSource}
+ onCancel={() => {
+ setAdding(false);
+ setEditing(null);
+ }}
+ onSubmit={(data) => {
+ if (editing) {
+ // 编辑模式:只更新名称与 EPG(地址不可改)
+ store.updateLiveSubscription(editing, { name: data.name, epg: data.epg });
+ } else {
+ store.addLiveSubscription(data.url, data.name, data.epg);
+ void runTest(data.url, () => api.liveTest(data.url));
+ }
+ setAdding(false);
+ setEditing(null);
+ }}
+ />
+
+ {empty && !adding && editingSource === undefined ? (
+ <EmptyState
+ icon="link"
+ title="还没有添加任何直播源"
+ description="添加 M3U 地址后即可在「直播」页按分组浏览与播放频道;也可在「数据源订阅」中一次导入点播源与直播源;部署者还可通过 DEFAULT_LIVE_SOURCES 环境变量预置。"
+ action={
+ <button className="btn-primary text-xs" onClick={() => setAdding(true)}>
+ 添加第一个直播源
+ </button>
+ }
/>
- {(subUrl.trim() || name.trim() || epg.trim()) && (
- <>
- <input
- className="input w-full"
- placeholder="名称(可选),如 我的频道列表"
- value={name}
- maxLength={50}
- onChange={(e) => setName(e.target.value)}
- />
- <input
- className="input w-full"
- placeholder="EPG 节目单地址(可选,XMLTV xml/xml.gz)"
- value={epg}
- maxLength={500}
- onChange={(e) => setEpg(e.target.value)}
- />
- </>
- )}
- <button className="btn-primary !py-1.5 text-xs w-full" disabled={!subUrl.trim()} onClick={addAndTest}>
- 添加直播源
- </button>
- </div>
- {store.liveEnvSources.length === 0 && store.liveSubscriptions.length === 0 ? (
- <p className="text-xs text-faint">
- 添加 M3U 地址后即可在「直播」页按分组浏览与播放频道;也可在「订阅与配置 → 数据源订阅」中一次导入点播源与直播源;部署者还可通过 DEFAULT_LIVE_SOURCES 环境变量预置。
- </p>
) : (
- <ul className="space-y-2 max-h-[50vh] overflow-y-auto scrollbar-thin pr-1">
- {store.liveEnvSources.map((s) => renderRow({ url: s.url, label: s.name, epgUrl: s.epg, preset: true }))}
- {store.liveSubscriptions.map((s) =>
- renderRow({
- url: s.url,
- label: s.name || hostnameOf(s.url),
- epgUrl: s.epg,
- lastSync: s.lastSync,
- fromSubscriptions: s.fromSubscriptions,
- })
+ <>
+ <div className="space-y-2 mb-3">
+ <SearchInput value={query} onChange={setQuery} placeholder="搜索名称或地址" />
+ <div className="flex flex-wrap items-center gap-1">
+ {LIVE_FILTERS.map((f) => (
+ <button
+ key={f.id}
+ className={cn(
+ 'px-2 py-0.5 rounded-full text-[11px] transition-colors',
+ filter === f.id ? 'bg-accent/10 text-accent font-medium' : 'text-muted hover:text-content hover:bg-hover'
+ )}
+ onClick={() => setFilter(f.id)}
+ aria-pressed={filter === f.id}
+ >
+ {f.label}
+ </button>
+ ))}
+ <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}>
+ {allEnabled ? '全部停用' : '全部启用'}
+ </button>
+ </div>
+
+ {rows.length === 0 ? (
+ <p className="text-xs text-faint py-6 text-center">没有符合条件的源</p>
+ ) : (
+ <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">
+ <div className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ className="h-4 w-4 accent-[#2563eb] shrink-0"
+ checked={enabled}
+ onChange={() => useAppStore.getState().toggleLiveSelected(row.url)}
+ aria-label={enabled ? `停用 ${row.label}` : `启用 ${row.label}`}
+ title={enabled ? '已启用,取消勾选可停用' : '已停用,勾选后生效'}
+ />
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-content truncate">
+ {row.label}
+ {row.preset && (
+ <span className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-chip text-faint align-middle">
+ 部署者预置
+ </span>
+ )}
+ {fromSubscription && (
+ <span
+ className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent align-middle"
+ title={`来自 ${row.fromSubscriptions.length} 个数据源订阅;删除单个订阅不影响此源,仅当不再被任何订阅引用时才会移除`}
+ >
+ 订阅
+ </span>
+ )}
+ </div>
+ <div className="text-xs text-faint truncate">
+ {row.url}
+ {row.epgUrl && ' · 已配置节目单'}
+ {row.lastSync && ` · 同步于 ${formatRelativeTime(row.lastSync)}`}
+ </div>
+ </div>
+ <TestBadge
+ state={tests[row.url]}
+ onTest={() => runTest(row.url, () => api.liveTest(row.url))}
+ title="拉取解析并测速(频道数量与耗时)"
+ badgeWhenOk={({ count }) => `✓ ${count ?? 0} 频道`}
+ />
+ <button
+ className="rounded-md p-2 text-muted transition-colors hover:bg-hover hover:text-accent shrink-0"
+ onClick={() => exportM3u(row.url)}
+ aria-label="导出 M3U"
+ title="导出为标准 M3U 文件"
+ >
+ <Icon name="download" className="w-4 h-4" />
+ </button>
+ {row.preset ? null : fromSubscription ? (
+ <>
+ {/* 订阅源由远端列表管理:编辑会被下次同步覆盖、删除会复活,故置为禁用态并指路 */}
+ <button
+ className="rounded-md p-2 text-muted/30 cursor-not-allowed shrink-0"
+ disabled
+ aria-label="订阅源不可单独编辑"
+ title="该源来自数据源订阅,修改会在下次同步时被覆盖;请修改远端订阅内容后重新同步"
+ >
+ <Icon name="edit" className="w-4 h-4" />
+ </button>
+ <button
+ className="rounded-md p-2 text-muted/30 cursor-not-allowed shrink-0"
+ disabled
+ aria-label="订阅源不可单独删除"
+ title="该源来自数据源订阅;请到「数据源订阅」中删除整个订阅"
+ >
+ <Icon name="trash" className="w-4 h-4" />
+ </button>
+ </>
+ ) : (
+ <>
+ <button
+ className="rounded-md p-2 text-muted transition-colors hover:bg-hover hover:text-accent shrink-0"
+ onClick={() => setEditing(row.url)}
+ aria-label="编辑"
+ title="编辑名称与节目单地址"
+ >
+ <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"
+ onClick={() => removeWithUndo(row)}
+ aria-label="删除直播源"
+ title="移除(可在提示中撤销)"
+ >
+ <Icon name="trash" className="w-4 h-4" />
+ </button>
+ </>
+ )}
+ </div>
+ </li>
+ );
+ })}
+ </ul>
)}
- </ul>
+ </>
)}
</section>
);
}
+
+/** 直播源表单:与点播源一致,由「+ 添加 / 编辑」按钮展开;编辑时地址只读、提交后自动探活(仅新增) */
+function LiveSourceForm({
+ visible,
+ initial,
+ onCancel,
+ onSubmit,
+}: {
+ visible: boolean;
+ /** 编辑模式:仅允许改名称与 EPG,地址只读 */
+ initial?: { url: string; name?: string; epg?: string };
+ onCancel: () => void;
+ onSubmit: (data: { url: string; name?: string; epg?: string }) => void;
+}) {
+ const [url, setUrl] = useState('');
+ const [name, setName] = useState('');
+ const [epg, setEpg] = useState('');
+ const { toast } = useToast();
+
+ useEffect(() => {
+ if (visible) {
+ setUrl(initial?.url ?? '');
+ setName(initial?.name ?? '');
+ setEpg(initial?.epg ?? '');
+ }
+ }, [visible, initial]);
+
+ if (!visible) return null;
+
+ const submit = () => {
+ if (initial) {
+ onSubmit({ url: initial.url, name: name.trim() || undefined, epg: epg.trim() || undefined });
+ return;
+ }
+ const u = url.trim();
+ if (!validateSourceUrl(u)) {
+ toast('订阅地址需以 http:// 或 https:// 开头', 'warning');
+ return;
+ }
+ onSubmit({ url: u, name: name.trim() || undefined, epg: epg.trim() || undefined });
+ };
+
+ return (
+ <div className="space-y-2 border border-line rounded-lg p-3 bg-chip mb-2">
+ <input
+ className="input w-full disabled:opacity-60"
+ placeholder="M3U 订阅地址,如 https://example.com/list.m3u"
+ value={url}
+ maxLength={500}
+ disabled={!!initial}
+ title={initial ? '地址不可修改;如需更换请删除后重新添加' : undefined}
+ onChange={(e) => setUrl(e.target.value)}
+ />
+ <input
+ className="input w-full"
+ placeholder="名称(可选),如 我的频道列表"
+ value={name}
+ maxLength={50}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <input
+ className="input w-full"
+ 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>
+ <button className="btn-primary !py-1 text-xs" onClick={submit}>
+ 添加
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/settings-shared.tsx b/src/components/settings-shared.tsx
new file mode 100644
index 0000000..2d7f78f
--- /dev/null
+++ b/src/components/settings-shared.tsx
@@ -0,0 +1,279 @@
+'use client';
+
+import { useCallback, useState, type ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+import { useAppStore } from '@/lib/store';
+import { useToast } from './toast';
+import { Icon, type IconName } from './icon';
+
+/**
+ * 设置面板共享件:把此前点播源 / 直播源各自「抄一遍」的标题、开关、
+ * 下拉、空态、搜索框、探活徽章与健康度统一到一处,保证两类源面板风格与行为一致。
+ */
+
+/** 探活结果(点播 / 直播共用同一结构) */
+export type TestState =
+ | { status: 'loading' }
+ | { status: 'done'; ok: boolean; ms?: number; count?: number; error?: string };
+
+/** 探活结果状态管理:替代两条源列表各自维护一份 tests 的实现 */
+export function useSourceTests() {
+ const [tests, setTests] = useState<Record<string, TestState>>({});
+ const runTest = useCallback(
+ async (
+ key: string,
+ run: () => Promise<{ ok: boolean; ms?: number; count?: number; error?: string }>
+ ) => {
+ setTests((prev) => ({ ...prev, [key]: { status: 'loading' } }));
+ try {
+ const r = await run();
+ setTests((prev) => ({
+ ...prev,
+ [key]: r.ok
+ ? { status: 'done', ok: true, ms: r.ms, count: r.count }
+ : { status: 'done', ok: false, error: r.error },
+ }));
+ } catch (err) {
+ setTests((prev) => ({
+ ...prev,
+ [key]: { status: 'done', ok: false, error: err instanceof Error ? err.message : '测试失败' },
+ }));
+ }
+ },
+ []
+ );
+ return { tests, runTest };
+}
+
+export function SectionTitle({ title, hint, extra }: { title: string; hint?: string; extra?: ReactNode }) {
+ return (
+ <div className="flex items-center justify-between gap-2 mb-2.5">
+ <div className="min-w-0">
+ <h3 className="text-sm font-semibold text-content">{title}</h3>
+ {hint && <p className="text-[11px] text-faint truncate">{hint}</p>}
+ </div>
+ {extra}
+ </div>
+ );
+}
+
+export function ToggleRow({
+ label,
+ description,
+ checked,
+ onChange,
+}: {
+ label: string;
+ description: string;
+ checked: boolean;
+ onChange: (v: boolean) => void;
+}) {
+ return (
+ <div className="flex items-center justify-between gap-4 py-0.5">
+ <div className="min-w-0">
+ <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}
+ 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)}
+ >
+ <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>
+ );
+}
+
+export function SelectRow({
+ label,
+ value,
+ onChange,
+ options,
+}: {
+ label: string;
+ value: string;
+ onChange: (v: string) => void;
+ options: { value: string; label: string }[];
+}) {
+ return (
+ <div className="flex items-center justify-between gap-4">
+ <span className="text-sm text-content shrink-0">{label}</span>
+ <div className="relative min-w-0">
+ <select
+ className="input !py-1.5 !pl-2.5 !pr-7 cursor-pointer appearance-none text-xs max-w-full"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ aria-label={label}
+ >
+ {options.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ <Icon
+ name="chevronDown"
+ className="pointer-events-none absolute right-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-faint"
+ />
+ </div>
+ </div>
+ );
+}
+
+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,
+ placeholder,
+}: {
+ value: string;
+ onChange: (v: string) => void;
+ placeholder?: string;
+}) {
+ return (
+ <div className="relative">
+ <Icon
+ name="search"
+ className="w-4 h-4 absolute left-2.5 top-1/2 -translate-y-1/2 text-faint pointer-events-none"
+ />
+ <input
+ className="input w-full !pl-8 !py-1.5 text-xs"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ />
+ </div>
+ );
+}
+
+/** 单源探活徽章 + 触发按钮(点播 / 直播共用;`badgeWhenOk` 决定成功文案) */
+export function TestBadge({
+ state,
+ onTest,
+ title,
+ badgeWhenOk,
+}: {
+ state?: TestState;
+ onTest: () => void;
+ title: string;
+ badgeWhenOk: (t: { ms?: number; count?: number }) => string;
+}) {
+ return (
+ <span className="flex items-center gap-1 shrink-0">
+ {state?.status === 'done' && (
+ <span
+ className={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'
+ )}
+ title={state.ok ? `${state.ms}ms` : state.error}
+ >
+ {state.ok ? badgeWhenOk({ ms: state.ms, count: state.count }) : `✗ ${state.error?.slice(0, 12) || '失败'}`}
+ </span>
+ )}
+ <button
+ className={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'
+ )}
+ 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" />
+ )}
+ </button>
+ </span>
+ );
+}
+
+/** 点播源搜索健康度徽章(随搜索/批量测活滚动更新);被自动停用的源提供手动恢复入口 */
+export function HealthBadge({ sourceKey }: { sourceKey: string }) {
+ const entry = useAppStore((s) => s.sourceHealth[sourceKey]);
+ const { toast } = useToast();
+ if (!entry) return null;
+
+ const disabled = !!entry.disabledUntil && entry.disabledUntil > Date.now();
+ if (disabled) {
+ const remainMin = Math.max(1, Math.ceil(((entry.disabledUntil ?? 0) - Date.now()) / 60000));
+ 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} 分钟后自动恢复`}
+ >
+ <Icon name="clock" className="w-3 h-3" />
+ {remainMin} 分
+ </span>
+ <button
+ className="text-[10px] px-1.5 py-0.5 rounded text-muted hover:text-accent hover:bg-hover transition-colors"
+ aria-label="恢复此源"
+ title="清除健康度记录,立即恢复参与搜索"
+ onClick={() => {
+ useAppStore.getState().clearSourceHealth(sourceKey);
+ toast('已恢复,下次搜索重新参与', 'success');
+ }}
+ >
+ 恢复
+ </button>
+ </span>
+ );
+ }
+
+ 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`}>
+ ✓ {entry.ms}ms
+ </span>
+ );
+ }
+ return (
+ <span
+ className={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'
+ )}
+ title={entry.error}
+ >
+ 连续 {entry.failStreak} 次失败
+ </span>
+ );
+}
diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsx
index d8071e2..412aed8 100644
--- a/src/components/source-manager.tsx
+++ b/src/components/source-manager.tsx
@@ -1,411 +1,638 @@
'use client';
-import { useEffect, useState } from 'react';
-import { Drawer } from './header';
+import { useEffect, useMemo, useState } from 'react';
+import { Drawer } from './drawer';
+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,
+ useSourceTests,
+ type TestState,
+} from './settings-shared';
+import { useSourceProbe } from './use-source-probe';
import { isSourceDisabled, keyBelongsToSubscription, subKeyPrefix, useAppStore } from '@/lib/store';
+import type { SourceConfig } from '@/lib/types';
import { useToast } from './toast';
-import { formatRelativeTime, validateSourceUrl, cn } from '@/lib/utils';
+import { formatRelativeTime, hostnameOf, validateSourceUrl, cn } from '@/lib/utils';
import { exportConfig, importConfig } from '@/lib/db';
import { useAuth } from './auth';
import { api } from '@/lib/client-api';
import { syncSourceSubscription } from '@/lib/subscription-sync';
import { describeParseStats } from '@/lib/tvbox-parser';
-import { LiveSourceManager } from './live-source-manager';
/**
- * 设置抽屉:顶部 Tab 分类(点播源 / 直播源 / 播放设置 / 订阅与配置),
- * 每次只渲染一类内容,避免源很多时长距离滚动。
+ * 设置抽屉:顶部两级导航。
+ * - 一级按性质分组:源管理 / 偏好设置 / 数据;
+ * - 二级为该分组下的具体面板,每次只渲染一类内容,避免源很多时长距离滚动。
+ * 选中位置记忆到 localStorage,再次打开回到上次所在面板。
*/
-type TestState =
- | { status: 'loading' }
- | { status: 'done'; ok: boolean; ms?: number; count?: number; error?: string };
-
-type SettingsTab = 'sources' | 'live' | 'playback' | 'config';
+type PrimaryTab = 'sources' | 'prefs' | 'data';
+type SecondaryTab = 'vod' | 'live' | 'subs' | 'playback' | 'image' | 'home' | 'io';
-const SETTINGS_TABS: { id: SettingsTab; label: string }[] = [
- { id: 'sources', label: '点播源' },
- { id: 'live', label: '直播源' },
- { id: 'playback', label: '播放设置' },
- { id: 'config', label: '订阅与配置' },
+const PRIMARY_TABS: { id: PrimaryTab; label: string; icon: IconName }[] = [
+ { id: 'sources', label: '源管理', icon: 'link' },
+ { id: 'prefs', label: '偏好设置', icon: 'gear' },
+ { id: 'data', label: '数据', icon: 'download' },
];
+const SECONDARY_TABS: Record<PrimaryTab, { id: SecondaryTab; label: string }[]> = {
+ sources: [
+ { id: 'vod', label: '点播源' },
+ { id: 'live', label: '直播源' },
+ { id: 'subs', label: '数据源订阅' },
+ ],
+ prefs: [
+ { id: 'playback', label: '播放与过滤' },
+ { id: 'image', label: '封面图加载' },
+ { id: 'home', label: '首页与内容' },
+ ],
+ data: [{ id: 'io', label: '配置导入导出' }],
+};
+
+const TAB_STORAGE_KEY = 'libretv-settings-tab';
+
export function SourceManagerDrawer({ open, onClose }: { open: boolean; onClose: () => void }) {
- const store = useAppStore();
- const { toast } = useToast();
- const [editing, setEditing] = useState<string | null>(null);
- const [tests, setTests] = useState<Record<string, TestState>>({});
- // Tab 选中态不持久化:每次打开抽屉回到「点播源」
- const [settingsTab, setSettingsTab] = useState<SettingsTab>('sources');
+ const [primary, setPrimary] = useState<PrimaryTab>('sources');
+ const [secondary, setSecondary] = useState<Record<PrimaryTab, SecondaryTab>>({
+ sources: 'vod',
+ prefs: 'playback',
+ data: 'io',
+ });
- const runTest = async (key: string, url: string) => {
- setTests((prev) => ({ ...prev, [key]: { status: 'loading' } }));
+ // 挂载后读取上次位置(不在渲染期读 localStorage,避免 SSR/hydration 不一致)
+ useEffect(() => {
try {
- const r = await api.testSource(url);
- setTests((prev) => ({
- ...prev,
- [key]: r.ok
- ? { status: 'done', ok: true, ms: r.ms, count: r.count }
- : { status: 'done', ok: false, error: r.error },
- }));
- } catch (err) {
- setTests((prev) => ({
- ...prev,
- [key]: { status: 'done', ok: false, error: err instanceof Error ? err.message : '测试失败' },
- }));
+ const raw = localStorage.getItem(TAB_STORAGE_KEY);
+ if (!raw) return;
+ const saved = JSON.parse(raw) as {
+ primary?: PrimaryTab;
+ secondary?: Partial<Record<PrimaryTab, SecondaryTab>>;
+ };
+ // 旧版把「数据源订阅」放在「数据」下,现已迁至「源管理」:自动重定向到新位置
+ const migratedSubs = saved.secondary?.data === 'subs';
+ const targetPrimary = migratedSubs && saved.primary === 'data' ? 'sources' : saved.primary;
+ if (targetPrimary && SECONDARY_TABS[targetPrimary]) setPrimary(targetPrimary);
+ setSecondary((prev) => {
+ const next = { ...prev };
+ if (migratedSubs) next.sources = 'subs';
+ for (const key of Object.keys(SECONDARY_TABS) as PrimaryTab[]) {
+ const v = saved.secondary?.[key];
+ if (v && SECONDARY_TABS[key].some((t) => t.id === v)) next[key] = v;
+ }
+ return next;
+ });
+ } catch {
+ /* 本地记录损坏时忽略,回到默认面板 */
}
- };
+ }, []);
- /** 搜索健康度徽章:展示最近一次搜索该源的结果;被自动停用的源提供手动恢复入口 */
- const healthBadge = (key: string) => {
- const e = store.sourceHealth[key];
- if (!e) return null;
- if (isSourceDisabled(store, key)) {
- const remainMin = Math.max(1, Math.ceil(((e.disabledUntil ?? 0) - Date.now()) / 60000));
- return (
- <span className="flex items-center gap-1 shrink-0">
- <span
- className="text-[10px] px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-500"
- title={`连续 ${e.failStreak} 次超时/失败,${remainMin} 分钟后自动恢复`}
- >
- ⏱ 已停用 {remainMin} 分
- </span>
+ useEffect(() => {
+ try {
+ localStorage.setItem(TAB_STORAGE_KEY, JSON.stringify({ primary, secondary }));
+ } catch {
+ /* 隐私模式等无法写入时忽略 */
+ }
+ }, [primary, secondary]);
+
+ const current = secondary[primary];
+
+ return (
+ <Drawer
+ open={open}
+ onClose={onClose}
+ title="设置"
+ resetScrollKey={current}
+ subheader={
+ <div className="space-y-2">
+ <TabRow tabs={PRIMARY_TABS} value={primary} onChange={setPrimary} variant="primary" ariaLabel="设置分类" />
+ {/* 分组下只有一项时无需二级导航,直接展示该面板 */}
+ {SECONDARY_TABS[primary].length > 1 && (
+ <TabRow
+ tabs={SECONDARY_TABS[primary]}
+ value={current}
+ onChange={(id) => setSecondary((prev) => ({ ...prev, [primary]: id }))}
+ variant="secondary"
+ ariaLabel="设置项"
+ />
+ )}
+ </div>
+ }
+ >
+ {current === 'vod' && <VodSourcesPanel />}
+ {current === 'live' && <LiveSourceManager />}
+ {current === 'playback' && <PlaybackPanel />}
+ {current === 'image' && <ImagePanel />}
+ {current === 'home' && <HomePanel />}
+ {current === 'subs' && <SourceSubscriptions />}
+ {current === 'io' && <ConfigIoPanel />}
+ </Drawer>
+ );
+}
+
+/** 一级/二级导航条(role=tablist,左右方向键切换) */
+function TabRow<T extends string>({
+ tabs,
+ value,
+ onChange,
+ variant,
+ ariaLabel,
+}: {
+ tabs: { id: T; label: string; icon?: IconName }[];
+ value: T;
+ onChange: (id: T) => void;
+ variant: 'primary' | 'secondary';
+ ariaLabel: string;
+}) {
+ const move = (dir: 1 | -1) => {
+ const idx = tabs.findIndex((t) => t.id === value);
+ onChange(tabs[(idx + dir + tabs.length) % tabs.length].id);
+ };
+ return (
+ <div
+ role="tablist"
+ aria-label={ariaLabel}
+ className={cn('flex gap-1', variant === 'primary' ? 'p-0.5 bg-chip rounded-lg' : 'overflow-x-auto scrollbar-thin')}
+ onKeyDown={(e) => {
+ if (e.key === 'ArrowRight') {
+ e.preventDefault();
+ move(1);
+ } else if (e.key === 'ArrowLeft') {
+ e.preventDefault();
+ move(-1);
+ }
+ }}
+ >
+ {tabs.map((t) => {
+ const active = t.id === value;
+ return (
<button
- className="text-[10px] px-1 text-muted hover:text-accent"
- aria-label="恢复此源"
- title="清除健康度记录,立即恢复参与搜索"
- onClick={() => {
- store.clearSourceHealth(key);
- toast('已恢复,下次搜索重新参与', 'success');
- }}
+ key={t.id}
+ role="tab"
+ aria-selected={active}
+ className={cn(
+ 'shrink-0 inline-flex items-center justify-center gap-1 rounded-md transition-colors',
+ variant === 'primary'
+ ? cn(
+ 'flex-1 px-2 py-1.5 text-xs',
+ active ? 'bg-surface-raised text-accent font-medium shadow-sm' : 'text-muted hover:text-content'
+ )
+ : cn(
+ 'px-2.5 py-1 text-xs',
+ active ? 'bg-accent/10 text-accent font-medium' : 'text-muted hover:text-content hover:bg-hover'
+ )
+ )}
+ onClick={() => onChange(t.id)}
>
- 恢复
+ {t.icon && <Icon name={t.icon} className="w-3.5 h-3.5" />}
+ {t.label}
</button>
- </span>
- );
+ );
+ })}
+ </div>
+ );
+}
+
+// —— 点播源面板 ——
+
+type VodFilter = 'all' | 'enabled' | 'disabled' | 'sub' | 'manual';
+
+// 与直播源面板保持同一组筛选项与顺序:先状态(已启用 / 已停用),后来源(来自订阅 / 手动添加)
+const VOD_FILTERS: { id: VodFilter; label: string }[] = [
+ { id: 'all', label: '全部' },
+ { id: 'enabled', label: '已启用' },
+ { id: 'disabled', label: '已停用' },
+ { id: 'sub', label: '来自订阅' },
+ { id: 'manual', label: '手动添加' },
+];
+
+function VodSourcesPanel() {
+ const store = useAppStore();
+ const { toast } = useToast();
+ const [editing, setEditing] = useState<string | null>(null);
+ const [query, setQuery] = useState('');
+ const [filter, setFilter] = useState<VodFilter>('all');
+ const { tests, runTest } = useSourceTests();
+ const { progress, probe, cancel, isProbing } = useSourceProbe();
+
+ const envKeys = useMemo(() => new Set(store.envSources.map((s) => s.key)), [store.envSources]);
+ const all = useMemo(() => [...store.envSources, ...store.customAPIs], [store.envSources, store.customAPIs]);
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ return all.filter((s) => {
+ const fromSub = s.key.startsWith('sub_');
+ // 已启用 = 勾选中且当前未被自动停用(即真正在参与搜索的源)
+ if (filter === 'enabled' && !(store.selectedKeys.includes(s.key) && !isSourceDisabled(store, s.key))) return false;
+ if (filter === 'disabled' && !isSourceDisabled(store, s.key)) return false;
+ if (filter === 'sub' && !fromSub) return false;
+ // 手动添加 = 既非订阅导入、也非部署者预置
+ if (filter === 'manual' && (fromSub || envKeys.has(s.key))) return false;
+ if (!q) return true;
+ return s.name.toLowerCase().includes(q) || s.url.toLowerCase().includes(q);
+ });
+ }, [all, query, filter, store, envKeys]);
+
+ const visibleKeys = filtered.map((s) => s.key);
+ const allSelected = visibleKeys.length > 0 && visibleKeys.every((k) => store.selectedKeys.includes(k));
+
+ const toggleAll = () => {
+ if (allSelected) {
+ store.setSelectedKeys(store.selectedKeys.filter((k) => !visibleKeys.includes(k)));
+ return;
}
- if (e.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={`上次搜索 ${e.ms}ms`}
- >
- ✓ {e.ms}ms
- </span>
- );
+ // 成人过滤开启时成人源不可勾选,与行内复选框保持一致
+ const eligible = filtered.filter((s) => !(s.isAdult && store.yellowFilter)).map((s) => s.key);
+ const skipped = filtered.length - eligible.length;
+ store.setSelectedKeys([...new Set([...store.selectedKeys, ...eligible])]);
+ if (skipped > 0) toast(`已启用 ${eligible.length} 个;${skipped} 个成人源因过滤开启被跳过`, 'info');
+ };
+
+ const runAll = async () => {
+ if (isProbing) {
+ cancel();
+ return;
}
- return (
- <span
- className={cn(
- 'text-[10px] px-1.5 py-0.5 rounded shrink-0',
- e.timedOut ? 'bg-amber-500/15 text-amber-500' : 'bg-red-500/15 text-red-500'
- )}
- title={e.error}
- >
- {e.timedOut ? '⏱' : '✗'} 连续 {e.failStreak} 次失败
- </span>
- );
+ const result = await probe(filtered.map((s) => ({ key: s.key, url: s.url })));
+ if (!result) return; // 被取消则无汇总
+ toast(`测活完成:${result.ok}/${result.total} 个可用`, result.ok === result.total ? 'success' : 'info');
};
- const testButton = (key: string, url: string) => {
- const t = tests[key];
- return (
- <span className="flex items-center gap-1 shrink-0">
- {t?.status === 'done' && (
- <span
- className={cn(
- 'text-[10px] px-1.5 py-0.5 rounded',
- t.ok ? 'bg-green-500/15 text-green-600 dark:text-green-400' : 'bg-red-500/15 text-red-500'
- )}
- title={t.ok ? `响应 ${t.ms}ms,搜索到 ${t.count ?? 0} 条` : t.error}
- >
- {t.ok ? `✓ ${t.ms}ms` : `✗ ${t.error?.slice(0, 12) || '失败'}`}
- </span>
- )}
- <button
- className={cn(
- 'rounded-md p-1.5 transition-colors disabled:opacity-40',
- t?.status === 'done' && !t.ok ? 'text-red-400' : 'text-muted hover:text-accent hover:bg-hover'
- )}
- disabled={t?.status === 'loading'}
- onClick={() => runTest(key, url)}
- aria-label="测试此源"
- title="测试可用性(搜索耗时与结果量)"
- >
- {t?.status === 'loading' ? '…' : '⚡'}
- </button>
- </span>
- );
+ /** 一键恢复被自动停用的源(仅「已停用」筛选下提供) */
+ const restoreAll = () => {
+ const keys = filtered.filter((s) => isSourceDisabled(store, s.key)).map((s) => s.key);
+ if (keys.length === 0) return;
+ keys.forEach((k) => useAppStore.getState().clearSourceHealth(k));
+ toast(`已恢复 ${keys.length} 个源`, 'success');
};
+ const empty = store.envSources.length === 0 && store.customAPIs.length === 0;
+
return (
- <Drawer open={open} onClose={onClose} title="设置">
- {/* 分类 Tab 条:-mt-4 抵消内容容器的上内边距使其贴合标题栏;sticky 吸附在标题栏下方(标题栏高 60px + 1px 边框) */}
- <div className="sticky top-[61px] z-10 -mx-4 -mt-4 px-4 pt-3 pb-2.5 bg-surface-raised border-b border-line flex gap-1">
- {SETTINGS_TABS.map((tab) => (
- <button
- key={tab.id}
- className={cn(
- 'px-2.5 py-1 rounded-md text-xs transition-colors',
- settingsTab === tab.id
- ? 'bg-accent/10 text-accent font-medium'
- : 'text-muted hover:text-content hover:bg-hover'
- )}
- onClick={() => setSettingsTab(tab.id)}
- >
- {tab.label}
+ <section>
+ <SectionTitle
+ 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__')}>
+ <Icon name="plus" className="w-3.5 h-3.5" />
+ 添加 API
</button>
- ))}
- </div>
+ }
+ />
- {settingsTab === 'sources' && (
- <>
- <section className="mb-6 pt-5">
- <SectionTitle
- title="点播源"
- extra={
- <button className="btn-primary !py-1 !px-2.5 text-xs" onClick={() => setEditing('__new__')}>
- + 添加 API
+ <SourceForm
+ visible={editing === '__new__'}
+ onCancel={() => setEditing(null)}
+ onSubmit={(data) => {
+ store.addCustomApi(data);
+ setEditing(null);
+ }}
+ />
+
+ {empty && editing !== '__new__' ? (
+ <EmptyState
+ icon="link"
+ title="还没有添加任何点播源"
+ description="添加一个 Apple CMS 采集站 API 即可开始搜索影片;也可到「数据源订阅」一次导入点播源与直播源"
+ action={
+ <button className="btn-primary text-xs" onClick={() => setEditing('__new__')}>
+ 添加第一个点播源
</button>
}
/>
- <SourceForm
- visible={editing === '__new__'}
- onCancel={() => setEditing(null)}
- onSubmit={(data) => {
- store.addCustomApi(data);
- setEditing(null);
- }}
- />
- {store.customAPIs.length === 0 && store.envSources.length === 0 && editing !== '__new__' ? (
- <EmptySourceGuide onAdd={() => setEditing('__new__')} />
- ) : (
- <>
- {/* 源很多时限高内滚,避免 tab 内长滚 */}
- <div className="max-h-[50vh] overflow-y-auto scrollbar-thin pr-1">
- {store.envSources.length > 0 && (
- <ul className="space-y-2 mb-2">
- {store.envSources.map((api) => (
- <li key={api.key} className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">
- <div className="flex items-center gap-2">
- <input
- type="checkbox"
- className="h-4 w-4 accent-[#2563eb]"
- checked={store.selectedKeys.includes(api.key)}
- onChange={() => store.toggleSourceSelected(api.key)}
- disabled={!!api.isAdult && store.yellowFilter}
- title={api.isAdult && store.yellowFilter ? '成人内容过滤开启中,需先关闭过滤才能启用此源' : undefined}
- aria-label={`选择 ${api.name}`}
- />
- <div className="flex-1 min-w-0">
- <div className="text-sm font-medium text-content truncate">
- {api.name}
- {api.isAdult && <span className="text-pink-400 text-xs ml-1">(18+)</span>}
- {api.isAdult && store.yellowFilter && (
- <span className="text-[10px] text-faint ml-1">过滤开启中,需关闭后才能启用</span>
- )}
- <span className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-chip text-faint align-middle">
- 部署者预置
- </span>
- </div>
- <div className="text-xs text-faint truncate">{api.url}</div>
- </div>
- {healthBadge(api.key)}
- {testButton(api.key, api.url)}
- </div>
- </li>
- ))}
- </ul>
+ ) : (
+ <>
+ <div className="space-y-2 mb-3">
+ <SearchInput value={query} onChange={setQuery} placeholder="搜索名称或地址" />
+ <div className="flex flex-wrap items-center gap-1">
+ {VOD_FILTERS.map((f) => (
+ <button
+ key={f.id}
+ className={cn(
+ 'px-2 py-0.5 rounded-full text-[11px] transition-colors',
+ filter === f.id ? 'bg-accent/10 text-accent font-medium' : 'text-muted hover:text-content hover:bg-hover'
+ )}
+ onClick={() => setFilter(f.id)}
+ aria-pressed={filter === f.id}
+ >
+ {f.label}
+ </button>
+ ))}
+ <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}>
+ {allSelected ? '全部停用' : '全部启用'}
+ </button>
+ <button
+ className="btn-ghost !py-1 !px-2 text-[11px]"
+ onClick={runAll}
+ disabled={filtered.length === 0}
+ >
+ {isProbing ? '取消测活' : '批量测活'}
+ </button>
+ {/* 查看「已停用」时提供一键恢复,省去逐个点击 */}
+ {filter === 'disabled' && (
+ <button className="btn-ghost !py-1 !px-2 text-[11px]" onClick={restoreAll} disabled={filtered.length === 0}>
+ 全部恢复
+ </button>
+ )}
+ </div>
+ {progress && (
+ <div className="flex items-center gap-2 text-[11px] text-muted">
+ <div className="flex-1 h-1.5 bg-chip rounded-full overflow-hidden">
+ <div
+ className="h-full bg-accent transition-[width] duration-200"
+ style={{ width: `${Math.round((progress.done / progress.total) * 100)}%` }}
+ />
+ </div>
+ <span className="tabular-nums shrink-0">
+ {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>
+ </div>
)}
+ </div>
+
+ {filtered.length === 0 ? (
+ <p className="text-xs text-faint py-6 text-center">没有符合条件的源</p>
+ ) : (
<ul className="space-y-2">
- {store.customAPIs.map((api) => {
- const fromSubscription = api.key.startsWith('sub_');
- return (
- <li key={api.key} className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">
- {editing === api.key ? (
- <SourceForm
- visible
- initial={api}
- onCancel={() => setEditing(null)}
- onSubmit={(data) => {
- store.updateCustomApi(api.key, data);
- setEditing(null);
- }}
- />
- ) : (
- <div className="flex items-center gap-2">
- <input
- type="checkbox"
- className="h-4 w-4 accent-[#2563eb]"
- checked={store.selectedKeys.includes(api.key)}
- onChange={() => store.toggleSourceSelected(api.key)}
- disabled={!!api.isAdult && store.yellowFilter}
- title={api.isAdult && store.yellowFilter ? '成人内容过滤开启中,需先关闭过滤才能启用此源' : undefined}
- aria-label={`选择 ${api.name}`}
- />
- <div className="flex-1 min-w-0">
- <div className="text-sm font-medium text-content truncate">
- {api.name}
- {api.isAdult && <span className="text-pink-400 text-xs ml-1">(18+)</span>}
- {api.isAdult && store.yellowFilter && (
- <span className="text-[10px] text-faint ml-1">过滤开启中,需关闭后才能启用</span>
- )}
- {fromSubscription && (
- <span
- className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent align-middle"
- title="来自数据源订阅,重新同步时此源的名称/地址会以订阅内容为准"
- >
- 订阅
- </span>
- )}
- </div>
- <div className="text-xs text-faint truncate">{api.url}</div>
- </div>
- {healthBadge(api.key)}
- {testButton(api.key, api.url)}
- {fromSubscription ? (
- // 订阅源由远端列表管理:编辑会被下次同步覆盖,删除会复活,引导到订阅区操作
- <>
- <button
- className="rounded-md p-1.5 text-muted/40"
- aria-label="订阅源不可单独编辑"
- title="该源来自订阅,编辑修改会在下次同步时被覆盖;如需调整请修改远端订阅列表后重新同步"
- onClick={() => toast('订阅源以远端列表为准;请修改远端订阅内容后重新同步', 'info')}
- >
- ✎
- </button>
- <button
- className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-red-400"
- onClick={() => {
- store.removeCustomApi(api.key);
- toast('已移除;注意:重新同步订阅时该源会恢复', 'info');
- }}
- aria-label="删除"
- title="移除此源(重新同步订阅时会恢复)"
- >
- ✕
- </button>
- </>
- ) : (
- <>
- <button
- className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-accent"
- onClick={() => setEditing(api.key)}
- aria-label="编辑"
- >
- ✎
- </button>
- <button
- className="rounded-md p-1.5 text-muted transition-colors hover:bg-hover hover:text-red-400"
- onClick={() => store.removeCustomApi(api.key)}
- aria-label="删除"
- >
- ✕
- </button>
- </>
- )}
- </div>
- )}
- </li>
- );
- })}
+ {filtered.map((source) => (
+ <VodSourceRow
+ key={source.key}
+ api={source}
+ isEnv={envKeys.has(source.key)}
+ editing={editing === source.key}
+ onEdit={setEditing}
+ onCancelEdit={() => setEditing(null)}
+ onUpdate={(data) => {
+ store.updateCustomApi(source.key, data);
+ setEditing(null);
+ }}
+ testState={tests[source.key]}
+ onTest={() =>
+ runTest(source.key, async () => {
+ const r = await api.testSource(source.url);
+ // 手动测试也写入健康度,与搜索 / 批量测活共用同一份模型(不再存在两套健康度)
+ useAppStore.getState().recordSourceHealth([
+ { sourceKey: source.key, ok: r.ok, ms: r.ms, error: r.error, list: [] },
+ ]);
+ return r;
+ })
+ }
+ />
+ ))}
</ul>
- </div>
- </>
- )}
- </section>
- </>
+ )}
+ </>
)}
+ </section>
+ );
+}
- {settingsTab === 'live' && <LiveSourceManager />}
-
- {settingsTab === 'playback' && (
- <>
- <section className="mb-6 pt-5">
- <SectionTitle title="播放与过滤" />
- <div className="space-y-3">
- <ToggleRow
- label="广告过滤"
- description="过滤 m3u8 中的广告分片"
- checked={store.adFilter}
- onChange={(v) => store.updateSettings({ adFilter: v })}
- />
- <ToggleRow
- label="自动连播"
- description="单集播放结束后自动播放下一集"
- checked={store.autoplayNext}
- onChange={(v) => store.updateSettings({ autoplayNext: v })}
- />
+function formatEta(done: number, total: number, startedAt: number): string {
+ if (done <= 0 || done >= total) return '';
+ const elapsed = Date.now() - startedAt;
+ const remainSec = Math.max(0, Math.round((elapsed / done) * (total - done) / 1000));
+ return remainSec > 0 ? ` · 约 ${remainSec}s` : '';
+}
+
+/** 单条点播源行:勾选 / 名称标签 / 健康度 / 探活 / 编辑删除(订阅源与预置源按来源限制操作) */
+function VodSourceRow({
+ api,
+ isEnv,
+ editing,
+ onEdit,
+ onCancelEdit,
+ onUpdate,
+ testState,
+ onTest,
+}: {
+ api: SourceConfig;
+ isEnv: boolean;
+ editing: boolean;
+ onEdit: (key: string) => void;
+ onCancelEdit: () => void;
+ onUpdate: (data: { name: string; url: string; detail?: string; isAdult?: boolean }) => void;
+ testState?: TestState;
+ onTest: () => void;
+}) {
+ const selected = useAppStore((s) => s.selectedKeys.includes(api.key));
+ const yellowFilter = useAppStore((s) => s.yellowFilter);
+ const toast = useToast().toast;
+ const fromSubscription = api.key.startsWith('sub_');
+ const adultBlocked = !!api.isAdult && yellowFilter;
+
+ const remove = () => {
+ const snapshot = useAppStore.getState().removeCustomApi(api.key);
+ if (!snapshot) return;
+ // 轻操作:不做确认弹窗,给 6 秒撤销窗口
+ toast(`已移除「${api.name}」`, 'info', {
+ action: {
+ label: '撤销',
+ onClick: () => {
+ const ok = useAppStore.getState().restoreCustomApi(snapshot);
+ toast(ok ? '已恢复' : '恢复失败:该源位置已被重新占用', ok ? 'success' : 'warning');
+ },
+ },
+ });
+ };
+
+ if (editing) {
+ return (
+ <li className="bg-card rounded-lg p-3">
+ <SourceForm visible initial={api} onCancel={onCancelEdit} onSubmit={onUpdate} />
+ </li>
+ );
+ }
+
+ return (
+ <li className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">
+ <div className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ className="h-4 w-4 accent-[#2563eb] shrink-0"
+ checked={selected}
+ onChange={() => useAppStore.getState().toggleSourceSelected(api.key)}
+ disabled={adultBlocked}
+ title={adultBlocked ? '成人内容过滤开启中,需先关闭过滤才能启用此源' : undefined}
+ aria-label={`选择 ${api.name}`}
+ />
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-content truncate">
+ {api.name}
+ {api.isAdult && <span className="text-pink-400 text-xs ml-1">(18+)</span>}
+ {isEnv && (
+ <span className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-chip text-faint align-middle">
+ 部署者预置
+ </span>
+ )}
+ {fromSubscription && (
+ <span
+ className="ml-1.5 text-[10px] px-1.5 py-0.5 rounded bg-accent/10 text-accent align-middle"
+ title="来自数据源订阅,重新同步时此源的名称/地址会以订阅内容为准"
+ >
+ 订阅
+ </span>
+ )}
+ </div>
+ <div className="text-xs text-faint truncate">{api.url}</div>
</div>
- </section>
+ <HealthBadge sourceKey={api.key} />
+ <TestBadge
+ state={testState}
+ onTest={onTest}
+ title="测试可用性(搜索耗时与结果量)"
+ badgeWhenOk={({ ms }) => `✓ ${ms}ms`}
+ />
+ {!isEnv &&
+ (fromSubscription ? (
+ // 订阅源由远端列表管理:编辑会被下次同步覆盖、删除会复活,故置为禁用态并说明去处
+ <>
+ <button
+ className="rounded-md p-2 text-muted/30 cursor-not-allowed shrink-0"
+ disabled
+ aria-label="订阅源不可单独编辑"
+ title="该源来自订阅,修改会在下次同步时被覆盖;请修改远端订阅后重新同步"
+ >
+ <Icon name="edit" className="w-4 h-4" />
+ </button>
+ <button
+ className="rounded-md p-2 text-muted/30 cursor-not-allowed shrink-0"
+ disabled
+ aria-label="订阅源不可单独删除"
+ title="该源来自订阅,单独删除会在下次同步时恢复;请到「数据源订阅」删除整个订阅"
+ >
+ <Icon name="trash" className="w-4 h-4" />
+ </button>
+ </>
+ ) : (
+ <>
+ <button
+ className="rounded-md p-2 text-muted transition-colors hover:bg-hover hover:text-accent shrink-0"
+ onClick={() => onEdit(api.key)}
+ aria-label="编辑"
+ title="编辑"
+ >
+ <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"
+ onClick={remove}
+ aria-label="删除"
+ title="移除(可在提示中撤销)"
+ >
+ <Icon name="trash" className="w-4 h-4" />
+ </button>
+ </>
+ ))}
+ </div>
+ </li>
+ );
+}
- <section className="mb-6 border-t border-line pt-5">
- <SectionTitle title="封面图加载" />
- <div className="space-y-2">
- <SelectRow
- label="加载方式"
- value={store.imageProxyMode}
- onChange={(v) => store.updateSettings({ imageProxyMode: v as 'direct' | 'proxy' | 'custom' })}
- options={[
- { value: 'direct', label: '直连' },
- { value: 'proxy', label: '内置代理(默认)' },
- { value: 'custom', label: '自定义代理' },
- ]}
+// —— 偏好设置面板 ——
+
+function PlaybackPanel() {
+ const store = useAppStore();
+ return (
+ <section>
+ <SectionTitle title="播放与过滤" />
+ <div className="space-y-3">
+ <ToggleRow
+ label="广告过滤"
+ description="过滤 m3u8 中的广告分片"
+ checked={store.adFilter}
+ onChange={(v) => store.updateSettings({ adFilter: v })}
+ />
+ <ToggleRow
+ label="自动连播"
+ description="单集播放结束后自动播放下一集"
+ checked={store.autoplayNext}
+ onChange={(v) => store.updateSettings({ autoplayNext: v })}
+ />
+ </div>
+ </section>
+ );
+}
+
+function ImagePanel() {
+ const store = useAppStore();
+ return (
+ <section>
+ <SectionTitle title="封面图加载" />
+ <div className="space-y-2">
+ <SelectRow
+ label="加载方式"
+ value={store.imageProxyMode}
+ onChange={(v) => store.updateSettings({ imageProxyMode: v as 'direct' | 'proxy' | 'custom' })}
+ options={[
+ { value: 'direct', label: '直连' },
+ { value: 'proxy', label: '内置代理(默认)' },
+ { 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' && (
- <input
- className="input w-full"
- placeholder="代理模板,如 https://p.example.com/?url={url}"
- value={store.customImageProxy}
- onChange={(e) => store.updateSettings({ customImageProxy: e.target.value })}
- />
- )}
- <p className="text-xs text-faint">豆瓣封面在某些网络下直连会被拒绝,可切换为内置代理。</p>
- </div>
- </section>
- </>
- )}
+ )}
+ <p className="text-xs text-faint">豆瓣封面在某些网络下直连会被拒绝,可切换为内置代理。</p>
+ </div>
+ </section>
+ );
+}
- {settingsTab === 'config' && (
- <>
- <SourceSubscriptions />
- <section className="mb-6 pt-5 border-t border-line">
- <SectionTitle title="首页与内容过滤" />
- <div className="space-y-3">
- <ToggleRow
- label="成人内容过滤"
- description="过滤“伦理片”等分类的结果"
- checked={store.yellowFilter}
- onChange={(v) => store.updateSettings({ yellowFilter: v })}
- />
- <ToggleRow
- label="首页推荐"
- description="在首页展示推荐内容"
- checked={store.doubanEnabled}
- onChange={(v) => store.updateSettings({ doubanEnabled: v })}
- />
- <SelectRow
- label="推荐数据源"
- value={store.recommendSource}
- onChange={(v) => store.updateSettings({ recommendSource: v as 'douban' | 'bangumi' | 'hot-list' })}
- options={[
- { value: 'douban', label: '豆瓣(电影/剧集)' },
- { value: 'bangumi', label: 'Bangumi 新番放送' },
- { value: 'hot-list', label: '影视榜单(豆瓣周榜/百度热播)' },
- ]}
- />
- </div>
- </section>
- <section className="mb-6 pt-5 border-t border-line">
- <SectionTitle title="配置" />
- <ConfigIoButtons />
- </section>
- </>
- )}
- </Drawer>
+function HomePanel() {
+ const store = useAppStore();
+ return (
+ <section>
+ <SectionTitle title="首页与内容过滤" />
+ <div className="space-y-3">
+ <ToggleRow
+ label="成人内容过滤"
+ description="过滤“伦理片”等分类的结果"
+ checked={store.yellowFilter}
+ onChange={(v) => store.updateSettings({ yellowFilter: v })}
+ />
+ <ToggleRow
+ label="首页推荐"
+ description="在首页展示推荐内容"
+ checked={store.doubanEnabled}
+ onChange={(v) => store.updateSettings({ doubanEnabled: v })}
+ />
+ <SelectRow
+ label="推荐数据源"
+ value={store.recommendSource}
+ onChange={(v) => store.updateSettings({ recommendSource: v as 'douban' | 'bangumi' | 'hot-list' })}
+ options={[
+ { value: 'douban', label: '豆瓣(电影/剧集)' },
+ { value: 'bangumi', label: 'Bangumi 新番放送' },
+ { value: 'hot-list', label: '影视榜单(豆瓣周榜/百度热播)' },
+ ]}
+ />
+ </div>
+ </section>
);
}
+// —— 数据面板 ——
+
/**
* 数据源订阅 / 分享:
* - 订阅:填入远程订阅地址(LibreTV-SourceList JSON 或 TVBOX 配置 JSON,由服务端自动识别),
@@ -416,10 +643,12 @@ function SourceSubscriptions() {
const store = useAppStore();
const { toast } = useToast();
const [subUrl, setSubUrl] = useState('');
- const [syncing, setSyncing] = useState<string | null>(null);
+ // 每个订阅独立的同步状态,允许多个订阅并行同步(此前单值状态会串台)
+ const [syncing, setSyncing] = useState<Set<string>>(new Set());
+ const [pendingDelete, setPendingDelete] = useState<string | null>(null);
const sync = async (url: string) => {
- setSyncing(url);
+ setSyncing((prev) => new Set(prev).add(url));
try {
const { vodCount, liveCount, stats } = await syncSourceSubscription(url);
// 如实说明跳过/截断情况,避免用户疑惑「配置里站点很多,为何只导入了个位数」
@@ -430,7 +659,11 @@ function SourceSubscriptions() {
} catch (err) {
toast(err instanceof Error ? err.message : '订阅同步失败', 'error');
} finally {
- setSyncing(null);
+ setSyncing((prev) => {
+ const next = new Set(prev);
+ next.delete(url);
+ return next;
+ });
}
};
@@ -476,8 +709,16 @@ function SourceSubscriptions() {
toast(`已导出 ${sources.length} 个点播源、${liveSources.length} 个直播源,托管后即可被他人订阅`, 'success');
};
+ const deleteImpact = (url: string) => {
+ const prefix = subKeyPrefix(url);
+ return {
+ vod: store.customAPIs.filter((a) => keyBelongsToSubscription(a.key, prefix)).length,
+ live: store.liveSubscriptions.filter((s) => s.fromSubscriptions.includes(url)).length,
+ };
+ };
+
return (
- <section className="mb-6 pt-5">
+ <section>
<SectionTitle
title="数据源订阅 / 分享"
extra={
@@ -495,7 +736,7 @@ function SourceSubscriptions() {
/>
<div className="flex gap-2 mb-2">
<input
- className="input w-full"
+ className="input flex-1 min-w-0"
placeholder="订阅地址(LibreTV 源列表或 TVBOX 配置的 JSON URL)"
value={subUrl}
onChange={(e) => setSubUrl(e.target.value)}
@@ -503,8 +744,12 @@ function SourceSubscriptions() {
if (e.key === 'Enter') addAndSync();
}}
/>
- <button className="btn-primary !py-1.5 text-xs shrink-0" disabled={!subUrl.trim() || syncing !== null} onClick={addAndSync}>
- {syncing !== null ? '同步中…' : '订阅'}
+ <button
+ className="btn-primary !py-1.5 text-xs shrink-0"
+ disabled={!subUrl.trim() || syncing.size > 0}
+ onClick={addAndSync}
+ >
+ {syncing.size > 0 ? '同步中…' : '订阅'}
</button>
</div>
{store.subscriptions.length === 0 ? (
@@ -513,82 +758,215 @@ function SourceSubscriptions() {
「导出数据源」生成的 JSON 托管到任意 URL 即可分享给他人订阅。
</p>
) : (
- <ul className="space-y-2 max-h-[30vh] overflow-y-auto scrollbar-thin pr-1">
+ <ul className="space-y-2">
{store.subscriptions.map((sub) => {
const vodCount = store.customAPIs.filter((a) => keyBelongsToSubscription(a.key, subKeyPrefix(sub.url))).length;
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">
- <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>
- <div className="text-xs text-faint truncate">
- {sub.url}
- {sub.lastSync && ` · 同步于 ${formatRelativeTime(sub.lastSync)}`}
- </div>
- <div className="mt-1 flex gap-1">
- <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>
+ <li key={sub.url} className="bg-card rounded-lg p-3 transition-colors hover:bg-hover/50">
+ <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>
+ <div className="text-xs text-faint truncate">
+ {sub.url}
+ {sub.lastSync && ` · 同步于 ${formatRelativeTime(sub.lastSync)}`}
+ </div>
+ <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.lastStatus === 'error' ? (
+ <span
+ className="text-[10px] px-1.5 py-0.5 rounded bg-red-500/15 text-red-500"
+ 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">
+ 上次导入 {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>
+ )}
</div>
+ <button
+ className="rounded-md p-2 shrink-0 text-muted transition-colors hover:bg-hover hover:text-accent disabled:opacity-40"
+ disabled={isSyncing}
+ onClick={() => sync(sub.url)}
+ aria-label="重新同步"
+ title="重新同步(以远端列表为准,整体替换该订阅名下的点播源与直播源)"
+ >
+ {isSyncing ? (
+ <span className="block w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
+ ) : (
+ <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"
+ onClick={() => setPendingDelete(sub.url)}
+ aria-label="删除订阅"
+ title="删除订阅及其导入的点播源与直播源(保留收藏的频道)"
+ >
+ <Icon name="trash" className="w-4 h-4" />
+ </button>
</div>
- <button
- className="rounded-md p-1.5 shrink-0 text-muted transition-colors hover:bg-hover hover:text-accent disabled:opacity-40"
- // 同一时刻只允许一个同步在跑:syncing 是单值状态,并发会让先完成的提前解锁按钮
- disabled={syncing !== null}
- onClick={() => sync(sub.url)}
- aria-label="重新同步"
- title="重新同步(以远端列表为准,整体替换该订阅名下的点播源与直播源)"
- >
- {syncing === sub.url ? '…' : '⟳'}
- </button>
- <button
- className="rounded-md p-1.5 shrink-0 text-muted transition-colors hover:bg-hover hover:text-red-400"
- onClick={() => store.removeSubscription(sub.url)}
- aria-label="删除订阅"
- title="删除订阅及其导入的点播源与直播源(保留收藏的频道)"
- >
- ✕
- </button>
- </div>
- </li>
+ </li>
);
})}
</ul>
)}
+
+ {/* 重操作:删除订阅会级联移除其导入的源,先确认并说明影响面 */}
+ <ConfirmDialog
+ open={pendingDelete !== null}
+ danger
+ title="删除该订阅?"
+ message={
+ pendingDelete
+ ? (() => {
+ const impact = deleteImpact(pendingDelete);
+ const parts: string[] = [];
+ if (impact.vod > 0) parts.push(`${impact.vod} 个点播源`);
+ if (impact.live > 0) parts.push(`${impact.live} 个直播源`);
+ return parts.length > 0
+ ? `将同时删除该订阅导入的 ${parts.join(' 与 ')};你收藏的频道会保留。`
+ : '该订阅当前未导入任何源,删除后不影响其他数据。';
+ })()
+ : undefined
+ }
+ confirmLabel="删除订阅"
+ onCancel={() => setPendingDelete(null)}
+ onConfirm={() => {
+ const url = pendingDelete;
+ if (url) useAppStore.getState().removeSubscription(url);
+ setPendingDelete(null);
+ toast('订阅已删除', 'success');
+ }}
+ />
</section>
);
}
-/** 取 hostname 作为名称兜底;地址非法时原样返回 */
-function hostnameOf(url: string): string {
- try {
- return new URL(url).hostname;
- } catch {
- return url;
- }
-}
+/** 配置导入导出(导出受登录门控;导入前先解析预览再确认,避免误覆盖) */
+function ConfigIoPanel() {
+ const { toast } = useToast();
+ const { verified, openLogin } = useAuth();
+ const [pending, setPending] = useState<{ file: File; summary: string } | null>(null);
+
+ const doExport = async () => {
+ if (verified === false) {
+ openLogin();
+ return;
+ }
+ try {
+ const json = await exportConfig();
+ const blob = new Blob([json], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `LibreTV-Settings_${Date.now()}.json`;
+ a.click();
+ URL.revokeObjectURL(url);
+ toast('配置已导出', 'success');
+ } catch {
+ toast('导出失败', 'error');
+ }
+ };
+
+ const pickImport = async (file: File) => {
+ try {
+ const summary = summarizeConfig(await file.text());
+ setPending({ file, summary });
+ } catch (err) {
+ toast(err instanceof Error ? err.message : '导入失败', 'error');
+ }
+ };
+
+ const confirmImport = async () => {
+ if (!pending) return;
+ try {
+ await importConfig(await pending.file.text());
+ setPending(null);
+ toast('配置导入成功,即将刷新页面', 'success');
+ setTimeout(() => window.location.reload(), 1500);
+ } catch (err) {
+ toast(err instanceof Error ? err.message : '导入失败', 'error');
+ }
+ };
-function SectionTitle({ title, extra }: { title: string; extra?: React.ReactNode }) {
return (
- <div className="flex items-center justify-between mb-2.5">
- <h3 className="text-sm font-semibold text-content">{title}</h3>
- {extra}
- </div>
+ <section>
+ <SectionTitle title="配置导入导出" hint="导出/导入包含数据源、订阅与偏好设置的整机配置" />
+ <div className="flex gap-2">
+ <button className="btn-ghost flex-1 text-xs" onClick={doExport}>
+ 导出配置
+ </button>
+ <label className="btn-ghost flex-1 text-xs cursor-pointer">
+ 导入配置
+ <input
+ type="file"
+ accept=".json,application/json"
+ className="hidden"
+ onChange={(e) => {
+ const f = e.target.files?.[0];
+ if (f) void pickImport(f);
+ e.target.value = '';
+ }}
+ />
+ </label>
+ </div>
+
+ {/* 重操作:导入会覆盖全部配置,先确认并展示将导入的内容概要 */}
+ <ConfirmDialog
+ open={pending !== null}
+ danger
+ title="导入配置并覆盖当前数据?"
+ message={pending ? `${pending.summary}。导入后将立即刷新页面,当前设备上的配置与观看历史会被覆盖。` : undefined}
+ confirmLabel="导入并覆盖"
+ onCancel={() => setPending(null)}
+ onConfirm={confirmImport}
+ />
+ </section>
);
}
-function EmptySourceGuide({ onAdd }: { onAdd: () => void }) {
- return (
- <div className="border border-dashed border-line rounded-lg p-5 text-center">
- <p className="text-sm text-muted mb-1">还没有添加任何点播源</p>
- <p className="text-xs text-faint mb-3">
- 添加一个 Apple CMS 采集站 API 即可开始搜索影片;也可到「订阅与配置」一次导入点播源与直播源
- </p>
- <button className="btn-primary text-xs" onClick={onAdd}>
- 添加第一个点播源
- </button>
- </div>
- );
+/** 解析配置文件概要(宽松,仅用于导入前预览) */
+function summarizeConfig(text: string): string {
+ let cfg: { name?: string; data?: Record<string, unknown> };
+ try {
+ cfg = JSON.parse(text) as { name?: string; data?: Record<string, unknown> };
+ } catch {
+ throw new Error('文件不是合法的 JSON');
+ }
+ if (cfg.name !== 'LibreTV-Settings') throw new Error('不是 LibreTV 的配置文件');
+
+ const parts: string[] = [];
+ const settingsRaw = cfg.data?.['libretv-settings'];
+ if (typeof settingsRaw === 'string') {
+ try {
+ const state = (JSON.parse(settingsRaw) as { state?: Record<string, unknown> }).state ?? {};
+ const vod = Array.isArray(state.customAPIs) ? state.customAPIs.length : 0;
+ const live = Array.isArray(state.liveSubscriptions) ? state.liveSubscriptions.length : 0;
+ const subs = Array.isArray(state.subscriptions) ? state.subscriptions.length : 0;
+ parts.push(`${vod} 个点播源`, `${live} 个直播源`, `${subs} 个订阅`);
+ } catch {
+ /* 设置片段损坏时忽略该部分统计 */
+ }
+ }
+ const historyRaw = cfg.data?.['viewingHistory'];
+ if (typeof historyRaw === 'string') {
+ try {
+ const h = JSON.parse(historyRaw);
+ if (Array.isArray(h)) parts.push(`${h.length} 条观看历史`);
+ } catch {
+ /* 忽略 */
+ }
+ }
+ return parts.length > 0 ? `该文件包含 ${parts.join('、')}` : '该文件未包含可导入的数据';
}
function SourceForm({
@@ -634,7 +1012,7 @@ function SourceForm({
};
return (
- <div className="space-y-2 border border-line rounded-lg p-3 bg-chip">
+ <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"
@@ -649,7 +1027,12 @@ function SourceForm({
onChange={(e) => setDetail(e.target.value)}
/>
<label className="flex items-center gap-2 text-xs text-muted">
- <input type="checkbox" className="h-3.5 w-3.5 accent-pink-500" checked={isAdult} onChange={(e) => setIsAdult(e.target.checked)} />
+ <input
+ type="checkbox"
+ className="h-3.5 w-3.5 accent-pink-500"
+ checked={isAdult}
+ onChange={(e) => setIsAdult(e.target.checked)}
+ />
标记为成人内容源(受成人过滤控制)
</label>
<div className="flex gap-2 justify-end">
@@ -663,140 +1046,3 @@ function SourceForm({
</div>
);
}
-
-function ToggleRow({
- label,
- description,
- checked,
- onChange,
-}: {
- label: string;
- description: string;
- checked: boolean;
- onChange: (v: boolean) => void;
-}) {
- return (
- <div className="flex items-center justify-between gap-4 py-0.5">
- <div className="min-w-0">
- <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}
- 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)}
- >
- <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>
- );
-}
-
-function SelectRow({
- label,
- value,
- onChange,
- options,
-}: {
- label: string;
- value: string;
- onChange: (v: string) => void;
- options: { value: string; label: string }[];
-}) {
- return (
- <div className="flex items-center justify-between gap-4">
- <span className="text-sm text-content">{label}</span>
- <div className="relative">
- <select
- className="input !py-1.5 !pl-2.5 !pr-7 cursor-pointer appearance-none text-xs"
- value={value}
- onChange={(e) => onChange(e.target.value)}
- aria-label={label}
- >
- {options.map((o) => (
- <option key={o.value} value={o.value}>
- {o.label}
- </option>
- ))}
- </select>
- <svg
- className="pointer-events-none absolute right-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-faint"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- aria-hidden
- >
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
- </svg>
- </div>
- </div>
- );
-}
-
-function ConfigIoButtons() {
- const { toast } = useToast();
- const { verified, openLogin } = useAuth();
-
- const doExport = async () => {
- if (verified === false) {
- openLogin();
- return;
- }
- try {
- const json = await exportConfig();
- const blob = new Blob([json], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `LibreTV-Settings_${Date.now()}.json`;
- a.click();
- URL.revokeObjectURL(url);
- toast('配置已导出', 'success');
- } catch {
- toast('导出失败', 'error');
- }
- };
-
- const doImport = async (file: File) => {
- try {
- const content = await file.text();
- await importConfig(content);
- toast('配置导入成功,即将刷新页面', 'success');
- setTimeout(() => window.location.reload(), 1500);
- } catch (err) {
- toast(err instanceof Error ? err.message : '导入失败', 'error');
- }
- };
-
- return (
- <div className="flex gap-2">
- <button className="btn-ghost flex-1 text-xs" onClick={doExport}>
- 导出配置
- </button>
- <label className="btn-ghost flex-1 text-xs cursor-pointer">
- 导入配置
- <input
- type="file"
- accept=".json,application/json"
- className="hidden"
- onChange={(e) => {
- const f = e.target.files?.[0];
- if (f) doImport(f);
- e.target.value = '';
- }}
- />
- </label>
- </div>
- );
-}
diff --git a/src/components/toast.tsx b/src/components/toast.tsx
index 579b592..8c98cfb 100644
--- a/src/components/toast.tsx
+++ b/src/components/toast.tsx
@@ -3,16 +3,32 @@
import { createContext, useCallback, useContext, useRef, useState, type ReactNode } from 'react';
import { cn } from '@/lib/utils';
-// —— Toast —— 替代旧版 3 秒/条串行队列,支持并行堆叠与自动过期
+// —— Toast —— 替代旧版 3 秒/条串行队列,支持并行堆叠与自动过期;
+// 支持可选操作按钮(如「撤销」),用于轻量破坏性操作的即时回退。
+
+export type ToastType = 'error' | 'success' | 'info' | 'warning';
+
+export interface ToastAction {
+ label: string;
+ onClick: () => void;
+}
+
+export interface ToastOptions {
+ /** 操作按钮,例如删除后的「撤销」;点击后该条提示立即消失 */
+ action?: ToastAction;
+ /** 展示时长(ms);带 action 的操作默认 6000,普通提示默认 3000 */
+ duration?: number;
+}
interface ToastItem {
id: number;
message: string;
- type: 'error' | 'success' | 'info' | 'warning';
+ type: ToastType;
+ action?: ToastAction;
}
interface ToastContextValue {
- toast: (message: string, type?: ToastItem['type']) => void;
+ toast: (message: string, type?: ToastType, options?: ToastOptions) => void;
}
const ToastContext = createContext<ToastContextValue>({ toast: () => {} });
@@ -21,7 +37,7 @@ export function useToast(): ToastContextValue {
return useContext(ToastContext);
}
-const TYPE_STYLES: Record<ToastItem['type'], string> = {
+const TYPE_STYLES: Record<ToastType, string> = {
error: 'bg-red-500',
success: 'bg-green-600',
info: 'bg-blue-500',
@@ -31,15 +47,33 @@ const TYPE_STYLES: Record<ToastItem['type'], string> = {
export function ToastProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<ToastItem[]>([]);
const idRef = useRef(0);
+ const timersRef = useRef(new Map<number, ReturnType<typeof setTimeout>>());
- const toast = useCallback((message: string, type: ToastItem['type'] = 'info') => {
- const id = ++idRef.current;
- setItems((prev) => [...prev.slice(-3), { id, message, type }]);
- setTimeout(() => {
- setItems((prev) => prev.filter((t) => t.id !== id));
- }, 3000);
+ const dismiss = useCallback((id: number) => {
+ const timer = timersRef.current.get(id);
+ if (timer) {
+ clearTimeout(timer);
+ timersRef.current.delete(id);
+ }
+ setItems((prev) => prev.filter((t) => t.id !== id));
}, []);
+ const toast = useCallback(
+ (message: string, type: ToastType = 'info', options?: ToastOptions) => {
+ const id = ++idRef.current;
+ const duration = options?.duration ?? (options?.action ? 6000 : 3000);
+ setItems((prev) => [...prev.slice(-3), { id, message, type, action: options?.action }]);
+ timersRef.current.set(
+ id,
+ setTimeout(() => {
+ timersRef.current.delete(id);
+ setItems((prev) => prev.filter((t) => t.id !== id));
+ }, duration)
+ );
+ },
+ []
+ );
+
return (
<ToastContext.Provider value={{ toast }}>
{children}
@@ -49,10 +83,22 @@ export function ToastProvider({ children }: { children: ReactNode }) {
key={t.id}
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',
TYPE_STYLES[t.type]
)}
>
- {t.message}
+ <span>{t.message}</span>
+ {t.action && (
+ <button
+ className="shrink-0 font-medium underline underline-offset-2 hover:opacity-80 transition-opacity"
+ onClick={() => {
+ dismiss(t.id);
+ t.action?.onClick();
+ }}
+ >
+ {t.action.label}
+ </button>
+ )}
</div>
))}
</div>
diff --git a/src/components/use-source-probe.ts b/src/components/use-source-probe.ts
new file mode 100644
index 0000000..046baa9
--- /dev/null
+++ b/src/components/use-source-probe.ts
@@ -0,0 +1,101 @@
+'use client';
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { api } from '@/lib/client-api';
+import { useAppStore } from '@/lib/store';
+import type { SourceSearchOutcome } from '@/lib/types';
+
+/**
+ * 点播源批量探活 hook:
+ * - 受控并发(点播源上限 100,并发 4 足够快且不会同时压垮多个源站);
+ * - 进度实时回传(已完成 / 总数 / 可用数),可随时中止(已完成结果保留);
+ * - 结果写入 store 的 sourceHealth,与搜索过程共用同一份健康度模型
+ * (因此连续失败达阈值会临时停用,与搜索行为一致,不再出现两套「健康度」)。
+ */
+
+/** 同时在途的探测数 */
+const CONCURRENCY = 4;
+
+export interface SourceProbeProgress {
+ done: number;
+ total: number;
+ /** 已完成中可用的数量(能返回搜索结果) */
+ ok: number;
+ /** 本轮开始时间(用于估算剩余时间) */
+ startedAt: number;
+}
+
+export function useSourceProbe() {
+ const [progress, setProgress] = useState<SourceProbeProgress | null>(null);
+ const runIdRef = useRef(0);
+
+ useEffect(
+ () => () => {
+ // 卸载时作废在途轮次,避免结果写回已卸载组件的状态
+ runIdRef.current++;
+ },
+ []
+ );
+
+ /** 中止在途测活:已完成的结果保留 */
+ const cancel = useCallback(() => {
+ runIdRef.current++;
+ setProgress(null);
+ }, []);
+
+ const probe = useCallback(async (sources: { key: string; url: string }[]) => {
+ if (sources.length === 0) return;
+ const runId = ++runIdRef.current;
+ const total = sources.length;
+ const startedAt = Date.now();
+ setProgress({ done: 0, total, ok: 0, startedAt });
+
+ const outcomes: SourceSearchOutcome[] = [];
+ let done = 0;
+ let okCount = 0;
+ let cursor = 0;
+ // 进度写回节流:批量测活结果密集到达,避免每个源都触发一次渲染
+ let lastFlush = 0;
+ const flush = (force = false) => {
+ const now = Date.now();
+ if (!force && now - lastFlush < 150) return;
+ lastFlush = now;
+ setProgress({ done, total, ok: okCount, startedAt });
+ };
+
+ const worker = async () => {
+ for (;;) {
+ if (runIdRef.current !== runId) return;
+ const index = cursor++;
+ if (index >= sources.length) return;
+ const source = sources[index];
+ let outcome: SourceSearchOutcome;
+ try {
+ const r = await api.testSource(source.url);
+ outcome = { sourceKey: source.key, ok: r.ok, ms: r.ms, error: r.error, list: [] };
+ } catch (err) {
+ outcome = {
+ sourceKey: source.key,
+ ok: false,
+ error: err instanceof Error ? err.message : '测试失败',
+ list: [],
+ };
+ }
+ if (runIdRef.current !== runId) return;
+ outcomes.push(outcome);
+ done++;
+ if (outcome.ok) okCount++;
+ flush();
+ }
+ };
+
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, sources.length) }, worker));
+ if (runIdRef.current !== runId) return undefined;
+ useAppStore.getState().recordSourceHealth(outcomes);
+ setProgress(null);
+ // 返回汇总供调用方提示;被取消时返回 undefined
+ return { total, ok: okCount };
+ }, []);
+
+ return { progress, probe, cancel, isProbing: progress !== null };
+}
diff --git a/src/lib/store.test.ts b/src/lib/store.test.ts
index 7782ef8..7c202d7 100644
--- a/src/lib/store.test.ts
+++ b/src/lib/store.test.ts
@@ -183,3 +183,65 @@ describe('订阅同步的 store 语义', () => {
expect(store().liveFavorites).toContain(exclusive);
});
});
+
+describe('可撤销删除与订阅同步状态', () => {
+ it('删除点播源返回快照,撤销后恢复条目与勾选状态', () => {
+ useAppStore.setState({
+ customAPIs: [{ key: 'manual_0', name: '源A', url: 'https://x/api.php/provide/vod' }],
+ selectedKeys: ['manual_0'],
+ });
+
+ const snapshot = store().removeCustomApi('manual_0');
+ expect(snapshot).not.toBeNull();
+ expect(store().customAPIs).toHaveLength(0);
+ expect(store().selectedKeys).toHaveLength(0);
+
+ expect(store().restoreCustomApi(snapshot!)).toBe(true);
+ expect(store().customAPIs.map((a) => a.key)).toEqual(['manual_0']);
+ expect(store().selectedKeys).toEqual(['manual_0']);
+ });
+
+ it('原 key 被重新占用时放弃撤销,避免出现重复条目', () => {
+ useAppStore.setState({
+ customAPIs: [{ key: 'manual_0', name: '源A', url: 'https://x/api.php/provide/vod' }],
+ selectedKeys: [],
+ });
+ const snapshot = store().removeCustomApi('manual_0')!;
+ // 期间同 key 的源又出现(如订阅重新同步生成)
+ useAppStore.setState({
+ customAPIs: [{ key: 'manual_0', name: '新源', url: 'https://y/api.php/provide/vod' }],
+ });
+
+ expect(store().restoreCustomApi(snapshot)).toBe(false);
+ expect(store().customAPIs).toHaveLength(1);
+ expect(store().customAPIs[0].name).toBe('新源');
+ });
+
+ it('删除不存在的点播源返回 null', () => {
+ expect(store().removeCustomApi('nope')).toBeNull();
+ });
+
+ it('删除直播源返回快照,撤销后恢复条目与启用状态', () => {
+ store().addLiveSubscription('https://live.example.com/1.m3u', '手动');
+ const snapshot = store().removeLiveSubscription('https://live.example.com/1.m3u');
+ expect(snapshot).not.toBeNull();
+ expect(store().liveSubscriptions).toHaveLength(0);
+ expect(store().liveSelectedUrls).toHaveLength(0);
+
+ store().restoreLiveSubscription(snapshot!);
+ expect(store().liveSubscriptions.map((s) => s.url)).toEqual(['https://live.example.com/1.m3u']);
+ expect(store().liveSelectedUrls).toEqual(['https://live.example.com/1.m3u']);
+ });
+
+ it('同步成功记录状态与数量;同步失败记录原因且保留上次数量', () => {
+ const url = 'https://a.example.com/list.json';
+ store().addSubscription(url, 'A');
+ store().markSubscriptionSynced(url, 'A', { vod: 3, live: 1 });
+ expect(store().subscriptions[0]).toMatchObject({ lastStatus: 'ok', lastCounts: { vod: 3, live: 1 } });
+ expect(typeof store().subscriptions[0].lastSync).toBe('number');
+
+ store().markSubscriptionFailed(url, '网络错误');
+ expect(store().subscriptions[0]).toMatchObject({ lastStatus: 'error', lastError: '网络错误' });
+ expect(store().subscriptions[0].lastCounts).toEqual({ vod: 3, live: 1 });
+ });
+});
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 6662c76..11d80a8 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -23,6 +23,12 @@ export interface AppSettings {
customImageProxy: string;
}
+/** 一次订阅同步导入的数量(点播 / 直播),用于列表内展示同步结果 */
+export interface SubscriptionSyncCounts {
+ vod: number;
+ live: number;
+}
+
/**
* 数据源订阅:远程源列表(LibreTV-SourceList JSON 或 TVBOX 配置 JSON,由服务端自动识别),可一键同步更新。
* 一份订阅同时下发点播源与直播源;老订阅只有点播源。订阅内容一律归一化为本站源结构,故存储层与格式无关。
@@ -33,6 +39,24 @@ export interface SourceSubscription {
name?: string;
/** 上次同步成功时间 */
lastSync?: number;
+ /** 上次同步结果;undefined 表示尚未同步过 */
+ lastStatus?: 'ok' | 'error';
+ /** 上次同步的失败原因(lastStatus 为 error 时展示,保留到下次同步) */
+ lastError?: string;
+ /** 上次成功同步导入的数量统计 */
+ lastCounts?: SubscriptionSyncCounts;
+}
+
+/** 删除点播源后的撤销快照 */
+export interface RemovedSourceSnapshot {
+ entry: SourceConfig;
+ selected: boolean;
+}
+
+/** 删除直播源后的撤销快照 */
+export interface RemovedLiveSnapshot {
+ entry: LiveSubscription;
+ selected: boolean;
}
/** 直播源:远程 M3U 播放列表;可来自用户手动添加,也可来自统一订阅 */
@@ -147,20 +171,30 @@ interface AppState extends AppSettings {
envSubsSeen: string[];
addCustomApi: (api: Omit<SourceConfig, 'key'> & { key?: string }) => void;
updateCustomApi: (key: string, patch: Partial<SourceConfig>) => void;
- removeCustomApi: (key: string) => void;
+ /** 删除点播源;返回被删快照供撤销,key 不存在时返回 null */
+ removeCustomApi: (key: string) => RemovedSourceSnapshot | null;
+ /** 撤销删除;原 key 已被占用(如订阅重新同步占用)时放弃并返回 false */
+ restoreCustomApi: (snapshot: RemovedSourceSnapshot) => boolean;
toggleSourceSelected: (key: string) => void;
setSelectedKeys: (keys: string[]) => void;
setEnvSources: (list: SourceConfig[]) => void;
addSubscription: (url: string, name?: string) => void;
removeSubscription: (url: string) => void;
- markSubscriptionSynced: (url: string, name?: string) => void;
+ markSubscriptionSynced: (url: string, name?: string, counts?: SubscriptionSyncCounts) => void;
+ /** 记录一次同步失败(保留该订阅与已导入的源,仅更新状态供列表展示) */
+ markSubscriptionFailed: (url: string, error: string) => void;
/** 用订阅内容整体替换该订阅名下的点播源,返回新增数量 */
applySubscriptionSources: (subUrl: string, list: Omit<SourceConfig, 'key'>[]) => number;
/** 用订阅内容整体替换该订阅名下的直播源,返回新增数量 */
applySubscriptionLive: (subUrl: string, list: Omit<LiveSourceConfig, 'key'>[]) => number;
setLiveEnvSources: (list: LiveSourceConfig[]) => void;
addLiveSubscription: (url: string, name?: string, epg?: string) => void;
- removeLiveSubscription: (url: string) => void;
+ /** 删除直播源;返回被删快照供撤销,不存在时返回 null */
+ removeLiveSubscription: (url: string) => RemovedLiveSnapshot | null;
+ /** 撤销删除直播源(恢复条目与其启用状态) */
+ restoreLiveSubscription: (snapshot: RemovedLiveSnapshot) => void;
+ /** 更新直播源的名称/EPG(地址不可改:换地址等于换源,会影响启用状态与最近观看关联) */
+ updateLiveSubscription: (url: string, patch: { name?: string; epg?: string }) => void;
markLiveSynced: (url: string, name?: string, epg?: string) => void;
toggleLiveSelected: (url: string) => void;
toggleLiveFavorite: (channelUrl: string) => void;
@@ -243,10 +277,24 @@ export const useAppStore = create<AppState>()(
},
removeCustomApi: (key) => {
+ const entry = get().customAPIs.find((a) => a.key === key);
+ if (!entry) return null;
+ const selected = get().selectedKeys.includes(key);
set({
customAPIs: get().customAPIs.filter((a) => a.key !== key),
selectedKeys: get().selectedKeys.filter((k) => k !== key),
});
+ return { entry, selected };
+ },
+
+ restoreCustomApi: ({ entry, selected }) => {
+ // key 已被重新占用(如订阅重新同步生成了同 key 的源)时放弃撤销,避免出现重复条目
+ if (get().customAPIs.some((a) => a.key === entry.key)) return false;
+ set({
+ customAPIs: [...get().customAPIs, entry],
+ selectedKeys: selected ? [...get().selectedKeys, entry.key] : get().selectedKeys,
+ });
+ return true;
},
toggleSourceSelected: (key) => {
@@ -308,10 +356,28 @@ export const useAppStore = create<AppState>()(
});
},
- markSubscriptionSynced: (url, name) => {
+ markSubscriptionSynced: (url, name, counts) => {
+ set({
+ subscriptions: get().subscriptions.map((s) =>
+ s.url === url
+ ? {
+ ...s,
+ lastSync: Date.now(),
+ name: name ?? s.name,
+ lastStatus: 'ok',
+ lastError: undefined,
+ lastCounts: counts ?? s.lastCounts,
+ }
+ : s
+ ),
+ });
+ },
+
+ markSubscriptionFailed: (url, error) => {
+ // 失败不清空已导入的源(旧数据保留),仅记录状态供列表展示
set({
subscriptions: get().subscriptions.map((s) =>
- s.url === url ? { ...s, lastSync: Date.now(), name: name ?? s.name } : s
+ s.url === url ? { ...s, lastStatus: 'error', lastError: error } : s
),
});
},
@@ -421,10 +487,30 @@ export const useAppStore = create<AppState>()(
},
removeLiveSubscription: (url) => {
+ const entry = get().liveSubscriptions.find((s) => s.url === url);
+ if (!entry) return null;
+ const selected = get().liveSelectedUrls.includes(url);
set({
liveSubscriptions: get().liveSubscriptions.filter((s) => s.url !== url),
liveSelectedUrls: get().liveSelectedUrls.filter((u) => u !== url),
});
+ return { entry, selected };
+ },
+
+ restoreLiveSubscription: ({ entry, selected }) => {
+ if (get().liveSubscriptions.some((s) => s.url === entry.url)) return;
+ set({
+ liveSubscriptions: [...get().liveSubscriptions, entry],
+ liveSelectedUrls: selected
+ ? [...new Set([...get().liveSelectedUrls, entry.url])]
+ : get().liveSelectedUrls,
+ });
+ },
+
+ updateLiveSubscription: (url, patch) => {
+ set({
+ liveSubscriptions: get().liveSubscriptions.map((s) => (s.url === url ? { ...s, ...patch } : s)),
+ });
},
toggleLiveSelected: (url) => {
diff --git a/src/lib/subscription-sync.ts b/src/lib/subscription-sync.ts
index ca74907..bf2db69 100644
--- a/src/lib/subscription-sync.ts
+++ b/src/lib/subscription-sync.ts
@@ -27,26 +27,33 @@ export async function syncSourceSubscription(rawUrl: string): Promise<Subscripti
// 统一归一化(trim + 去尾斜杠):与 DEFAULT_SUBSCRIPTIONS 预置地址保持同一形态,
// 避免同一订阅地址因尾斜杠差异被存成两条订阅
const url = normalizeSubscriptionUrl(rawUrl);
- const { name, sources, liveSources, stats } = await api.fetchSourceList(url);
- if (sources.length === 0 && liveSources.length === 0) {
- throw new Error('订阅内容为空');
- }
- const store = useAppStore.getState();
- const vodCount = store.applySubscriptionSources(url, sources);
- const liveCount = store.applySubscriptionLive(url, liveSources);
- // 仅对本订阅引用的直播源记录同步时间(多归属:共享源也会被标记为新鲜,
- // 但名称/EPG 由 store 的「首次导入为准、缺失补齐」语义保护,不会被本订阅覆盖)
- const importedLiveUrls = new Set(
- useAppStore.getState().liveSubscriptions
- .filter((s) => s.fromSubscriptions.includes(url))
- .map((s) => s.url)
- );
- for (const s of liveSources) {
- if (importedLiveUrls.has(s.url)) store.markLiveSynced(s.url, s.name, s.epg);
+ try {
+ const { name, sources, liveSources, stats } = await api.fetchSourceList(url);
+ if (sources.length === 0 && liveSources.length === 0) {
+ throw new Error('订阅内容为空');
+ }
+ const store = useAppStore.getState();
+ const vodCount = store.applySubscriptionSources(url, sources);
+ const liveCount = store.applySubscriptionLive(url, liveSources);
+ // 仅对本订阅引用的直播源记录同步时间(多归属:共享源也会被标记为新鲜,
+ // 但名称/EPG 由 store 的「首次导入为准、缺失补齐」语义保护,不会被本订阅覆盖)
+ const importedLiveUrls = new Set(
+ useAppStore.getState().liveSubscriptions
+ .filter((s) => s.fromSubscriptions.includes(url))
+ .map((s) => s.url)
+ );
+ for (const s of liveSources) {
+ if (importedLiveUrls.has(s.url)) store.markLiveSynced(s.url, s.name, s.epg);
+ }
+ store.addSubscription(url, name);
+ store.markSubscriptionSynced(url, name, { vod: vodCount, live: liveCount });
+ return { name, vodCount, liveCount, stats };
+ } catch (err) {
+ // 记录失败状态供订阅列表展示(首次添加未成功时不产生条目);已导入的旧数据保持不动
+ const message = err instanceof Error ? err.message : '订阅同步失败';
+ useAppStore.getState().markSubscriptionFailed(url, message);
+ throw err instanceof Error ? err : new Error(message);
}
- store.addSubscription(url, name);
- store.markSubscriptionSynced(url, name);
- return { name, vodCount, liveCount, stats };
}
/** 预置订阅超过该间隔未同步时,启动阶段静默刷新一次 */
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
index 17c56f5..297b32a 100644
--- a/src/lib/utils.ts
+++ b/src/lib/utils.ts
@@ -58,6 +58,15 @@ export function validateSourceUrl(url: string): boolean {
return /^https?:\/\/.+/.test(url);
}
+/** 取 hostname 作为名称兜底;地址非法时原样返回 */
+export function hostnameOf(url: string): string {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return url;
+ }
+}
+
/** 为分享链接等场景构造观看页 URL */
export function buildWatchUrl(params: {
sourceKey: string;