Skip to content

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

feat(live): 频道侧栏交互与性能全面优化,版本 2.9.2

bestZwei39bbab3ffb60
diff --git a/package-lock.json b/package-lock.json
index 8a17a37..5b05f3c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "libretv",
- "version": "2.4.1",
+ "version": "2.9.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "libretv",
- "version": "2.4.1",
+ "version": "2.9.2",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@tanstack/react-query": "^5.59.0",
diff --git a/package.json b/package.json
index 47dd5b5..2da44f9 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "libretv",
- "version": "2.9.1",
+ "version": "2.9.2",
"private": true,
"description": "免费在线视频搜索与观看平台(Next.js 重构版)",
"license": "AGPL-3.0-or-later",
diff --git a/src/app/api/live/playlist/route.ts b/src/app/api/live/playlist/route.ts
index af31be6..e19ab0f 100644
--- a/src/app/api/live/playlist/route.ts
+++ b/src/app/api/live/playlist/route.ts
@@ -1,7 +1,8 @@
import { NextResponse } from 'next/server';
import { guardRequest, jsonError } from '@/lib/api-guard';
import { checkLiveUrlAllowed } from '@/lib/ssrf';
-import { fetchUpstream, getCache, setCache } from '@/lib/fetch-utils';
+import { fetchUpstream } from '@/lib/fetch-utils';
+import { getLiveCache, setLiveCache } from '@/lib/live-cache';
import { parseM3u } from '@/lib/m3u-parser';
import type { LivePlaylistResponse } from '@/lib/types';
@@ -60,7 +61,8 @@ export async function GET(req: Request) {
const verdict = await checkLiveUrlAllowed(url);
if (!verdict.ok) return jsonError(verdict.reason, 403);
- let playlist: LivePlaylistResponse | undefined = force ? undefined : getCache(cacheKey(url));
+ // 直播专用缓存:数千频道的播放列表 JSON 不与豆瓣等热点数据共池(通用缓存超限会整体 clear)
+ let playlist: LivePlaylistResponse | undefined = force ? undefined : getLiveCache<LivePlaylistResponse>(cacheKey(url));
if (!playlist) {
let text: string;
try {
@@ -78,7 +80,7 @@ export async function GET(req: Request) {
(a, b) => a.localeCompare(b, 'zh')
);
playlist = { name: extractPlaylistName(text), channels, groups };
- setCache(cacheKey(url), playlist, CACHE_TTL_MS);
+ setLiveCache(cacheKey(url), playlist, CACHE_TTL_MS, text.length);
}
if (format === 'm3u') {
diff --git a/src/app/live/page.tsx b/src/app/live/page.tsx
index ad078d3..47ed342 100644
--- a/src/app/live/page.tsx
+++ b/src/app/live/page.tsx
@@ -1,6 +1,6 @@
'use client';
-import { Suspense, useCallback, useMemo, useState } from 'react';
+import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/client-api';
@@ -15,6 +15,8 @@ import { buildImageUrl, cn } from '@/lib/utils';
/**
* 直播页:左侧播放器 + 频道信息 + 节目单;右侧频道侧栏。
* 状态由 URL 驱动(?url=&name=&group=&tvgId=&epg=),支持频道深链与刷新保持。
+ * 换台路径:侧栏点击、全局 ↑↓ 键盘、播放器控制条上一台/下一台(全屏可用)。
+ * 移动端侧栏为底部抽屉(右下角 FAB 呼出,选中频道后自动收起)。
*/
export default function LivePage() {
return (
@@ -49,17 +51,25 @@ async function copyText(text: string): Promise<boolean> {
function LiveContent() {
const searchParams = useSearchParams();
const router = useRouter();
- const store = useAppStore();
+ // 精确订阅所需字段:任何其他 store 变化(如测活写回)不应触发本组件重渲染
+ const liveSelectedUrls = useAppStore((s) => s.liveSelectedUrls);
+ const liveEnvSources = useAppStore((s) => s.liveEnvSources);
+ const liveSubscriptions = useAppStore((s) => s.liveSubscriptions);
+ const liveFavorites = useAppStore((s) => s.liveFavorites);
const imageProxyMode = useAppStore((s) => s.imageProxyMode);
const customImageProxy = useAppStore((s) => s.customImageProxy);
const { verified } = useAuth();
const [copied, setCopied] = useState(false);
+ // 移动端频道抽屉开合
+ const [listOpen, setListOpen] = useState(false);
+ /** 侧栏上报的筛选排序结果(键盘换台沿此列表顺序);ref 存储,不触发重渲染 */
+ const filteredRef = useRef<LiveChannelItem[]>([]);
// 仅聚合已启用的直播源(设置 → 直播源中的勾选状态)
const sources = useMemo(() => {
- const selected = new Set(store.liveSelectedUrls);
- return allLiveSources(store).filter((s) => selected.has(s.url));
- }, [store]);
+ const selected = new Set(liveSelectedUrls);
+ return allLiveSources({ liveEnvSources, liveSubscriptions }).filter((s) => selected.has(s.url));
+ }, [liveSelectedUrls, liveEnvSources, liveSubscriptions]);
// 聚合全部直播源的 M3U 解析结果(单源失败不影响整体)
const playlistsQuery = useQuery({
@@ -116,7 +126,7 @@ function LiveContent() {
if (c.tvgId) sp.set('tvgId', c.tvgId);
if (c.epg) sp.set('epg', c.epg);
router.replace(`/live?${sp.toString()}`, { scroll: false });
- store.addLiveRecent({
+ useAppStore.getState().addLiveRecent({
url: c.url,
name: c.name,
logo: c.logo,
@@ -126,7 +136,56 @@ function LiveContent() {
sourceUrl: c.sourceUrl,
});
},
- [router, store]
+ [router]
+ );
+
+ const handleFilteredChange = useCallback((list: LiveChannelItem[]) => {
+ filteredRef.current = list;
+ }, []);
+
+ /** 沿侧栏当前筛选排序的列表顺序切上一台/下一台(循环) */
+ const switchChannelByOffset = useCallback(
+ (delta: 1 | -1) => {
+ const list = filteredRef.current;
+ if (list.length === 0) return;
+ const nowUrl = new URLSearchParams(window.location.search).get('url') || '';
+ const idx = list.findIndex((c) => c.url === nowUrl);
+ const next =
+ idx === -1 ? (delta === 1 ? 0 : list.length - 1) : (idx + delta + list.length) % list.length;
+ selectChannel(list[next]);
+ },
+ [selectChannel]
+ );
+
+ const goPrevChannel = useCallback(() => switchChannelByOffset(-1), [switchChannelByOffset]);
+ const goNextChannel = useCallback(() => switchChannelByOffset(1), [switchChannelByOffset]);
+
+ // 全局键盘换台:↑↓ 直接切台。输入框/列表光标导航场景让位(列表聚焦时由列表内 ↑↓ 管理光标)
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
+ if (e.repeat || e.altKey || e.ctrlKey || e.metaKey) return;
+ const target = e.target as HTMLElement | null;
+ if (target) {
+ if (target.isContentEditable) return;
+ const tag = target.tagName;
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
+ if (target.closest('[data-channel-list]')) return;
+ }
+ e.preventDefault();
+ switchChannelByOffset(e.key === 'ArrowDown' ? 1 : -1);
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [switchChannelByOffset]);
+
+ const handleSelect = useCallback(
+ (c: LiveChannelItem) => {
+ selectChannel(c);
+ // 移动端抽屉:选中即收起
+ setListOpen(false);
+ },
+ [selectChannel]
);
if (!verified) {
@@ -141,6 +200,7 @@ function LiveContent() {
}
const logo = buildImageUrl(currentChannel?.logo, imageProxyMode, customImageProxy);
+ const isFavorite = currentChannel ? liveFavorites.includes(currentChannel.url) : false;
return (
<div className="min-h-screen flex flex-col">
@@ -151,13 +211,18 @@ function LiveContent() {
<div className="min-w-0">
<div className="aspect-video bg-black rounded-lg overflow-hidden">
{currentUrl ? (
- <LivePlayer url={currentUrl} title={currentChannel?.name || '直播'} />
+ <LivePlayer
+ url={currentUrl}
+ title={currentChannel?.name || '直播'}
+ onPrevChannel={goPrevChannel}
+ onNextChannel={goNextChannel}
+ />
) : (
<div className="w-full h-full flex flex-col items-center justify-center gap-2 bg-black">
<span className="live-dot" />
<p className="text-white/60 text-sm">
{sources.length === 0
- ? store.liveEnvSources.length + store.liveSubscriptions.length > 0
+ ? liveEnvSources.length + liveSubscriptions.length > 0
? '所有直播源均已停用,请在设置中勾选启用'
: '请先在设置中添加直播源(M3U 订阅)'
: playlistsQuery.isLoading
@@ -190,20 +255,48 @@ function LiveContent() {
<p className="text-xs text-faint truncate mt-0.5">{currentChannel.url}</p>
</div>
<div className="flex items-center gap-1 shrink-0">
+ <button
+ className="rounded-md p-2 text-muted hover:text-accent hover:bg-hover transition-colors"
+ aria-label="上一台"
+ title="上一台(↑)"
+ onClick={goPrevChannel}
+ >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
+ />
+ </svg>
+ </button>
+ <button
+ className="rounded-md p-2 text-muted hover:text-accent hover:bg-hover transition-colors"
+ aria-label="下一台"
+ title="下一台(↓)"
+ onClick={goNextChannel}
+ >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M13 5l7 7-7 7M5 5l7 7-7 7"
+ />
+ </svg>
+ </button>
<button
className={cn(
'rounded-md p-2 transition-colors',
- store.liveFavorites.includes(currentChannel.url)
- ? 'text-amber-400'
- : 'text-muted hover:text-amber-400 hover:bg-hover'
+ isFavorite ? 'text-amber-400' : 'text-muted hover:text-amber-400 hover:bg-hover'
)}
aria-label="收藏"
title="收藏"
- onClick={() => store.toggleLiveFavorite(currentChannel.url)}
+ onClick={() => useAppStore.getState().toggleLiveFavorite(currentChannel.url)}
>
<svg
className="w-4 h-4"
- fill={store.liveFavorites.includes(currentChannel.url) ? 'currentColor' : 'none'}
+ fill={isFavorite ? 'currentColor' : 'none'}
stroke="currentColor"
viewBox="0 0 24 24"
>
@@ -253,31 +346,81 @@ function LiveContent() {
)}
</div>
- {/* 侧栏:频道列表 */}
- <aside className="bg-surface-raised border border-line rounded-lg flex flex-col lg:sticky lg:top-20 h-[70vh] lg:h-[calc(100vh-6.5rem)] overflow-hidden">
- {playlistsQuery.isLoading && channels.length === 0 ? (
- <div className="flex-1 flex items-center justify-center">
- <div className="h-9 w-9 rounded-full border-4 border-line border-t-accent animate-spin" />
- </div>
- ) : (
- <LiveChannelList
- channels={channels}
- groups={groups}
- currentUrl={currentUrl}
- onSelect={selectChannel}
- />
- )}
- {(failedCount > 0 || sources.length === 0) && (
- <p className="text-[10px] text-faint px-3 py-1.5 border-t border-line shrink-0">
- {sources.length === 0
- ? store.liveEnvSources.length + store.liveSubscriptions.length > 0
- ? '所有直播源均已停用,请在设置中勾选启用'
- : '暂无直播源,请在设置 → 直播源中添加'
- : `${failedCount > 0 ? `${failedCount} 个订阅拉取失败 · ` : ''}共 ${sources.length} 个已启用源`}
- </p>
+ {/* 移动端抽屉遮罩 */}
+ {listOpen && (
+ <div
+ className="fixed inset-0 z-30 bg-black/50 lg:hidden"
+ aria-hidden="true"
+ onClick={() => setListOpen(false)}
+ />
+ )}
+
+ {/* 侧栏:桌面常驻 sticky;移动端底部抽屉 */}
+ <aside
+ className={cn(
+ 'bg-surface-raised border border-line flex-col overflow-hidden',
+ 'fixed inset-x-0 bottom-0 z-40 h-[75vh] rounded-t-2xl shadow-2xl',
+ listOpen ? 'flex' : 'hidden',
+ 'lg:sticky lg:top-20 lg:flex lg:h-[calc(100vh-6.5rem)] lg:rounded-lg lg:shadow-none'
)}
+ >
+ {/* 抽屉把手栏(仅移动端) */}
+ <div className="flex items-center justify-between px-3 pt-3 pb-1 shrink-0 lg:hidden">
+ <span className="text-sm font-semibold text-content">频道列表</span>
+ <button
+ className="rounded-md p-1.5 text-muted hover:text-content hover:bg-hover transition-colors"
+ aria-label="关闭频道列表"
+ onClick={() => setListOpen(false)}
+ >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </button>
+ </div>
+ <div className="flex-1 min-h-0 flex flex-col">
+ {playlistsQuery.isLoading && channels.length === 0 ? (
+ <div className="flex-1 flex items-center justify-center">
+ <div className="h-9 w-9 rounded-full border-4 border-line border-t-accent animate-spin" />
+ </div>
+ ) : (
+ <LiveChannelList
+ channels={channels}
+ groups={groups}
+ currentUrl={currentUrl}
+ onSelect={handleSelect}
+ onFilteredChange={handleFilteredChange}
+ />
+ )}
+ {(failedCount > 0 || sources.length === 0) && (
+ <p className="text-[10px] text-faint px-3 py-1.5 border-t border-line shrink-0">
+ {sources.length === 0
+ ? liveEnvSources.length + liveSubscriptions.length > 0
+ ? '所有直播源均已停用,请在设置中勾选启用'
+ : '暂无直播源,请在设置 → 直播源中添加'
+ : `${failedCount > 0 ? `${failedCount} 个订阅拉取失败 · ` : ''}共 ${sources.length} 个已启用源`}
+ </p>
+ )}
+ </div>
</aside>
</div>
+
+ {/* 移动端呼出频道列表的悬浮按钮 */}
+ {!listOpen && channels.length > 0 && (
+ <button
+ className="fixed bottom-4 right-4 z-30 flex items-center gap-1.5 rounded-full bg-accent px-4 py-2.5 text-sm text-white shadow-lg lg:hidden"
+ onClick={() => setListOpen(true)}
+ >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M4 6h16M4 12h16M4 18h16"
+ />
+ </svg>
+ 频道
+ </button>
+ )}
</main>
</div>
);
diff --git a/src/components/live-channel-list.tsx b/src/components/live-channel-list.tsx
index 0d94e3c..f878d70 100644
--- a/src/components/live-channel-list.tsx
+++ b/src/components/live-channel-list.tsx
@@ -1,18 +1,31 @@
'use client';
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { buildImageUrl, cn } from '@/lib/utils';
import { useAppStore } from '@/lib/store';
+import {
+ matchesAlive,
+ matchesKeyword,
+ normalizeForSearch,
+ sortChannels,
+ type AliveFilter,
+ type LiveSortMode,
+} from '@/lib/live-channel-filter';
import { useLiveProbe, type ProbeResult } from './use-live-probe';
import type { LiveChannel } from '@/lib/types';
/**
- * 直播频道侧栏:全部/收藏/最近三个视图 + 分组横向标签条 + 关键字搜索。
- * 支持批量测活:频道名前显示可达性状态点,可筛选「仅可用」。
- * 大列表渐进渲染(每次 300,点「加载更多」递增),避免数千频道一次性 DOM。
+ * 直播频道侧栏:全部/收藏/最近三个视图 + 分组横向标签条 + 关键字搜索 + 排序。
+ * - 搜索对分隔符归一化(cctv1 命中 CCTV-1),并匹配分组名;输入防抖后过滤;
+ * - 可用性两档筛选(绿点=分片级验证 / 可播=含弱验证);
+ * - 支持批量测活:频道名前显示可达性状态点;
+ * - 大列表渐进渲染 + 无限滚动(IntersectionObserver),「加载更多」兜底;
+ * - 键盘:容器聚焦后 ↑↓ 移动光标、Enter 播放;
+ * - 性能:本组件与 ChannelRow 均精确订阅 store,探测节流写回不会全列表重渲染。
*/
const PAGE_SIZE = 300;
+const SEARCH_DEBOUNCE_MS = 200;
export interface LiveChannelItem extends LiveChannel {
/** 来源订阅的 EPG 地址(用于节目单查询) */
@@ -26,57 +39,146 @@ interface ChannelListProps {
groups: string[];
currentUrl: string;
onSelect: (channel: LiveChannelItem) => void;
+ /** 筛选+排序结果变化时上报(页面级键盘换台沿此列表顺序切换) */
+ onFilteredChange?: (list: LiveChannelItem[]) => void;
}
type View = 'all' | 'fav' | 'recent';
-export function LiveChannelList({ channels, groups, currentUrl, onSelect }: ChannelListProps) {
- const store = useAppStore();
+function useDebouncedValue<T>(value: T, delay: number): T {
+ const [debounced, setDebounced] = useState(value);
+ useEffect(() => {
+ const timer = setTimeout(() => setDebounced(value), delay);
+ return () => clearTimeout(timer);
+ }, [value, delay]);
+ return debounced;
+}
+
+export function LiveChannelList({ channels, groups, currentUrl, onSelect, onFilteredChange }: ChannelListProps) {
+ // 精确订阅:避免任何 store 字段变化(尤其测活节流写回)引发本组件重渲染
+ const liveFavorites = useAppStore((s) => s.liveFavorites);
+ const liveRecent = useAppStore((s) => s.liveRecent);
const imageProxyMode = useAppStore((s) => s.imageProxyMode);
const customImageProxy = useAppStore((s) => s.customImageProxy);
+
const [view, setView] = useState<View>('all');
const [group, setGroup] = useState<string>('');
const [keyword, setKeyword] = useState('');
+ const debouncedKeyword = useDebouncedValue(keyword, SEARCH_DEBOUNCE_MS);
+ const [sortMode, setSortMode] = useState<LiveSortMode>('default');
+ const [aliveFilter, setAliveFilter] = useState<AliveFilter>('off');
const [limit, setLimit] = useState(PAGE_SIZE);
- const [onlyAlive, setOnlyAlive] = useState(false);
+ /** 键盘光标(filtered 的下标),与"正在播放"高亮独立 */
+ const [cursor, setCursor] = useState(-1);
+ const listRef = useRef<HTMLDivElement>(null);
+ const sentinelRef = useRef<HTMLDivElement>(null);
const { results: probeResults, progress: probeProgress, probe, clear: clearProbe, isProbing, hint: probeHint } = useLiveProbe();
- const favSet = useMemo(() => new Set(store.liveFavorites), [store.liveFavorites]);
+ const favSet = useMemo(() => new Set(liveFavorites), [liveFavorites]);
+ const recentOrder = useMemo(() => new Map(liveRecent.map((r, i) => [r.url, i] as const)), [liveRecent]);
+ const normalizedKeyword = useMemo(() => normalizeForSearch(debouncedKeyword.trim()), [debouncedKeyword]);
const filtered = useMemo(() => {
- const kw = keyword.trim().toLowerCase();
let list: LiveChannelItem[];
if (view === 'fav') {
list = channels.filter((c) => favSet.has(c.url));
} else if (view === 'recent') {
// 按最近观看时间倒序
- list = store.liveRecent
+ list = liveRecent
.map((r) => channels.find((c) => c.url === r.url))
.filter((c): c is LiveChannelItem => Boolean(c));
} else {
list = channels;
}
- if (view !== 'recent') {
- if (group) list = list.filter((c) => c.group === group);
+ if (view !== 'recent' && group) {
+ list = list.filter((c) => c.group === group);
}
- if (kw) {
- list = list.filter(
- (c) => c.name.toLowerCase().includes(kw) || (c.tvgId || '').toLowerCase().includes(kw)
- );
+ if (normalizedKeyword) {
+ list = list.filter((c) => matchesKeyword(c, normalizedKeyword));
}
- if (onlyAlive && probeResults.size > 0) {
- list = list.filter((c) => probeResults.get(c.url)?.ok === true);
+ if (aliveFilter !== 'off') {
+ list = list.filter((c) => matchesAlive(probeResults.get(c.url), aliveFilter));
}
- return list;
- }, [channels, favSet, store.liveRecent, view, group, keyword, onlyAlive, probeResults]);
+ return sortChannels(list, sortMode, { recentOrder, probeOf: (url) => probeResults.get(url) });
+ }, [channels, favSet, liveRecent, view, group, normalizedKeyword, aliveFilter, sortMode, recentOrder, probeResults]);
- const aliveCount = useMemo(
- () => (probeResults.size > 0 ? filtered.filter((c) => probeResults.get(c.url)?.ok === true).length : 0),
- [filtered, probeResults]
- );
+ // 上报筛选排序结果给页面(键盘换台用);列表存父组件 ref,不触发父组件重渲染
+ useEffect(() => {
+ onFilteredChange?.(filtered);
+ }, [filtered, onFilteredChange]);
- // 切换视图/分组/搜索时重置渐进渲染
- useEffect(() => setLimit(PAGE_SIZE), [view, group, keyword]);
+ const aliveCounts = useMemo(() => {
+ let ok = 0;
+ let green = 0;
+ for (const c of filtered) {
+ const p = probeResults.get(c.url);
+ if (!p?.ok) continue;
+ ok++;
+ if (p.level === 'segment') green++;
+ }
+ return { ok, green };
+ }, [filtered, probeResults]);
+
+ // 切换筛选/排序/频道时:重置渐进渲染与键盘光标,并把当前播放频道滚入视区
+ useEffect(() => {
+ setLimit(PAGE_SIZE);
+ setCursor(-1);
+ const root = listRef.current;
+ if (!root) return;
+ const activeRow = currentUrl
+ ? root.querySelector<HTMLElement>(`li[data-url="${CSS.escape(currentUrl)}"]`)
+ : null;
+ if (activeRow) activeRow.scrollIntoView({ block: 'nearest' });
+ else root.scrollTo({ top: 0 });
+ }, [view, group, sortMode, debouncedKeyword, aliveFilter, currentUrl]);
+
+ // 无限滚动:接近底部时自动续载
+ useEffect(() => {
+ const sentinel = sentinelRef.current;
+ const root = listRef.current;
+ if (!sentinel || !root || filtered.length <= limit) return;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((e) => e.isIntersecting)) {
+ setLimit((l) => Math.min(l + PAGE_SIZE, filtered.length));
+ }
+ },
+ { root, rootMargin: '240px' }
+ );
+ observer.observe(sentinel);
+ return () => observer.disconnect();
+ }, [filtered.length, limit]);
+
+ const scrollToChannelRow = useCallback((url: string) => {
+ listRef.current
+ ?.querySelector<HTMLElement>(`li[data-url="${CSS.escape(url)}"]`)
+ ?.scrollIntoView({ block: 'nearest' });
+ }, []);
+
+ const onListKeyDown = (e: React.KeyboardEvent) => {
+ if (filtered.length === 0) return;
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault();
+ const delta = e.key === 'ArrowDown' ? 1 : -1;
+ const base = cursor === -1 ? (delta === 1 ? -1 : 0) : cursor;
+ const next = Math.min(Math.max(base + delta, 0), filtered.length - 1);
+ setCursor(next);
+ if (next >= limit) setLimit(next + PAGE_SIZE);
+ const target = filtered[next];
+ if (target) scrollToChannelRow(target.url);
+ return;
+ }
+ if (e.key === 'Enter' && cursor >= 0 && cursor < filtered.length) {
+ // 焦点在行内按钮(收藏/删除)上时,Enter 交给按钮自身
+ if ((e.target as HTMLElement).closest('button')) return;
+ e.preventDefault();
+ onSelect(filtered[cursor]);
+ }
+ };
+
+ const removeRecent = useCallback((url: string) => {
+ useAppStore.getState().removeLiveRecent(url);
+ }, []);
const visible = filtered.slice(0, limit);
@@ -87,7 +189,7 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
{(
[
['all', `全部${channels.length ? ` ${channels.length}` : ''}`],
- ['fav', `收藏${store.liveFavorites.length ? ` ${store.liveFavorites.length}` : ''}`],
+ ['fav', `收藏${liveFavorites.length ? ` ${liveFavorites.length}` : ''}`],
['recent', '最近'],
] as [View, string][]
).map(([v, label]) => (
@@ -104,18 +206,39 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
))}
</div>
- {/* 搜索框 */}
- <div className="px-3 py-2 shrink-0">
+ {/* 搜索 + 排序 */}
+ <div className="px-3 py-2 shrink-0 flex items-center gap-1.5">
<input
className="input w-full !py-1.5 text-xs"
- placeholder="搜索频道名称或 tvg-id..."
+ placeholder="搜索频道 / tvg-id / 分组..."
value={keyword}
maxLength={60}
onChange={(e) => setKeyword(e.target.value)}
+ onKeyDown={(e) => {
+ // 搜索框内按 ↓ 进入列表光标导航
+ if (e.key === 'ArrowDown' && filtered.length > 0) {
+ e.preventDefault();
+ setCursor(0);
+ scrollToChannelRow(filtered[0].url);
+ listRef.current?.focus();
+ }
+ }}
/>
+ <select
+ className="input !py-1.5 !px-1.5 text-xs w-auto shrink-0 cursor-pointer"
+ value={sortMode}
+ aria-label="排序方式"
+ onChange={(e) => setSortMode(e.target.value as LiveSortMode)}
+ >
+ <option value="default">默认</option>
+ <option value="name">名称</option>
+ <option value="group">分组</option>
+ <option value="probe">可用优先</option>
+ <option value="recent">最近看</option>
+ </select>
</div>
- {/* 测活工具条 */}
+ {/* 测活 + 可用性筛选工具条 */}
<div className="flex items-center gap-1.5 px-3 pb-2 shrink-0 flex-wrap">
<button
className="btn-ghost !py-1 !px-2 text-xs"
@@ -138,19 +261,32 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
<button
className={cn(
'shrink-0 px-2 py-0.5 rounded-full text-[10px] whitespace-nowrap transition-colors border',
- onlyAlive
+ aliveFilter === 'green'
+ ? 'bg-accent text-white border-accent'
+ : 'bg-chip text-muted border-line hover:text-content hover:bg-hover'
+ )}
+ onClick={() => setAliveFilter((v) => (v === 'green' ? 'off' : 'green'))}
+ title="只看分片级验证通过的频道"
+ >
+ 绿点 {aliveCounts.green}
+ </button>
+ <button
+ className={cn(
+ 'shrink-0 px-2 py-0.5 rounded-full text-[10px] whitespace-nowrap transition-colors border',
+ aliveFilter === 'ok'
? 'bg-accent text-white border-accent'
: 'bg-chip text-muted border-line hover:text-content hover:bg-hover'
)}
- onClick={() => setOnlyAlive((v) => !v)}
+ onClick={() => setAliveFilter((v) => (v === 'ok' ? 'off' : 'ok'))}
+ title="看所有验证通过(含直链/清单级弱验证)的频道"
>
- 仅可用 {aliveCount}
+ 可播 {aliveCounts.ok}
</button>
<button
className="text-[10px] text-faint hover:text-content transition-colors"
onClick={() => {
clearProbe();
- setOnlyAlive(false);
+ setAliveFilter('off');
}}
>
清除结果
@@ -171,8 +307,14 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
</div>
)}
- {/* 频道列表 */}
- <div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-2 pb-2">
+ {/* 频道列表(容器可聚焦,↑↓/Enter 光标导航) */}
+ <div
+ ref={listRef}
+ data-channel-list
+ tabIndex={0}
+ onKeyDown={onListKeyDown}
+ className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-2 pb-2 focus:outline-none"
+ >
{visible.length === 0 ? (
<p className="text-center text-xs text-faint py-10">
{view === 'fav'
@@ -181,25 +323,28 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
? '暂无观看记录'
: channels.length === 0
? '暂无频道,请先在设置中添加直播源'
- : onlyAlive && probeResults.size > 0
- ? '没有探测到可用频道,可清除结果后重试'
+ : aliveFilter !== 'off' && probeResults.size > 0
+ ? '没有匹配该可用性的频道,可放宽或清除筛选'
: '没有匹配的频道'}
</p>
) : (
<ul className="space-y-1">
- {visible.map((c) => (
+ {visible.map((c, i) => (
<ChannelRow
key={c.url}
channel={c}
active={c.url === currentUrl}
+ cursor={cursor === i}
isFav={favSet.has(c.url)}
probe={probeResults.get(c.url)}
logoUrl={buildImageUrl(c.logo, imageProxyMode, customImageProxy)}
- onSelect={() => onSelect(c)}
+ onSelect={onSelect}
+ onRemoveRecent={view === 'recent' ? removeRecent : undefined}
/>
))}
</ul>
)}
+ <div ref={sentinelRef} className="h-1" />
{filtered.length > limit && (
<button
className="btn-ghost w-full mt-2 !py-1.5 text-xs"
@@ -229,22 +374,26 @@ function GroupChip({ label, active, onClick }: { label: string; active: boolean;
);
}
-function ChannelRow({
+const ChannelRow = memo(function ChannelRow({
channel,
active,
+ cursor,
isFav,
probe,
logoUrl,
onSelect,
+ onRemoveRecent,
}: {
channel: LiveChannelItem;
active: boolean;
+ cursor: boolean;
isFav: boolean;
probe?: ProbeResult;
logoUrl?: string;
- onSelect: () => void;
+ onSelect: (channel: LiveChannelItem) => void;
+ /** 仅最近视图传入:删除该条观看记录 */
+ onRemoveRecent?: (url: string) => void;
}) {
- const store = useAppStore();
const ref = useRef<HTMLLIElement>(null);
// 当前播放项自动滚入视区
@@ -254,7 +403,7 @@ function ChannelRow({
// H.265/HEVC:国内 IPTV 常见,测活通过但 Chromium 内核通常无法软解
const isHevc = Boolean(probe?.codec && /hvc1|hev1|hevc/i.test(probe.codec));
- // 状态点语义:绿=分片级验证通过;琥珀=仅弱验证(直链/清单级)或超时(源可能只是慢);红=不可达
+ // 状态点语义:绿=分片级验证通过;琥珀=弱验证(直链/清单级)或超时(源可能只是慢);红=不可达
const weakLevel = probe?.ok && probe.level !== 'segment';
const amber = Boolean(probe && (weakLevel || (!probe.ok && probe.timedOut)));
const dotClass = amber ? 'bg-amber-400' : probe?.ok ? 'bg-green-500' : 'bg-red-400';
@@ -273,21 +422,16 @@ function ChannelRow({
: undefined;
return (
- <li ref={ref}>
+ <li ref={ref} data-url={channel.url}>
<div
role="button"
- tabIndex={0}
+ tabIndex={-1}
className={cn(
'group flex items-center gap-2.5 px-2 py-2 rounded-md cursor-pointer transition-colors relative',
- active ? 'bg-accent/10' : 'hover:bg-hover'
+ active ? 'bg-accent/10' : 'hover:bg-hover',
+ cursor && 'ring-1 ring-accent/70'
)}
- onClick={onSelect}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- onSelect();
- }
- }}
+ onClick={() => onSelect(channel)}
>
{/* 当前播放高亮竖条 */}
<span
@@ -337,17 +481,39 @@ function ChannelRow({
<div className="text-[10px] text-faint truncate">{channel.group}</div>
)}
</div>
- {/* 收藏星标 */}
+ {/* 最近观看单条删除(仅最近视图;移动端常显) */}
+ {onRemoveRecent && (
+ <button
+ className={cn(
+ 'shrink-0 p-1 rounded transition-colors',
+ 'text-faint/60 opacity-60 lg:opacity-0 lg:group-hover:opacity-100 hover:text-red-400'
+ )}
+ aria-label="删除该观看记录"
+ title="删除该观看记录"
+ onClick={(e) => {
+ e.stopPropagation();
+ onRemoveRecent(channel.url);
+ }}
+ >
+ <svg className="w-3.5 h-3.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>
+ )}
+ {/* 收藏星标(移动端常显,桌面 hover 出现) */}
<button
className={cn(
'shrink-0 p-1 rounded transition-transform active:scale-125',
- isFav ? 'text-amber-400' : 'text-faint/50 opacity-0 group-hover:opacity-100 hover:text-amber-400'
+ isFav
+ ? 'text-amber-400'
+ : 'text-faint/60 opacity-60 lg:opacity-0 lg:group-hover:opacity-100 hover:text-amber-400'
)}
aria-label={isFav ? '取消收藏' : '收藏'}
title={isFav ? '取消收藏' : '收藏'}
onClick={(e) => {
e.stopPropagation();
- store.toggleLiveFavorite(channel.url);
+ // 点击时读取最新状态:行组件不订阅 store,保证探测期间的重渲染隔离
+ useAppStore.getState().toggleLiveFavorite(channel.url);
}}
>
<svg className="w-3.5 h-3.5" fill={isFav ? 'currentColor' : 'none'} stroke="currentColor" viewBox="0 0 24 24">
@@ -362,4 +528,4 @@ function ChannelRow({
</div>
</li>
);
-}
+});
diff --git a/src/components/live-player.tsx b/src/components/live-player.tsx
index b3a60a3..ed052c4 100644
--- a/src/components/live-player.tsx
+++ b/src/components/live-player.tsx
@@ -39,9 +39,12 @@ interface LivePlayerProps {
/** 上游直播流地址(直连优先,失败自动走代理) */
url: string;
title: string;
+ /** 上一台/下一台:传入时注册为播放器控制条按钮(全屏内也可操作) */
+ onPrevChannel?: () => void;
+ onNextChannel?: () => void;
}
-export function LivePlayer({ url, title }: LivePlayerProps) {
+export function LivePlayer({ url, title, onPrevChannel, onNextChannel }: LivePlayerProps) {
const containerRef = useRef<HTMLDivElement>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const artRef = useRef<any>(null);
@@ -244,6 +247,31 @@ export function LivePlayer({ url, title }: LivePlayerProps) {
};
const engine = engineOf(url);
+ // 上一台/下一台:注册到播放器控制条(普通态与全屏均可见),未传不显示
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const controls: any[] = [];
+ const channelBtnSvg = (path: string) =>
+ `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:18px;height:18px"><path d="${path}"/></svg>`;
+ if (onPrevChannel) {
+ controls.push({
+ name: 'prev-channel',
+ position: 'left',
+ index: 0,
+ html: channelBtnSvg('M11 19l-7-7 7-7m8 14l-7-7 7-7'),
+ tooltip: '上一台',
+ click: () => onPrevChannel(),
+ });
+ }
+ if (onNextChannel) {
+ controls.push({
+ name: 'next-channel',
+ position: 'left',
+ index: 1,
+ html: channelBtnSvg('M13 5l7 7-7 7M5 5l7 7-7 7'),
+ tooltip: '下一台',
+ click: () => onNextChannel(),
+ });
+ }
const art = new Artplayer({
container: containerRef.current,
url,
@@ -266,6 +294,7 @@ export function LivePlayer({ url, title }: LivePlayerProps) {
playsInline: true,
airplay: true,
theme: '#2563eb',
+ controls,
lang: navigator.language.toLowerCase().startsWith('zh') ? 'zh-cn' : 'en',
moreVideoAttr: { playsInline: true },
customType: {
@@ -322,7 +351,7 @@ export function LivePlayer({ url, title }: LivePlayerProps) {
destroyed = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [url, retryNonce]);
+ }, [url, retryNonce, onPrevChannel, onNextChannel]);
return (
<div className="relative w-full h-full">
diff --git a/src/components/use-live-probe.ts b/src/components/use-live-probe.ts
index 33af226..9ce7d7c 100644
--- a/src/components/use-live-probe.ts
+++ b/src/components/use-live-probe.ts
@@ -51,20 +51,35 @@ export function useLiveProbe() {
abortRef.current?.abort();
}, []);
- // 仅暴露 6 小时内的结果,过期条目对 UI 不可见
+ // 仅暴露 6 小时内的结果,过期条目对 UI 不可见。
+ // 结果对象按 (url, timestamp) 复用身份:节流写回只更新被探测到的频道,
+ // 未变化的条目保持同一对象引用,下游 memo 行组件才能精确跳过重渲染。
+ const identityRef = useRef(new Map<string, { timestamp: number; result: ProbeResult }>());
const results = useMemo(() => {
const now = Date.now();
const map = new Map<string, ProbeResult>();
+ const identities = identityRef.current;
for (const [url, e] of Object.entries(cache)) {
- if (now - e.timestamp < LIVE_PROBE_TTL_MS) {
- map.set(url, {
- ok: e.ok,
- ms: e.ms,
- level: e.level,
- error: e.error,
- codec: e.codec,
- timedOut: e.timedOut,
- });
+ if (now - e.timestamp >= LIVE_PROBE_TTL_MS) continue;
+ const known = identities.get(url);
+ const result =
+ known && known.timestamp === e.timestamp
+ ? known.result
+ : {
+ ok: e.ok,
+ ms: e.ms,
+ level: e.level,
+ error: e.error,
+ codec: e.codec,
+ timedOut: e.timedOut,
+ };
+ if (!known || known.timestamp !== e.timestamp) identities.set(url, { timestamp: e.timestamp, result });
+ map.set(url, result);
+ }
+ // 清理已过期频道的身份缓存,避免无界增长
+ if (identities.size > map.size) {
+ for (const url of identities.keys()) {
+ if (!map.has(url)) identities.delete(url);
}
}
return map;
diff --git a/src/lib/live-channel-filter.test.ts b/src/lib/live-channel-filter.test.ts
new file mode 100644
index 0000000..0365dc4
--- /dev/null
+++ b/src/lib/live-channel-filter.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from 'vitest';
+import {
+ matchesAlive,
+ matchesKeyword,
+ normalizeForSearch,
+ probeRank,
+ sortChannels,
+ type ProbeLike,
+} from './live-channel-filter';
+
+const channel = (over: Partial<{ name: string; tvgId?: string; group?: string; url: string }>) => ({
+ url: 'https://s.example/1',
+ name: '',
+ ...over,
+});
+
+describe('normalizeForSearch', () => {
+ it('小写化并去除分隔符', () => {
+ expect(normalizeForSearch('CCTV-1 综合')).toBe('cctv1综合');
+ expect(normalizeForSearch('CCTV_5+.HD')).toBe('cctv5hd');
+ });
+});
+
+describe('matchesKeyword', () => {
+ const c = channel({ name: 'CCTV-1 综合', tvgId: 'cctv1', group: '央视' });
+
+ it('空关键字恒匹配', () => {
+ expect(matchesKeyword(c, '')).toBe(true);
+ });
+
+ it('cctv1 命中 CCTV-1 综合(分隔符归一化)', () => {
+ expect(matchesKeyword(c, normalizeForSearch('cctv1'))).toBe(true);
+ });
+
+ it('按 tvg-id 匹配', () => {
+ expect(matchesKeyword(c, normalizeForSearch('CCTV1'))).toBe(true);
+ });
+
+ it('按分组名匹配', () => {
+ expect(matchesKeyword(c, normalizeForSearch('央 视'))).toBe(true);
+ });
+
+ it('不相关关键字不匹配', () => {
+ expect(matchesKeyword(c, normalizeForSearch('湖南卫视'))).toBe(false);
+ });
+});
+
+describe('matchesAlive', () => {
+ const green: ProbeLike = { ok: true, level: 'segment' };
+ const weak: ProbeLike = { ok: true, level: 'head' };
+ const timeout: ProbeLike = { ok: false, timedOut: true };
+ const dead: ProbeLike = { ok: false };
+
+ it('off 恒真(含未测)', () => {
+ expect(matchesAlive(undefined, 'off')).toBe(true);
+ expect(matchesAlive(dead, 'off')).toBe(true);
+ });
+
+ it('ok 档:任何验证级别通过', () => {
+ expect(matchesAlive(green, 'ok')).toBe(true);
+ expect(matchesAlive(weak, 'ok')).toBe(true);
+ expect(matchesAlive(timeout, 'ok')).toBe(false);
+ expect(matchesAlive(dead, 'ok')).toBe(false);
+ expect(matchesAlive(undefined, 'ok')).toBe(false);
+ });
+
+ it('green 档:仅分片级验证', () => {
+ expect(matchesAlive(green, 'green')).toBe(true);
+ expect(matchesAlive(weak, 'green')).toBe(false);
+ });
+});
+
+describe('probeRank', () => {
+ it('绿点 < 弱验证 < 超时 < 失败 < 未测', () => {
+ expect(probeRank({ ok: true, level: 'segment' })).toBeLessThan(probeRank({ ok: true, level: 'head' }));
+ expect(probeRank({ ok: true, level: 'head' })).toBeLessThan(probeRank({ ok: false, timedOut: true }));
+ expect(probeRank({ ok: false, timedOut: true })).toBeLessThan(probeRank({ ok: false }));
+ expect(probeRank({ ok: false })).toBeLessThan(probeRank(undefined));
+ });
+});
+
+describe('sortChannels', () => {
+ // 用 ASCII 台名/分组断言排序,避免依赖运行环境的中文 collation 细节
+ const list = [
+ channel({ name: 'TV5', group: 'B-Sat', url: 'u1' }),
+ channel({ name: 'CCTV-1', group: 'A-Nat', url: 'u2' }),
+ channel({ name: 'CCTV-5', group: 'A-Nat', url: 'u3' }),
+ ];
+
+ it('default 保持原序', () => {
+ expect(sortChannels(list, 'default').map((c) => c.url)).toEqual(['u1', 'u2', 'u3']);
+ });
+
+ it('name 按名称排序', () => {
+ expect(sortChannels(list, 'name').map((c) => c.url)).toEqual(['u2', 'u3', 'u1']);
+ });
+
+ it('group 先按分组再按名称', () => {
+ expect(sortChannels(list, 'group').map((c) => c.url)).toEqual(['u2', 'u3', 'u1']);
+ });
+
+ it('group 同分组内保持稳定序(sort 稳定性)', () => {
+ const order = sortChannels(list, 'group').filter((c) => c.group === 'A-Nat');
+ expect(order.map((c) => c.url)).toEqual(['u2', 'u3']);
+ });
+
+ it('probe 可用优先、同级按耗时升序', () => {
+ const probeOf = (url: string): ProbeLike | undefined =>
+ url === 'u3' ? { ok: true, level: 'head' } : url === 'u1' ? { ok: true, level: 'segment', ms: 200 } : { ok: false };
+ // u1 绿点最快 → u3 弱验证 → u2 失败
+ expect(sortChannels(list, 'probe', { probeOf }).map((c) => c.url)).toEqual(['u1', 'u3', 'u2']);
+ });
+
+ it('probe 未测频道排在已测之后', () => {
+ const probeOf = (url: string): ProbeLike | undefined => (url === 'u1' ? { ok: false } : undefined);
+ expect(sortChannels(list, 'probe', { probeOf }).map((c) => c.url)).toEqual(['u1', 'u2', 'u3']);
+ });
+
+ it('recent 按最近观看序排列,未观看的靠后', () => {
+ const recentOrder = new Map([
+ ['u3', 0],
+ ['u1', 1],
+ ]);
+ expect(sortChannels(list, 'recent', { recentOrder }).map((c) => c.url)).toEqual(['u3', 'u1', 'u2']);
+ });
+});
diff --git a/src/lib/live-channel-filter.ts b/src/lib/live-channel-filter.ts
new file mode 100644
index 0000000..ae89547
--- /dev/null
+++ b/src/lib/live-channel-filter.ts
@@ -0,0 +1,107 @@
+/**
+ * 直播频道列表的纯函数过滤/排序工具。
+ * 从 live-channel-list 组件中抽出为可测试的纯逻辑:
+ * - 搜索归一化:忽略分隔符差异(cctv1 可命中 CCTV-1 综合);
+ * - 可用性两档筛选:仅绿点(分片级验证)/ 含琥珀(弱验证或超时);
+ * - 排序:默认 / 名称 / 分组 / 可用性优先 / 最近观看。
+ */
+
+/** 与 store 的 LiveProbeEntry 结构兼容的测活结果子集(避免 lib 依赖 client store 类型) */
+export interface ProbeLike {
+ ok: boolean;
+ ms?: number;
+ level?: 'segment' | 'manifest' | 'head';
+ timedOut?: boolean;
+}
+
+export type LiveSortMode = 'default' | 'name' | 'group' | 'probe' | 'recent';
+export type AliveFilter = 'off' | 'ok' | 'green';
+
+/** 常见台名分隔符(空格、连字符、下划线、点、竖线、括号等),搜索时忽略 */
+const SEPARATOR_RE = /[\s\-_./·|+()()[\]【】]/g;
+
+export function normalizeForSearch(input: string): string {
+ return input.toLowerCase().replace(SEPARATOR_RE, '');
+}
+
+export interface KeywordMatchable {
+ name: string;
+ tvgId?: string;
+ group?: string;
+}
+
+/** 关键字匹配台名 / tvg-id / 分组名(三者都做分隔符归一化);空关键字恒匹配 */
+export function matchesKeyword(channel: KeywordMatchable, normalizedKeyword: string): boolean {
+ if (!normalizedKeyword) return true;
+ if (normalizeForSearch(channel.name).includes(normalizedKeyword)) return true;
+ if (channel.tvgId && normalizeForSearch(channel.tvgId).includes(normalizedKeyword)) return true;
+ if (channel.group && normalizeForSearch(channel.group).includes(normalizedKeyword)) return true;
+ return false;
+}
+
+/**
+ * 可用性筛选:
+ * - 'ok':任何验证级别通过(绿点或琥珀中的弱验证)
+ * - 'green':仅分片级验证通过(真实可播置信度最高)
+ */
+export function matchesAlive(probe: ProbeLike | undefined, mode: AliveFilter): boolean {
+ if (mode === 'off') return true;
+ if (!probe?.ok) return false;
+ return mode === 'ok' || probe.level === 'segment';
+}
+
+/** 探测状态排序权重:绿点 → 弱验证 → 超时 → 失败 → 未测 */
+export function probeRank(probe: ProbeLike | undefined): number {
+ if (!probe) return 4;
+ if (probe.ok) return probe.level === 'segment' ? 0 : 1;
+ return probe.timedOut ? 2 : 3;
+}
+
+export interface SortContext {
+ /** url → 最近观看序(liveRecent 下标,越小越近) */
+ recentOrder?: Map<string, number>;
+ probeOf?: (url: string) => ProbeLike | undefined;
+}
+
+export function sortChannels<T extends KeywordMatchable & { url: string }>(
+ list: T[],
+ mode: LiveSortMode,
+ ctx: SortContext = {}
+): T[] {
+ const out = [...list];
+ switch (mode) {
+ case 'name':
+ out.sort((a, b) => a.name.localeCompare(b.name, 'zh'));
+ break;
+ case 'group':
+ out.sort(
+ (a, b) =>
+ (a.group ?? '').localeCompare(b.group ?? '', 'zh') ||
+ a.name.localeCompare(b.name, 'zh')
+ );
+ break;
+ case 'probe': {
+ const probeOf = ctx.probeOf;
+ out.sort((a, b) => {
+ const pa = probeOf?.(a.url);
+ const pb = probeOf?.(b.url);
+ const rank = probeRank(pa) - probeRank(pb);
+ if (rank !== 0) return rank;
+ return (pa?.ms ?? Number.POSITIVE_INFINITY) - (pb?.ms ?? Number.POSITIVE_INFINITY);
+ });
+ break;
+ }
+ case 'recent': {
+ const recentOrder = ctx.recentOrder;
+ out.sort(
+ (a, b) =>
+ (recentOrder?.get(a.url) ?? Number.POSITIVE_INFINITY) -
+ (recentOrder?.get(b.url) ?? Number.POSITIVE_INFINITY)
+ );
+ break;
+ }
+ default:
+ break;
+ }
+ return out;
+}
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 628ec2f..2bfb1cd 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -130,6 +130,10 @@ interface AppState extends AppSettings {
toggleLiveSelected: (url: string) => void;
toggleLiveFavorite: (channelUrl: string) => void;
addLiveRecent: (entry: Omit<LiveRecentEntry, 'timestamp'>) => void;
+ /** 删除单条最近观看(按流 URL) */
+ removeLiveRecent: (channelUrl: string) => void;
+ /** 清空最近观看 */
+ clearLiveRecent: () => void;
/** 合并写入测活结果,并顺带清理过期条目 */
setLiveProbeResults: (entries: Record<string, LiveProbeEntry>) => void;
clearLiveProbeResults: () => void;
@@ -384,6 +388,12 @@ export const useAppStore = create<AppState>()(
set({ liveRecent: [{ ...entry, timestamp: Date.now() }, ...rest].slice(0, 20) });
},
+ removeLiveRecent: (channelUrl) => {
+ set({ liveRecent: get().liveRecent.filter((r) => r.url !== channelUrl) });
+ },
+
+ clearLiveRecent: () => set({ liveRecent: [] }),
+
setLiveProbeResults: (entries) => {
const now = Date.now();
// 合并新结果并顺带清理过期条目,避免 localStorage 无限增长