Skip to content

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

feat(live): 频道侧栏筛选/排序/可用性全面优化与移动端抽屉

bestZweic13c20b433e0
diff --git a/src/app/live/page.tsx b/src/app/live/page.tsx
index ad078d3..e100e59 100644
--- a/src/app/live/page.tsx
+++ b/src/app/live/page.tsx
@@ -49,17 +49,23 @@ async function copyText(text: string): Promise<boolean> {
function LiveContent() {
const searchParams = useSearchParams();
const router = useRouter();
- const store = useAppStore();
+ // 精确订阅:避免测活结果等无关字段写回时整页重渲染(进而打断列表行的 memo)
+ 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);
// 仅聚合已启用的直播源(设置 → 直播源中的勾选状态)
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 +122,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,
@@ -125,8 +131,9 @@ function LiveContent() {
epg: c.epg,
sourceUrl: c.sourceUrl,
});
+ setListOpen(false);
},
- [router, store]
+ [router]
);
if (!verified) {
@@ -157,7 +164,7 @@ function LiveContent() {
<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
@@ -193,17 +200,17 @@ function LiveContent() {
<button
className={cn(
'rounded-md p-2 transition-colors',
- store.liveFavorites.includes(currentChannel.url)
+ liveFavorites.includes(currentChannel.url)
? '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={liveFavorites.includes(currentChannel.url) ? 'currentColor' : 'none'}
stroke="currentColor"
viewBox="0 0 24 24"
>
@@ -253,8 +260,39 @@ 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">
+ {/* 移动端抽屉遮罩 */}
+ {listOpen && (
+ <div
+ className="fixed inset-0 z-30 bg-black/50 lg:hidden"
+ onClick={() => setListOpen(false)}
+ aria-hidden
+ />
+ )}
+
+ {/* 侧栏:频道列表(移动端为底部抽屉,桌面端为固定侧栏) */}
+ <aside
+ className={cn(
+ 'bg-surface-raised border border-line flex flex-col overflow-hidden',
+ // 移动端:底部抽屉
+ 'fixed inset-x-0 bottom-0 z-40 h-[75vh] rounded-t-2xl shadow-2xl',
+ listOpen ? 'flex' : 'hidden',
+ // 桌面端:贴右侧的常驻侧栏,恢复静态布局
+ 'lg:static lg:flex lg:sticky lg:top-20 lg:h-[calc(100vh-6.5rem)] lg:rounded-lg lg:shadow-none'
+ )}
+ >
+ {/* 移动端抽屉头:标题 + 关闭 */}
+ <div className="flex items-center justify-between px-3 py-2 border-b border-line lg:hidden shrink-0">
+ <span className="text-xs font-medium text-content">频道列表</span>
+ <button
+ className="p-1 rounded text-muted hover:text-content hover:bg-hover"
+ 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>
{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" />
@@ -270,7 +308,7 @@ function LiveContent() {
{(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
+ ? liveEnvSources.length + liveSubscriptions.length > 0
? '所有直播源均已停用,请在设置中勾选启用'
: '暂无直播源,请在设置 → 直播源中添加'
: `${failedCount > 0 ? `${failedCount} 个订阅拉取失败 · ` : ''}共 ${sources.length} 个已启用源`}
@@ -279,6 +317,19 @@ function LiveContent() {
</aside>
</div>
</main>
+
+ {/* 移动端:打开频道列表抽屉 */}
+ {!listOpen && (
+ <button
+ className="fixed bottom-4 right-4 z-30 lg:hidden flex items-center gap-1.5 rounded-full bg-accent px-4 py-2.5 text-xs font-medium text-white shadow-lg active:scale-95 transition-transform"
+ 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>
+ )}
</div>
);
}
diff --git a/src/components/live-channel-list.tsx b/src/components/live-channel-list.tsx
index 0d94e3c..ea732d4 100644
--- a/src/components/live-channel-list.tsx
+++ b/src/components/live-channel-list.tsx
@@ -1,15 +1,29 @@
'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 {
+ countAlive,
+ countGroups,
+ matchesAlive,
+ matchesKeyword,
+ sortChannels,
+ type AliveFilter,
+ type LiveSortMode,
+ type ProbeView,
+} from '@/lib/live-channel-filter';
import { useLiveProbe, type ProbeResult } from './use-live-probe';
import type { LiveChannel } from '@/lib/types';
/**
- * 直播频道侧栏:全部/收藏/最近三个视图 + 分组横向标签条 + 关键字搜索。
- * 支持批量测活:频道名前显示可达性状态点,可筛选「仅可用」。
- * 大列表渐进渲染(每次 300,点「加载更多」递增),避免数千频道一次性 DOM。
+ * 直播频道侧栏:全部/收藏/最近三个视图 + 分组标签条 + 关键字搜索 + 排序 + 可用性筛选。
+ *
+ * 筛选语义(四层可叠加,界面始终显示"显示 N / 共 M"并可一键重置):
+ * 视图(全部/收藏/最近) → 分组 → 关键字(频道名/tvg-id/分组名,忽略空格分隔符) → 可用性
+ * - 分组标签条在「全部」「收藏」视图都显示(避免筛选状态不可见);
+ * - 可用性两档:仅绿点(分片级验证通过)/ 含琥珀(弱验证、超时);
+ * - 列表渐进渲染 + 滚动到底自动续载;支持 ↑↓ 换台、Enter 播放。
*/
const PAGE_SIZE = 300;
@@ -30,56 +44,143 @@ interface ChannelListProps {
type View = 'all' | 'fav' | 'recent';
+const SORT_LABELS: Record<LiveSortMode, string> = {
+ default: '默认',
+ name: '名称',
+ group: '分组',
+ probe: '测活',
+ recent: '最近观看',
+};
+
export function LiveChannelList({ channels, groups, currentUrl, onSelect }: ChannelListProps) {
- const store = useAppStore();
+ 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 [group, setGroup] = useState('');
const [keyword, setKeyword] = useState('');
+ const [sort, setSort] = useState<LiveSortMode>('default');
+ const [alive, setAlive] = useState<AliveFilter>('off');
const [limit, setLimit] = useState(PAGE_SIZE);
- const [onlyAlive, setOnlyAlive] = useState(false);
+ // 键盘导航光标(-1 = 未启用),与"正在播放"的高亮互相独立
+ 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 probeOf = useCallback(
+ (url: string): ProbeView | undefined => probeResults.get(url),
+ [probeResults]
+ );
- 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
+ // 视图 → 基础列表(分组/关键字/可用性在之后叠加)
+ const baseList = useMemo(() => {
+ if (view === 'fav') return channels.filter((c) => favSet.has(c.url));
+ if (view === 'recent') {
+ return 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 (kw) {
- list = list.filter(
- (c) => c.name.toLowerCase().includes(kw) || (c.tvgId || '').toLowerCase().includes(kw)
- );
- }
- if (onlyAlive && probeResults.size > 0) {
- list = list.filter((c) => probeResults.get(c.url)?.ok === true);
- }
- return list;
- }, [channels, favSet, store.liveRecent, view, group, keyword, onlyAlive, probeResults]);
+ return channels;
+ }, [channels, favSet, liveRecent, view]);
- const aliveCount = useMemo(
- () => (probeResults.size > 0 ? filtered.filter((c) => probeResults.get(c.url)?.ok === true).length : 0),
- [filtered, probeResults]
+ // 分组计数基于"视图 + 关键字"过滤后的列表,保证数字与选择该项后的结果一致
+ const groupCounts = useMemo(
+ () => countGroups(keyword.trim() ? baseList.filter((c) => matchesKeyword(c, keyword)) : baseList),
+ [baseList, keyword]
);
- // 切换视图/分组/搜索时重置渐进渲染
- useEffect(() => setLimit(PAGE_SIZE), [view, group, keyword]);
+ const filtered = useMemo(() => {
+ let list = baseList;
+ if (view !== 'recent' && group) list = list.filter((c) => c.group === group);
+ if (keyword.trim()) list = list.filter((c) => matchesKeyword(c, keyword));
+ if (alive !== 'off') list = list.filter((c) => matchesAlive(probeOf(c.url), alive));
+ return sortChannels(list, sort, probeOf, recentOrder);
+ }, [baseList, view, group, keyword, alive, sort, probeOf, recentOrder]);
+
+ const aliveCounts = useMemo(() => countAlive(baseList, probeOf), [baseList, probeOf]);
+
+ // 切换筛选/排序时重置渐进渲染并回到顶部
+ useEffect(() => {
+ setLimit(PAGE_SIZE);
+ setCursor(-1);
+ listRef.current?.scrollTo({ top: 0 });
+ }, [view, group, keyword, alive, sort]);
+
+ // 测活结果被清空时,可用性筛选同步复位,避免停留在"永远为空"的状态
+ useEffect(() => {
+ if (alive !== 'off' && probeResults.size === 0) setAlive('off');
+ }, [alive, probeResults.size]);
+
+ // 滚动到底自动续载(保留"加载更多"按钮作为兜底)
+ useEffect(() => {
+ const root = listRef.current;
+ const target = sentinelRef.current;
+ if (!root || !target || filtered.length <= limit) return;
+ const io = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((e) => e.isIntersecting)) {
+ setLimit((l) => Math.min(l + PAGE_SIZE, filtered.length));
+ }
+ },
+ { root, rootMargin: '240px' }
+ );
+ io.observe(target);
+ return () => io.disconnect();
+ }, [filtered.length, limit]);
const visible = filtered.slice(0, limit);
+ const scrollToUrl = (url: string) => {
+ const root = listRef.current;
+ if (!root) return;
+ const escaped = typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(url) : url;
+ root.querySelector(`[data-url="${escaped}"]`)?.scrollIntoView({ block: 'nearest' });
+ };
+
+ // ↑↓ 换台、Enter 播放(电视/遥控场景)
+ const onListKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Enter') return;
+ if (filtered.length === 0) return;
+ if (e.key === 'Enter') {
+ if (cursor >= 0 && filtered[cursor]) {
+ e.preventDefault();
+ onSelect(filtered[cursor]);
+ }
+ return;
+ }
+ e.preventDefault();
+ const delta = e.key === 'ArrowDown' ? 1 : -1;
+ const next = cursor < 0 ? 0 : Math.min(filtered.length - 1, Math.max(0, cursor + delta));
+ setCursor(next);
+ if (next >= limit) setLimit(Math.min(next + 1, filtered.length));
+ scrollToUrl(filtered[next].url);
+ };
+
+ const filterActive = group !== '' || keyword.trim() !== '' || alive !== 'off';
+ const resetFilters = () => {
+ setGroup('');
+ setKeyword('');
+ setAlive('off');
+ setSort('default');
+ };
+
+ const emptyText = (() => {
+ if (view === 'fav') return '暂无收藏频道,点击频道右侧星标即可收藏';
+ if (view === 'recent') return '暂无观看记录';
+ if (channels.length === 0) return '暂无频道,请先在设置中添加直播源';
+ if (alive !== 'off' && aliveCounts.ok === 0) return '没有探测到可用频道,可「清除结果」后重试';
+ if (filterActive) return '没有匹配的频道,可重置筛选条件';
+ return '没有匹配的频道';
+ })();
+
return (
<div className="flex flex-col h-full min-h-0">
{/* 视图 tab */}
@@ -87,7 +188,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]) => (
@@ -102,20 +203,39 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
{label}
</button>
))}
+ <span className="ml-auto text-[10px] text-faint tabular-nums whitespace-nowrap">
+ 显示 {filtered.length}/{baseList.length}
+ </span>
</div>
- {/* 搜索框 */}
- <div className="px-3 py-2 shrink-0">
+ {/* 搜索框(归一化匹配频道名 / tvg-id / 分组名) */}
+ <div className="px-3 py-2 shrink-0 relative">
<input
- className="input w-full !py-1.5 text-xs"
- placeholder="搜索频道名称或 tvg-id..."
+ className="input w-full !py-1.5 text-xs !pr-7"
+ placeholder="搜索频道 / tvg-id / 分组..."
value={keyword}
maxLength={60}
onChange={(e) => setKeyword(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ listRef.current?.focus();
+ }
+ }}
/>
+ {keyword && (
+ <button
+ className="absolute right-5 top-1/2 -translate-y-1/2 text-faint hover:text-content text-xs"
+ aria-label="清空搜索"
+ title="清空搜索"
+ onClick={() => setKeyword('')}
+ >
+ ✕
+ </button>
+ )}
</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"
@@ -125,81 +245,121 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
>
⚡ 测活
</button>
+ <select
+ className="rounded border border-line bg-chip px-1 py-0.5 text-[10px] text-muted hover:text-content"
+ value={sort}
+ onChange={(e) => setSort(e.target.value as LiveSortMode)}
+ title="排序方式(测活=可用优先且分片耗时升序;最近观看=按观看顺序)"
+ >
+ {(Object.keys(SORT_LABELS) as LiveSortMode[]).map((m) => (
+ <option key={m} value={m}>
+ 排序:{SORT_LABELS[m]}
+ </option>
+ ))}
+ </select>
{isProbing && probeProgress && (
<span className="text-[10px] text-faint">
探测中 {probeProgress.done}/{probeProgress.total}
</span>
)}
- {probeHint && !isProbing && (
- <span className="text-[10px] text-faint">{probeHint}</span>
- )}
+ {probeHint && !isProbing && <span className="text-[10px] text-faint">{probeHint}</span>}
{probeResults.size > 0 && !isProbing && (
<>
<button
className={cn(
'shrink-0 px-2 py-0.5 rounded-full text-[10px] whitespace-nowrap transition-colors border',
- onlyAlive
+ alive === 'green'
+ ? 'bg-green-500/15 text-green-600 border-green-500/40'
+ : 'bg-chip text-muted border-line hover:text-content hover:bg-hover'
+ )}
+ onClick={() => setAlive(alive === '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',
+ alive === 'ok'
? 'bg-accent text-white border-accent'
: 'bg-chip text-muted border-line hover:text-content hover:bg-hover'
)}
- onClick={() => setOnlyAlive((v) => !v)}
+ onClick={() => setAlive(alive === 'ok' ? 'off' : 'ok')}
+ title="绿点 + 琥珀(弱验证 / 超时)"
>
- 仅可用 {aliveCount}
+ 可用(含琥珀){aliveCounts.ok}
</button>
<button
className="text-[10px] text-faint hover:text-content transition-colors"
onClick={() => {
clearProbe();
- setOnlyAlive(false);
+ setAlive('off');
}}
>
清除结果
</button>
</>
)}
+ {(filterActive || sort !== 'default') && (
+ <button
+ className="text-[10px] text-faint hover:text-content transition-colors underline decoration-dotted"
+ onClick={resetFilters}
+ >
+ 重置筛选
+ </button>
+ )}
</div>
- {/* 分组标签条(横向可滑动) */}
- {view === 'all' && groups.length > 0 && (
+ {/* 分组标签条:全部/收藏视图都显示(换行平铺 + 数量,避免横滑找不到) */}
+ {view !== 'recent' && groups.length > 0 && (
<div className="px-3 pb-2 shrink-0">
- <div className="flex gap-1.5 overflow-x-auto scrollbar-thin pb-1">
- <GroupChip active={!group} label="全部分组" onClick={() => setGroup('')} />
+ <div className="flex flex-wrap gap-1.5 max-h-24 overflow-y-auto scrollbar-thin">
+ <GroupChip
+ active={!group}
+ label={`全部分组 ${baseList.length}`}
+ onClick={() => setGroup('')}
+ />
{groups.map((g) => (
- <GroupChip key={g} active={group === g} label={g} onClick={() => setGroup(g === group ? '' : g)} />
+ <GroupChip
+ key={g}
+ active={group === g}
+ label={`${g} ${groupCounts.get(g) ?? 0}`}
+ onClick={() => setGroup(g === group ? '' : g)}
+ />
))}
</div>
</div>
)}
- {/* 频道列表 */}
- <div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-2 pb-2">
+ {/* 频道列表(可聚焦:↑↓ 换台、Enter 播放) */}
+ <div
+ ref={listRef}
+ tabIndex={0}
+ onKeyDown={onListKeyDown}
+ className="flex-1 min-h-0 overflow-y-auto scrollbar-thin px-2 pb-2 outline-none"
+ title="↑↓ 选择频道,Enter 播放"
+ >
{visible.length === 0 ? (
- <p className="text-center text-xs text-faint py-10">
- {view === 'fav'
- ? '暂无收藏频道,点击频道右侧星标即可收藏'
- : view === 'recent'
- ? '暂无观看记录'
- : channels.length === 0
- ? '暂无频道,请先在设置中添加直播源'
- : onlyAlive && probeResults.size > 0
- ? '没有探测到可用频道,可清除结果后重试'
- : '没有匹配的频道'}
- </p>
+ <p className="text-center text-xs text-faint py-10">{emptyText}</p>
) : (
<ul className="space-y-1">
- {visible.map((c) => (
+ {visible.map((c, i) => (
<ChannelRow
key={c.url}
channel={c}
active={c.url === currentUrl}
+ cursor={i === cursor}
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"
@@ -213,6 +373,11 @@ export function LiveChannelList({ channels, groups, currentUrl, onSelect }: Chan
);
}
+/** 从最近观看中移除单条(不订阅 store,点击时读取状态,避免整列表重渲染) */
+function removeRecent(url: string) {
+ useAppStore.getState().removeLiveRecent(url);
+}
+
function GroupChip({ label, active, onClick }: { label: string; active: boolean; onClick: () => void }) {
return (
<button
@@ -229,22 +394,30 @@ function GroupChip({ label, active, onClick }: { label: string; active: boolean;
);
}
-function ChannelRow({
+interface ChannelRowProps {
+ channel: LiveChannelItem;
+ active: boolean;
+ /** 键盘光标所在行(与"正在播放"相互独立) */
+ cursor: boolean;
+ isFav: boolean;
+ probe?: ProbeResult;
+ logoUrl?: string;
+ onSelect: (channel: LiveChannelItem) => void;
+ /** 传入时显示"从最近观看移除"按钮 */
+ onRemoveRecent?: (url: string) => void;
+}
+
+/** 行组件 memo 化:测活流式写回时只重渲染状态真正变化的行 */
+const ChannelRow = memo(function ChannelRow({
channel,
active,
+ cursor,
isFav,
probe,
logoUrl,
onSelect,
-}: {
- channel: LiveChannelItem;
- active: boolean;
- isFav: boolean;
- probe?: ProbeResult;
- logoUrl?: string;
- onSelect: () => void;
-}) {
- const store = useAppStore();
+ onRemoveRecent,
+}: ChannelRowProps) {
const ref = useRef<HTMLLIElement>(null);
// 当前播放项自动滚入视区
@@ -273,21 +446,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 && !active && 'ring-1 ring-accent/40 bg-hover'
)}
- onClick={onSelect}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- onSelect();
- }
- }}
+ onClick={() => onSelect(channel)}
>
{/* 当前播放高亮竖条 */}
<span
@@ -316,10 +484,7 @@ function ChannelRow({
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5 min-w-0">
{probe && (
- <span
- className={cn('w-1.5 h-1.5 rounded-full shrink-0', dotClass)}
- title={probeTitle}
- />
+ <span className={cn('w-1.5 h-1.5 rounded-full shrink-0', dotClass)} title={probeTitle} />
)}
<span className={cn('text-xs truncate', active ? 'text-accent font-medium' : 'text-content')}>
{channel.name}
@@ -333,11 +498,25 @@ function ChannelRow({
</span>
)}
</div>
- {channel.group && (
- <div className="text-[10px] text-faint truncate">{channel.group}</div>
- )}
+ {channel.group && <div className="text-[10px] text-faint truncate">{channel.group}</div>}
</div>
- {/* 收藏星标 */}
+ {/* 最近观看:移除该条记录 */}
+ {onRemoveRecent && (
+ <button
+ className="shrink-0 p-1 rounded text-faint/60 opacity-0 group-hover:opacity-100 hover:text-red-400 transition-colors"
+ aria-label="从最近观看移除"
+ title="从最近观看移除"
+ onClick={(e) => {
+ e.stopPropagation();
+ onRemoveRecent(channel.url);
+ }}
+ >
+ <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </button>
+ )}
+ {/* 收藏星标(不订阅 store:点击时直接触发动作) */}
<button
className={cn(
'shrink-0 p-1 rounded transition-transform active:scale-125',
@@ -347,7 +526,7 @@ function ChannelRow({
title={isFav ? '取消收藏' : '收藏'}
onClick={(e) => {
e.stopPropagation();
- store.toggleLiveFavorite(channel.url);
+ 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 +541,4 @@ function ChannelRow({
</div>
</li>
);
-}
+});
diff --git a/src/lib/live-channel-filter.test.ts b/src/lib/live-channel-filter.test.ts
new file mode 100644
index 0000000..dd24068
--- /dev/null
+++ b/src/lib/live-channel-filter.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from 'vitest';
+import {
+ countAlive,
+ countGroups,
+ matchesAlive,
+ matchesKeyword,
+ normalizeForSearch,
+ sortChannels,
+ type ProbeView,
+} from './live-channel-filter';
+
+const ch = (name: string, url: string, group?: string, tvgId?: string) => ({ name, url, group, tvgId });
+
+describe('normalizeForSearch / matchesKeyword', () => {
+ it('忽略空白与分隔符,cctv1 可命中 CCTV-1', () => {
+ expect(normalizeForSearch('CCTV-1 综合')).toBe('cctv1综合');
+ expect(matchesKeyword(ch('CCTV-1 综合', 'u1'), 'cctv1')).toBe(true);
+ expect(matchesKeyword(ch('CCTV-1 综合', 'u1'), 'cctv-1')).toBe(true);
+ });
+
+ it('匹配 tvg-id 与分组名', () => {
+ const c = ch('浙江影视', 'u2', '浙江频道', 'zjys.cn');
+ expect(matchesKeyword(c, 'zjys')).toBe(true);
+ expect(matchesKeyword(c, '浙江频道')).toBe(true);
+ expect(matchesKeyword(c, '不存在')).toBe(false);
+ });
+
+ it('空关键字命中所有', () => {
+ expect(matchesKeyword(ch('任意', 'u3'), ' ')).toBe(true);
+ });
+});
+
+describe('matchesAlive', () => {
+ const green: ProbeView = { ok: true, level: 'segment', ms: 100 };
+ const weak: ProbeView = { ok: true, level: 'head' };
+ const manifest: ProbeView = { ok: true, level: 'manifest' };
+ const timeout: ProbeView = { ok: false, timedOut: true, error: '探测超时(10000ms)' };
+ const dead: ProbeView = { ok: false, error: '入口响应 404' };
+
+ it('off 全部通过(含未探测)', () => {
+ expect(matchesAlive(undefined, 'off')).toBe(true);
+ expect(matchesAlive(dead, 'off')).toBe(true);
+ });
+
+ it('green 仅分片级通过', () => {
+ expect(matchesAlive(green, 'green')).toBe(true);
+ expect(matchesAlive(weak, 'green')).toBe(false);
+ expect(matchesAlive(manifest, 'green')).toBe(false);
+ expect(matchesAlive(timeout, 'green')).toBe(false);
+ expect(matchesAlive(undefined, 'green')).toBe(false);
+ });
+
+ it('ok 含弱验证与超时,但不含不可达', () => {
+ expect(matchesAlive(green, 'ok')).toBe(true);
+ expect(matchesAlive(weak, 'ok')).toBe(true);
+ expect(matchesAlive(manifest, 'ok')).toBe(true);
+ expect(matchesAlive(timeout, 'ok')).toBe(false);
+ expect(matchesAlive(dead, 'ok')).toBe(false);
+ });
+});
+
+describe('countGroups / countAlive', () => {
+ const list = [ch('a', 'u1', '央视'), ch('b', 'u2', '央视'), ch('c', 'u3', '卫视'), ch('d', 'u4')];
+
+ it('统计分组数量并忽略无分组频道', () => {
+ const counts = countGroups(list);
+ expect(counts.get('央视')).toBe(2);
+ expect(counts.get('卫视')).toBe(1);
+ expect(counts.size).toBe(2);
+ });
+
+ it('统计可用数:green 仅分片级,ok 含琥珀', () => {
+ const probes = new Map<string, ProbeView>([
+ ['u1', { ok: true, level: 'segment' }],
+ ['u2', { ok: true, level: 'head' }],
+ ['u3', { ok: false, timedOut: true }],
+ ]);
+ const { green, ok } = countAlive(list, (url) => probes.get(url));
+ expect(green).toBe(1);
+ expect(ok).toBe(2);
+ });
+});
+
+describe('sortChannels', () => {
+ const list = [ch('B频道', 'u1', '乙'), ch('A频道', 'u2', '甲'), ch('C频道', 'u3', '乙')];
+ const noProbe = () => undefined;
+ const emptyRecent = new Map<string, number>();
+
+ it('default 保持原顺序(源顺序 / 最近观看顺序)', () => {
+ expect(sortChannels(list, 'default', noProbe, emptyRecent).map((c) => c.url)).toEqual([
+ 'u1',
+ 'u2',
+ 'u3',
+ ]);
+ });
+
+ it('name 按名称排序', () => {
+ expect(sortChannels(list, 'name', noProbe, emptyRecent).map((c) => c.name)).toEqual([
+ 'A频道',
+ 'B频道',
+ 'C频道',
+ ]);
+ });
+
+ it('group 先按分组再按名称', () => {
+ expect(sortChannels(list, 'group', noProbe, emptyRecent).map((c) => c.name)).toEqual([
+ 'A频道',
+ 'B频道',
+ 'C频道',
+ ]);
+ });
+
+ it('probe 可用优先 + 分片耗时升序,未测排最后', () => {
+ const probes = new Map<string, ProbeView>([
+ ['u1', { ok: true, level: 'segment', ms: 800 }],
+ ['u2', { ok: true, level: 'head' }],
+ ['u3', { ok: true, level: 'segment', ms: 200 }],
+ ]);
+ expect(sortChannels(list, 'probe', (u) => probes.get(u), emptyRecent).map((c) => c.url)).toEqual([
+ 'u3',
+ 'u1',
+ 'u2',
+ ]);
+ });
+
+ it('recent 按最近观看顺序,未观看排最后', () => {
+ const recent = new Map([
+ ['u3', 0],
+ ['u1', 1],
+ ]);
+ expect(sortChannels(list, 'recent', noProbe, recent).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..ede99cf
--- /dev/null
+++ b/src/lib/live-channel-filter.ts
@@ -0,0 +1,128 @@
+/**
+ * 直播频道侧栏的筛选/排序纯逻辑(便于单测,组件只负责渲染)。
+ * 抽取自 live-channel-list.tsx,避免筛选语义散落在 JSX 里。
+ */
+
+export type LiveSortMode = 'default' | 'name' | 'group' | 'probe' | 'recent';
+
+/** 可用性筛选档位:off=不过滤;ok=包含弱验证/超时(琥珀);green=仅分片级验证通过 */
+export type AliveFilter = 'off' | 'ok' | 'green';
+
+export interface ProbeView {
+ ok: boolean;
+ level?: 'segment' | 'manifest' | 'head';
+ ms?: number;
+ timedOut?: boolean;
+ error?: string;
+}
+
+/** 筛选/排序所需的最小频道字段(LiveChannel 结构上满足即可) */
+export interface FilterableChannel {
+ name: string;
+ url: string;
+ group?: string;
+ tvgId?: string;
+}
+
+/** 搜索归一化:小写并去掉空白与常见分隔符,让 "cctv1" 能命中 "CCTV-1"、"东方-卫视" 命中 "东方卫视" */
+export function normalizeForSearch(input: string): string {
+ return input.toLowerCase().replace(/[\s\-_./·|+()()【】[\]]/g, '');
+}
+
+/** 关键字匹配:频道名、tvg-id、分组名(均做归一化,分组名也参与匹配) */
+export function matchesKeyword(
+ channel: Pick<FilterableChannel, 'name' | 'tvgId' | 'group'>,
+ keyword: string
+): boolean {
+ const kw = normalizeForSearch(keyword);
+ if (!kw) return true;
+ return (
+ normalizeForSearch(channel.name).includes(kw) ||
+ normalizeForSearch(channel.tvgId || '').includes(kw) ||
+ normalizeForSearch(channel.group || '').includes(kw)
+ );
+}
+
+/** 可用性判定 */
+export function matchesAlive(probe: ProbeView | undefined, mode: AliveFilter): boolean {
+ if (mode === 'off') return true;
+ if (!probe) return false;
+ if (mode === 'green') return probe.ok && probe.level === 'segment';
+ return probe.ok; // ok=绿 + 琥珀(弱验证 / 超时)
+}
+
+/** 测活结果的排序权重:绿点(分片级)最优,其次弱验证、超时、失败、未测 */
+function probeRank(probe: ProbeView | undefined): number {
+ if (!probe) return 4;
+ if (probe.ok) return probe.level === 'segment' ? 0 : 1;
+ return probe.timedOut ? 2 : 3;
+}
+
+/** 按当前可见列表统计各分组的频道数 */
+export function countGroups(list: Pick<FilterableChannel, 'group'>[]): Map<string, number> {
+ const counts = new Map<string, number>();
+ for (const c of list) {
+ if (!c.group) continue;
+ counts.set(c.group, (counts.get(c.group) ?? 0) + 1);
+ }
+ return counts;
+}
+
+/** 统计可用数:green 仅分片级;ok 含琥珀 */
+export function countAlive(
+ list: Pick<FilterableChannel, 'url'>[],
+ probeOf: (url: string) => ProbeView | undefined
+): { green: number; ok: number } {
+ let green = 0;
+ let ok = 0;
+ for (const c of list) {
+ const probe = probeOf(c.url);
+ if (!probe?.ok) continue;
+ ok++;
+ if (probe.level === 'segment') green++;
+ }
+ return { green, ok };
+}
+
+/**
+ * 排序:default 保持传入顺序(源顺序 / 最近观看顺序);
+ * probe 为"可用优先 + 分片耗时升序",让能播且快的排前面。
+ */
+export function sortChannels<T extends FilterableChannel>(
+ list: T[],
+ mode: LiveSortMode,
+ probeOf: (url: string) => ProbeView | undefined,
+ recentOrder: Map<string, number>
+): T[] {
+ if (mode === 'default') return list;
+ const copy = [...list];
+ switch (mode) {
+ case 'name':
+ copy.sort((a, b) => a.name.localeCompare(b.name, 'zh'));
+ break;
+ case 'group':
+ copy.sort(
+ (a, b) =>
+ (a.group || '').localeCompare(b.group || '', 'zh') || a.name.localeCompare(b.name, 'zh')
+ );
+ break;
+ case 'probe':
+ copy.sort((a, b) => {
+ const pa = probeOf(a.url);
+ const pb = probeOf(b.url);
+ return (
+ probeRank(pa) - probeRank(pb) ||
+ (pa?.ms ?? Number.MAX_SAFE_INTEGER) - (pb?.ms ?? Number.MAX_SAFE_INTEGER)
+ );
+ });
+ break;
+ case 'recent':
+ copy.sort(
+ (a, b) =>
+ (recentOrder.get(a.url) ?? Number.MAX_SAFE_INTEGER) -
+ (recentOrder.get(b.url) ?? Number.MAX_SAFE_INTEGER)
+ );
+ break;
+ }
+ return copy;
+}
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 628ec2f..6b468d5 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -130,6 +130,9 @@ interface AppState extends AppSettings {
toggleLiveSelected: (url: string) => void;
toggleLiveFavorite: (channelUrl: string) => void;
addLiveRecent: (entry: Omit<LiveRecentEntry, 'timestamp'>) => void;
+ /** 从最近观看中移除单条 */
+ removeLiveRecent: (url: string) => void;
+ clearLiveRecent: () => void;
/** 合并写入测活结果,并顺带清理过期条目 */
setLiveProbeResults: (entries: Record<string, LiveProbeEntry>) => void;
clearLiveProbeResults: () => void;
@@ -384,6 +387,12 @@ export const useAppStore = create<AppState>()(
set({ liveRecent: [{ ...entry, timestamp: Date.now() }, ...rest].slice(0, 20) });
},
+ removeLiveRecent: (url) => {
+ set({ liveRecent: get().liveRecent.filter((r) => r.url !== url) });
+ },
+
+ clearLiveRecent: () => set({ liveRecent: [] }),
+
setLiveProbeResults: (entries) => {
const now = Date.now();
// 合并新结果并顺带清理过期条目,避免 localStorage 无限增长