Skip to content

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

feat(player): 跳过片段泛化为片头/中段/片尾并改为抽屉式标记

bestZwei811394801a5f
diff --git a/README.md b/README.md
index b1a5895..724e771 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,7 @@ LibreTV Next.js 迁移版:免费在线视频聚合搜索与观看平台。基
- **聚合搜索**:多采集站服务端并行搜索
- **跨源同名聚合**:同名影片合并为一张卡片,展开即可比较和选择各来源
-- **HLS 播放**:ArtPlayer + hls.js,广告分片过滤、片头片尾标记与自动跳过、自动连播、倍速、快捷键、移动端长按 3 倍速
+- **HLS 播放**:ArtPlayer + hls.js,广告分片过滤、跳过片段(片头/中段/片尾标记与自动跳过)、自动连播、倍速、快捷键、移动端长按 3 倍速
- **直播 / IPTV**:M3U 订阅解析,`/live` 页面按分组浏览、搜索频道并站内播放(HLS + HTTP-FLV),支持 XMLTV 节目单(EPG)与频道收藏;直播流经专用长连接代理(`/api/live/stream`)转发
- **进度同步**:播放进度与观看历史存于本机 IndexedDB,精确到秒的续播
- **换源测速**:跨源搜索同名资源并测速排序,一键切换保留集数位置
@@ -107,7 +107,7 @@ PASSWORD=your-password npm start # 监听 8080
1. **添加点播源**:设置 → 源管理 → 点播源 → 添加 API,填入 Apple CMS 采集站地址(如 `https://example.com/api.php/provide/vod`),可选填详情页地址(部分源需要爬详情页提取播放地址)。
2. **搜索**:勾选点播源后输入片名;搜索通过服务端聚合,个别源失败不影响整体结果。
-3. **播放**:详情弹窗选择剧集进入 `/watch`;支持快捷键(空格/←→/↑↓/F/Alt+←→)、移动端长按 3 倍速、自动连播、换源测速。观看/暂停时后续分片自动缓存到本地(设置可关),播放页可「下载本集」(TS/MP4)离线观看。播放页「片头片尾」可记录片头结束/片尾开始,之后同剧各集与同名资源自动跳过(设置可分别关闭自动跳,仍保留手动按钮)。
+3. **播放**:详情弹窗选择剧集进入 `/watch`;支持快捷键(空格/←→/↑↓/F/Alt+←→)、移动端长按 3 倍速、自动连播、换源测速。观看/暂停时后续分片自动缓存到本地(设置可关),播放页可「下载本集」(TS/MP4)离线观看。播放页「跳过标记」可标记片头/中段/片尾区间(快捷键 Shift+I 片头结束、Shift+O 片尾开始、Shift+S·Shift+E 中段区间),之后同剧各集与同名资源自动跳过——片头/中段跳到片段末尾,片尾则直接结束本集(是否连播下一集由自动连播决定),三类片段共用「自动跳过片段」一个开关;跳过时提示条带「撤销」,「跳过标记」抽屉可逐剧关闭、微调边界、试跳起点/终点(记录与试跳都会先暂停),命中区间在进度条上着色。
4. **进度与历史**:自动保存在本设备 IndexedDB,仅定位信息入库,播放时自动同步最新剧集。
5. **配置迁移**:设置 → 数据 → 配置导入导出(兼容旧版 LibreTV-Settings JSON 的历史记录迁移)。
diff --git a/src/app/watch/page.tsx b/src/app/watch/page.tsx
index a5e0c9e..a02c025 100644
--- a/src/app/watch/page.tsx
+++ b/src/app/watch/page.tsx
@@ -18,8 +18,9 @@ const PlayerShell = dynamic(() => import('@/components/player-shell').then((m) =
import { EmptyState, LoadingState, Spinner } from '@/components/states';
import { SwitchSourceModal } from '@/components/switch-source';
import { SkipMarkPanel } from '@/components/skip-mark-panel';
-import { skipMarkKey } from '@/lib/skip-marks';
+import { skipMarkKey, validateSegment, type SkipSegment } from '@/lib/skip-marks';
import type { PlayerSkipApi } from '@/components/player-shell';
+import { useToast } from '@/components/toast';
import { enqueueDownload } from '@/components/download-manager';
import { Icon } from '@/components/icon';
import { useAuth } from '@/components/auth';
@@ -53,6 +54,7 @@ function WatchContent() {
const router = useRouter();
const store = useAppStore();
const { verified } = useAuth();
+ const { toast } = useToast();
const sourceKey = searchParams.get('source') || '';
const vodId = searchParams.get('id') || '';
@@ -96,7 +98,7 @@ function WatchContent() {
return indexParam;
}, [episodes, indexParam]);
- // 片头片尾标记按剧名记忆:换集不变,换源到同名资源也能命中。
+ // 跳过片段按剧名记忆:换集不变,换源到同名资源也能命中。
// 标题缺失(直连链接)时退回 source:vodId,至少保证本源本片可用。
const skipMarkFallback = `${sourceKey}:${vodId || currentUrl}`;
const markKey = useMemo(
@@ -104,6 +106,12 @@ function WatchContent() {
[videoTitle, skipMarkFallback]
);
const skipMark = store.skipMarks[markKey];
+ const markedCount = skipMark?.segments.length ?? 0;
+
+ // 中段两步态的起点:页面层持有,面板按钮与 Shift+S/E 共用同一份状态
+ const [pendingStart, setPendingStart] = useState<number | null>(null);
+ // 换集清空中段两步态:起点属于上一集,不能和新集的位置拼成区间
+ useEffect(() => setPendingStart(null), [sourceKey, vodId, currentIndex]);
const goEpisode = useCallback(
(index: number) => {
@@ -170,6 +178,31 @@ function WatchContent() {
}
}, [store.autoplayNext, currentIndex, episodes.length, goEpisode, sourceKey, vodId]);
+ // 快捷键(Shift+I/O/S/E)记录片段:校验后写入
+ const handleRecordSegment = useCallback(
+ (segment: SkipSegment) => {
+ const duration = playerApiRef.current?.getDuration() ?? 0;
+ const existing = useAppStore.getState().skipMarks[markKey]?.segments ?? [];
+ const error = validateSegment(segment, duration, existing);
+ if (error) {
+ toast(error, 'error');
+ return;
+ }
+ useAppStore.getState().setSkipMark(markKey, [...existing, segment]);
+ const label =
+ segment.type === 'opening' ? '片头结束' : segment.type === 'ending' ? '片尾开始' : '中段片段';
+ // 中段命中时的表现取决于全局「自动跳过片段」,记完就说清楚,避免"标了却没反应"
+ const hint =
+ segment.type === 'middle'
+ ? useAppStore.getState().autoSkipSegments
+ ? ',命中时将自动跳过'
+ : ',命中时显示跳过按钮'
+ : '';
+ toast(`已记录${label}${hint}`, 'success');
+ },
+ [markKey, toast]
+ );
+
// Alt+←/→ 集数切换快捷键
useEffect(() => {
const handler = (e: KeyboardEvent) => {
@@ -258,9 +291,11 @@ function WatchContent() {
adFilter={store.adFilter}
autoplayNext={store.autoplayNext}
skipMark={skipMark}
- autoSkipIntro={store.autoSkipIntro}
- autoSkipOutro={store.autoSkipOutro}
+ autoSkipSegments={store.autoSkipSegments}
+ pendingStart={pendingStart}
+ onPendingStart={setPendingStart}
onPlayerApi={(api) => { playerApiRef.current = api; }}
+ onRecordSegment={handleRecordSegment}
episodeKey={`${sourceKey}:${vodId}:${currentIndex}`}
nextUrl={currentIndex + 1 < episodes.length ? episodes[currentIndex + 1] : undefined}
nextEpisodeKey={currentIndex + 1 < episodes.length ? `${sourceKey}:${vodId}:${currentIndex + 1}` : undefined}
@@ -310,11 +345,20 @@ function WatchContent() {
下一集
</button>
<button
- className="btn-ghost btn-sm"
+ className={cn('btn-ghost btn-sm', skipPanelOpen && 'bg-chip text-content')}
aria-expanded={skipPanelOpen}
+ aria-haspopup="dialog"
onClick={() => setSkipPanelOpen((v) => !v)}
+ title={
+ markedCount > 0
+ ? `本剧已标记 ${markedCount} 段${skipMark?.enabled === false ? '(本剧跳过已关闭)' : ''}`
+ : '标记片头 / 中段 / 片尾,供本剧各集自动跳过'
+ }
>
- 片头片尾
+ 跳过标记{markedCount > 0 ? ` (${markedCount})` : ''}
+ {markedCount > 0 && skipMark?.enabled === false && (
+ <span className="ml-1 inline-block size-1.5 rounded-full bg-faint" aria-label="本剧跳过已关闭" />
+ )}
</button>
<label className="flex items-center gap-1.5 text-xs text-muted ml-auto cursor-pointer">
<input
@@ -327,16 +371,24 @@ function WatchContent() {
</label>
</div>
- {skipPanelOpen && (
- <SkipMarkPanel
- markKey={markKey}
- getPlayerClock={() => {
- const api = playerApiRef.current;
- if (!api) return null;
- return { currentTime: api.getCurrentTime(), duration: api.getDuration() };
- }}
- />
- )}
+ <SkipMarkPanel
+ open={skipPanelOpen}
+ onClose={() => setSkipPanelOpen(false)}
+ markKey={markKey}
+ pendingStart={pendingStart}
+ onPendingStart={setPendingStart}
+ getPlayerClock={() => {
+ const api = playerApiRef.current;
+ if (!api) return null;
+ return {
+ currentTime: api.getCurrentTime(),
+ duration: api.getDuration(),
+ seek: (s) => api.seek(s),
+ pause: () => api.pause(),
+ isPaused: () => api.isPaused(),
+ };
+ }}
+ />
</div>
{/* 剧集侧栏 */}
diff --git a/src/components/player-shell.tsx b/src/components/player-shell.tsx
index af6e531..7bfa3ef 100644
--- a/src/components/player-shell.tsx
+++ b/src/components/player-shell.tsx
@@ -14,10 +14,14 @@ import { loadCacheSettings } from '@/lib/video-cache';
import { formatTime } from '@/lib/utils';
import { prefersTouchPointer } from '@/lib/touch-pointer';
import {
- hasCrossedOutro,
- isIntroActive,
- resolveSkipWindow,
+ findActiveSegment,
+ findCrossedEnding,
+ resolveSegments,
+ SEGMENT_COLORS,
+ SEGMENT_LABELS,
+ type ResolvedSegment,
type SkipMark,
+ type SkipSegment,
} from '@/lib/skip-marks';
import {
ART_DEFAULT_CONTROL_HIDE_MS,
@@ -25,6 +29,9 @@ import {
TOUCH_CONTROL_HIDE_MS,
} from '@/lib/control-hide';
+/** 片段时间统一保留 1 位小数:与面板展示保持一致,避免浮点尾巴 */
+const round1 = (v: number) => Math.round(v * 10) / 10;
+
/**
* 播放器外壳:ArtPlayer + hls.js(旧版 player.js 的 React 化)。
* 保留:广告分片过滤、自动连播回调、进度回调、快捷键、移动端长按倍速、错误恢复。
@@ -39,6 +46,12 @@ import {
export interface PlayerSkipApi {
getCurrentTime(): number;
getDuration(): number;
+ /** 跳转到指定位置(「试跳」/标记片段起点用) */
+ seek(seconds: number): void;
+ /** 暂停播放:记录标记前先定格,避免点击到读取之间视频继续走 */
+ pause(): void;
+ /** 当前是否处于暂停状态 */
+ isPaused(): boolean;
}
interface PlayerShellProps {
@@ -46,14 +59,21 @@ interface PlayerShellProps {
title: string;
adFilter: boolean;
autoplayNext: boolean;
- /** 当前剧的片头片尾标记(父级按归一化剧名查好后传入,换集/换源不变) */
+ /** 当前剧的跳过片段标记(父级按归一化剧名查好后传入,换集/换源不变) */
skipMark?: SkipMark;
- /** 命中片头标记时自动跳到片头结束 */
- autoSkipIntro: boolean;
- /** 连续播放越过片尾标记时自动结束本集 */
- autoSkipOutro: boolean;
+ /**
+ * 自动跳过标记的片段:片头/中段跳到片段末尾,片尾(连续播放越过起点)结束本集。
+ * 是否连播下一集仍由 autoplayNext 决定。
+ */
+ autoSkipSegments: boolean;
+ /** 中段两步态的起点:由页面层持有,面板与快捷键共用同一份状态 */
+ pendingStart: number | null;
+ /** 更新中段起点;null 表示取消或已消费 */
+ onPendingStart: (start: number | null) => void;
/** 播放器创建/销毁时回调,供播放页读取精确播放位置 */
onPlayerApi?: (api: PlayerSkipApi | null) => void;
+ /** 快捷键(Shift+I/O/S/E)记录片段时回调,由父级做校验与写入 */
+ onRecordSegment?: (segment: SkipSegment) => void;
/** 剧集标识 `${source}:${vodId}:${episodeIndex}`(片段缓存按集淘汰的分组键) */
episodeKey?: string;
/** 下一集 m3u8 地址:当前集预取完成后预热下一集前 7 分钟 */
@@ -85,9 +105,11 @@ export function PlayerShell({
adFilter,
autoplayNext,
skipMark,
- autoSkipIntro,
- autoSkipOutro,
+ autoSkipSegments,
+ pendingStart,
+ onPendingStart,
onPlayerApi,
+ onRecordSegment,
episodeKey,
nextUrl,
nextEpisodeKey,
@@ -114,13 +136,15 @@ export function PlayerShell({
// 始终持有最新 props/回调,避免重建播放器
const propsRef = useRef({
- url, title, adFilter, autoplayNext, skipMark, autoSkipIntro, autoSkipOutro, onPlayerApi,
+ url, title, adFilter, autoplayNext, skipMark, autoSkipSegments,
+ pendingStart, onPendingStart, onPlayerApi, onRecordSegment,
episodeKey, nextUrl, nextEpisodeKey,
getRestorePosition, onTimeUpdate, onEnded, onPause, onQuality, onRequestSwitchSource,
onPrevEpisode, onNextEpisode, hasPrevEpisode, hasNextEpisode,
});
propsRef.current = {
- url, title, adFilter, autoplayNext, skipMark, autoSkipIntro, autoSkipOutro, onPlayerApi,
+ url, title, adFilter, autoplayNext, skipMark, autoSkipSegments,
+ pendingStart, onPendingStart, onPlayerApi, onRecordSegment,
episodeKey, nextUrl, nextEpisodeKey,
getRestorePosition, onTimeUpdate, onEnded, onPause, onQuality, onRequestSwitchSource,
onPrevEpisode, onNextEpisode, hasPrevEpisode, hasNextEpisode,
@@ -150,14 +174,18 @@ export function PlayerShell({
const recoveryRef = useRef<PlaybackRecovery | null>(null);
// 自然播完标记,卸载时不回写进度(避免覆盖「已看完」记录)
const endedRef = useRef(false);
- // 片头/片尾:每集各只处理一次,换集时重置(见 loadEpisode)
- const introHandledRef = useRef(false);
- const outroHandledRef = useRef(false);
+ // 跳过片段:每集已处理的片段(按 type:start 去重),换集时重置(见 loadEpisode)
+ const handledSegmentsRef = useRef<Set<string>>(new Set());
+ // 被「撤销」过的片段:本集不再自动跳(否则撤回到片段内会被立刻再跳走),但仍保留提示按钮
+ const suppressedAutoRef = useRef<Set<string>>(new Set());
// 上一次 timeupdate 的位置:用于区分「连续播放越过片尾」与「拖动进度条」
const lastSampleRef = useRef(0);
// 跳过按钮提示;用 ref 比较,避免 timeupdate 每 250ms 触发重渲染
- const [skipPrompt, setSkipPrompt] = useState<'intro' | 'outro' | null>(null);
- const skipPromptRef = useRef<'intro' | 'outro' | null>(null);
+ const [skipPrompt, setSkipPrompt] = useState<ResolvedSegment | null>(null);
+ const skipPromptRef = useRef<ResolvedSegment | null>(null);
+ // 刚跳过的片段:给一个撤销窗口,误标导致跳掉正片时不必手动拖回去
+ const [undoSkip, setUndoSkip] = useState<{ from: number; segment: ResolvedSegment } | null>(null);
+ const undoTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const showHint = (text: string) => {
setHint(text);
@@ -213,35 +241,95 @@ export function PlayerShell({
});
};
- /** 切换提示状态;相同值直接返回,避免 timeupdate 高频 setState */
- const updateSkipPrompt = (next: 'intro' | 'outro' | null) => {
- if (skipPromptRef.current === next) return;
+ /** 切换提示状态;值相同直接返回,避免 timeupdate 高频 setState */
+ const updateSkipPrompt = (next: ResolvedSegment | null) => {
+ const prev = skipPromptRef.current;
+ const same =
+ prev === next ||
+ (prev !== null &&
+ next !== null &&
+ prev.type === next.type &&
+ prev.start === next.start &&
+ prev.end === next.end);
+ if (same) return;
skipPromptRef.current = next;
setSkipPrompt(next);
};
- /** 跳到片头结束并续跑预取;同步 lastSampleRef,避免下一拍被误判为「连续越过片尾」 */
- const skipTo = (seconds: number) => {
+ /** 片段去重键:按类型 + 起点,同一集内每段只处理一次 */
+ const segmentKey = (s: ResolvedSegment) => `${s.type}:${s.start}`;
+
+ /** 进度条区间可视化:在进度条轨道叠加半透明色带(颜色与面板图例共用 SEGMENT_COLORS) */
+ const renderSkipMarks = () => {
+ const art = artRef.current;
+ const progress = art?.template.$progress;
+ if (!progress) return;
+ progress.querySelectorAll('[data-skip-segment]').forEach((el: Element) => el.remove());
+ const duration = art.duration;
+ if (!Number.isFinite(duration) || duration <= 0) return;
+ const segments = resolveSegments(propsRef.current.skipMark, duration);
+ for (const seg of segments) {
+ const el = document.createElement('div');
+ el.dataset.skipSegment = '1';
+ el.title = `跳过${SEGMENT_LABELS[seg.type]}`;
+ const left = (seg.start / duration) * 100;
+ const width = Math.max(0.4, ((seg.end - seg.start) / duration) * 100);
+ el.style.cssText = `position:absolute;left:${left}%;width:${width}%;top:0;bottom:0;background:${SEGMENT_COLORS[seg.type]};pointer-events:none;`;
+ progress.appendChild(el);
+ }
+ };
+
+ /**
+ * 跳到片段末尾并续跑预取;同步 lastSampleRef,避免下一拍被误判为「连续越过片尾」。
+ * 返回是否成功:媒体未就绪导致赋值失败时返回 false,调用方不置已处理标记,
+ * 下一次 timeupdate 会重新判定(保证「可重试」)。
+ */
+ const skipTo = (seconds: number): boolean => {
const art = artRef.current;
- if (!art || !Number.isFinite(seconds) || seconds < 0) return;
+ if (!art || !Number.isFinite(seconds) || seconds < 0) return false;
try {
art.currentTime = seconds;
} catch {
- /* 媒体尚未就绪时忽略,下一次 timeupdate 会再次判定 */
+ return false;
}
lastSampleRef.current = seconds;
ensurePrefetch(currentMediaUrlRef.current, seconds);
+ return true;
+ };
+
+ /** 记录一次跳过(跳转前的位置):给 12s 撤销窗口,误标导致跳掉正片时不用手动拖回去 */
+ const rememberSkip = (from: number, segment: ResolvedSegment) => {
+ setUndoSkip({ from, segment });
+ if (undoTimerRef.current) clearTimeout(undoTimerRef.current);
+ undoTimerRef.current = setTimeout(() => setUndoSkip(null), 12_000);
+ };
+
+ const undoLastSkip = () => {
+ const last = undoSkip;
+ if (!last) return;
+ if (undoTimerRef.current) {
+ clearTimeout(undoTimerRef.current);
+ undoTimerRef.current = null;
+ }
+ // 撤销后把片段从「已处理」移除(按钮会重新出现),同时本集不再自动跳它:
+ // 否则回到片段内会被下一次 timeupdate 立刻再跳走,形成"撤销→又被跳过"的死循环
+ handledSegmentsRef.current.delete(segmentKey(last.segment));
+ suppressedAutoRef.current.add(segmentKey(last.segment));
+ skipTo(last.from);
+ setUndoSkip(null);
+ showHint('已撤回跳过');
};
/**
* 跳过片尾:与自然播完共用 onEnded 链路(清进度 + 依 autoplayNext 连播下一集)。
* endedRef 置 true 同时阻止 video:ended 重复回调,也避免卸载时把片尾进度回写。
*/
- const finishBySkip = () => {
+ const finishBySkip = (ending?: ResolvedSegment) => {
const art = artRef.current;
- outroHandledRef.current = true;
+ if (ending) handledSegmentsRef.current.add(segmentKey(ending));
endedRef.current = true;
updateSkipPrompt(null);
+ setUndoSkip(null);
try {
art?.pause();
} catch {
@@ -382,12 +470,13 @@ export function PlayerShell({
videoErrorRetryUsedRef.current = false;
restoredRef.current = false;
lastPrefetchEnsureRef.current = 0;
- // 片头/片尾按集重置:上一集已处理过不意味新一集也处理过
- introHandledRef.current = false;
- outroHandledRef.current = false;
+ // 跳过片段按集重置:上一集已处理过不意味新一集也处理过
+ handledSegmentsRef.current.clear();
+ suppressedAutoRef.current.clear();
lastSampleRef.current = 0;
endedRef.current = false;
updateSkipPrompt(null);
+ setUndoSkip(null);
recoveryRef.current = new PlaybackRecovery();
// 换集时清掉上一集的预取窗口,避免带宽被旧集占用
getVideoPrefetcher().stop();
@@ -415,8 +504,8 @@ export function PlayerShell({
restoredRef.current = false;
recoveryRef.current = new PlaybackRecovery();
endedRef.current = false;
- introHandledRef.current = false;
- outroHandledRef.current = false;
+ handledSegmentsRef.current.clear();
+ suppressedAutoRef.current.clear();
lastSampleRef.current = 0;
let lastSave = 0;
@@ -475,6 +564,14 @@ export function PlayerShell({
});
artRef.current = art;
+ // 进度条区间可视化:初始渲染一次,换集 duration 变化时重绘
+ renderSkipMarks();
+ art.on('video:durationchange', renderSkipMarks);
+ // 全屏切换 / 播放器尺寸变化会重建控件,色带随之被清掉,这里补一次重绘
+ art.on('fullscreen', renderSkipMarks);
+ art.on('fullscreenWeb', renderSkipMarks);
+ art.on('resize', renderSkipMarks);
+
// 播放页「记录当前」需要精确时间:不能依赖 5s 节流的 onTimeUpdate
propsRef.current.onPlayerApi?.({
getCurrentTime: () => {
@@ -485,6 +582,22 @@ export function PlayerShell({
const duration = artRef.current?.duration;
return typeof duration === 'number' && Number.isFinite(duration) ? duration : 0;
},
+ seek: (seconds) => {
+ if (!Number.isFinite(seconds) || seconds < 0) return;
+ try {
+ artRef.current.currentTime = seconds;
+ } catch {
+ /* 忽略 */
+ }
+ },
+ pause: () => {
+ try {
+ artRef.current?.pause();
+ } catch {
+ /* 忽略 */
+ }
+ },
+ isPaused: () => artRef.current?.video?.paused ?? true,
});
/**
@@ -545,52 +658,53 @@ export function PlayerShell({
ensurePrefetch(currentMediaUrlRef.current, art.currentTime);
}
- // —— 片头 / 片尾跳过 ——
+ // —— 跳过片段判定 ——
const p = propsRef.current;
const current = art.currentTime;
const duration = art.duration;
const previous = lastSampleRef.current;
lastSampleRef.current = current;
- const window = resolveSkipWindow(p.skipMark, duration);
-
- // 片头:一旦自然越过或已自动跳转,本集不再处理;用户之后拖回片头也不会被反复拉扯。
- // 必须等进度恢复完成(restoredRef)且已真正开始播放,否则会先跳到片头结束、
- // 再被 restoreAndStart 拉回断点处。
- if (window.introEnd !== undefined && !introHandledRef.current) {
- if (current >= window.introEnd) {
- introHandledRef.current = true;
- } else if (
- p.autoSkipIntro &&
- restoredRef.current &&
- playbackStartedRef.current &&
- isIntroActive(current, window)
- ) {
- introHandledRef.current = true;
- skipTo(window.introEnd);
- showHint('已跳过片头');
- }
+ const segments = resolveSegments(p.skipMark, duration);
+
+ // 结尾片段:只认连续播放越过起点;拖动进度条、刚写入标记、进度恢复造成的大跳变
+ // 都不自动结束,只显示按钮由用户决定。是否结束由合并后的 autoSkipSegments 控制
+ // (片头/中段跳段,片尾结束本集,是否连播下一集仍看 autoplayNext)。
+ if (
+ p.autoSkipSegments &&
+ restoredRef.current &&
+ playbackStartedRef.current &&
+ findCrossedEnding(segments, previous, current)
+ ) {
+ const ending = segments.find(
+ (s) => s.type === 'ending' && previous < s.start && current >= s.start
+ );
+ finishBySkip(ending);
+ return;
}
- // 片尾:只认连续播放越过边界;拖动进度条、刚写入标记、进度恢复造成的大跳变
- // 都不自动结束,只显示按钮由用户决定。
- if (window.outroStart !== undefined && !outroHandledRef.current) {
- if (current >= duration - 0.5) {
- outroHandledRef.current = true;
- } else if (
- p.autoSkipOutro &&
- playbackStartedRef.current &&
- hasCrossedOutro(previous, current, window)
- ) {
- finishBySkip();
- return;
+ // 片头/中段片段:命中则自动跳到末尾(同一类操作,共用 autoSkipSegments 开关);
+ // 已处理过的片段本集不再反复拉扯。
+ const active = findActiveSegment(segments, current);
+ if (
+ active &&
+ active.type !== 'ending' &&
+ p.autoSkipSegments &&
+ !handledSegmentsRef.current.has(segmentKey(active)) &&
+ !suppressedAutoRef.current.has(segmentKey(active)) &&
+ restoredRef.current &&
+ playbackStartedRef.current
+ ) {
+ if (skipTo(active.end)) {
+ handledSegmentsRef.current.add(segmentKey(active));
+ rememberSkip(current, active);
+ showHint(active.type === 'opening' ? '已跳过片头' : '已跳过中段');
}
}
- const introActive =
- window.introEnd !== undefined && !introHandledRef.current && isIntroActive(current, window);
- const outroActive =
- window.outroStart !== undefined && !outroHandledRef.current && current >= window.outroStart;
- updateSkipPrompt(introActive ? 'intro' : outroActive ? 'outro' : null);
+ // 按钮提示:当前落在某个未处理片段内(结尾片段显示「跳过片尾」)
+ const prompt =
+ active && !handledSegmentsRef.current.has(segmentKey(active)) ? active : null;
+ updateSkipPrompt(prompt);
});
art.on('video:seeked', () => {
ensurePrefetch(currentMediaUrlRef.current, art.currentTime);
@@ -598,12 +712,11 @@ export function PlayerShell({
// 暂停中 seek 不会触发 timeupdate,这里也同步刷新按钮的显隐。
const current = art.currentTime;
lastSampleRef.current = current;
- const window = resolveSkipWindow(propsRef.current.skipMark, art.duration);
- const introActive =
- window.introEnd !== undefined && !introHandledRef.current && isIntroActive(current, window);
- const outroActive =
- window.outroStart !== undefined && !outroHandledRef.current && current >= window.outroStart;
- updateSkipPrompt(introActive ? 'intro' : outroActive ? 'outro' : null);
+ const segments = resolveSegments(propsRef.current.skipMark, art.duration);
+ const active = findActiveSegment(segments, current);
+ const prompt =
+ active && !handledSegmentsRef.current.has(segmentKey(active)) ? active : null;
+ updateSkipPrompt(prompt);
});
art.on('video:pause', () => {
// 跳过片尾会主动 pause:此时已按「看完」处理,不能再把片尾位置写回进度
@@ -656,6 +769,45 @@ export function PlayerShell({
case 'f': case 'F':
current.fullscreen = !current.fullscreen; e.preventDefault();
break;
+ // 标记类快捷键一律要求 Shift:这几键会直接写盘并影响整部剧,
+ // 单键太容易误触(误记片头 = 之后每集都被跳过一大段)
+ case 'i': case 'I':
+ if (!e.shiftKey) break;
+ propsRef.current.onRecordSegment?.({
+ type: 'opening',
+ start: 0,
+ end: round1(current.currentTime),
+ });
+ e.preventDefault();
+ break;
+ case 'o': case 'O':
+ if (!e.shiftKey) break;
+ propsRef.current.onRecordSegment?.({
+ type: 'ending',
+ start: round1(current.currentTime),
+ end: -1,
+ });
+ e.preventDefault();
+ break;
+ case 's': case 'S':
+ if (!e.shiftKey) break;
+ propsRef.current.onPendingStart(round1(current.currentTime));
+ showHint('片段起点已记录,播放到终点后按 Shift+E');
+ e.preventDefault();
+ break;
+ case 'e': case 'E': {
+ if (!e.shiftKey) break;
+ const start = propsRef.current.pendingStart;
+ if (start === null) {
+ showHint('请先按 Shift+S 记录片段起点');
+ } else {
+ const end = round1(current.currentTime);
+ propsRef.current.onPendingStart(null);
+ propsRef.current.onRecordSegment?.({ type: 'middle', start, end });
+ }
+ e.preventDefault();
+ break;
+ }
}
};
document.addEventListener('keydown', shortcuts);
@@ -744,6 +896,7 @@ export function PlayerShell({
document.removeEventListener('keydown', shortcuts);
document.removeEventListener('visibilitychange', saveOnHide);
if (hintTimerRef.current) clearTimeout(hintTimerRef.current);
+ if (undoTimerRef.current) clearTimeout(undoTimerRef.current);
el?.removeEventListener('touchstart', onTouchStart);
el?.removeEventListener('touchend', onTouchEnd);
el?.removeEventListener('touchcancel', onTouchEnd);
@@ -783,21 +936,21 @@ export function PlayerShell({
});
}, [hasPrevEpisode, hasNextEpisode, url]);
- // —— 标记变化:重置片尾采样基准并立即刷新提示 ——
- // 刚记录「片尾开始」时当前时间恰好等于新边界,若沿用上一拍采样会被判成
- // 「连续越过」而当场结束本集;把基准拉平后本集只保留手动按钮,下一集才自动跳。
+ // —— 标记变化:重置采样基准并立即刷新提示 ——
+ // 刚写入片段时当前时间可能恰好等于新边界,若沿用上一拍采样会被判成
+ // 「连续越过」而当场触发;把基准拉平后本集只保留手动按钮,下一集才自动。
// 顺带覆盖暂停中修改标记的场景(没有 timeupdate 也要让按钮即时出现/消失)。
useEffect(() => {
const art = artRef.current;
if (!art) return;
const current = art.currentTime;
lastSampleRef.current = Number.isFinite(current) ? current : 0;
- const window = resolveSkipWindow(skipMark, art.duration);
- const introActive =
- window.introEnd !== undefined && !introHandledRef.current && isIntroActive(current, window);
- const outroActive =
- window.outroStart !== undefined && !outroHandledRef.current && current >= window.outroStart;
- updateSkipPrompt(introActive ? 'intro' : outroActive ? 'outro' : null);
+ const segments = resolveSegments(skipMark, art.duration);
+ const active = findActiveSegment(segments, current);
+ const prompt =
+ active && !handledSegmentsRef.current.has(segmentKey(active)) ? active : null;
+ updateSkipPrompt(prompt);
+ renderSkipMarks();
}, [skipMark]);
// —— 换集:仅切换 HLS 源,不重建播放器(保留网页全屏等状态) ——
@@ -839,23 +992,24 @@ export function PlayerShell({
type="button"
className="absolute bottom-16 left-1/2 -translate-x-1/2 z-10 rounded-full bg-black/70 px-4 py-2 text-sm text-white transition-colors hover:bg-black/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
onClick={() => {
- if (skipPrompt === 'intro') {
- // 用当前这集的有效窗口取目标位置:持久化标记可能已越界/损坏
- const window = resolveSkipWindow(propsRef.current.skipMark, artRef.current?.duration ?? 0);
- if (window.introEnd === undefined) {
- updateSkipPrompt(null);
- return;
- }
- introHandledRef.current = true;
- skipTo(window.introEnd);
- updateSkipPrompt(null);
- showHint('已跳过片头');
+ if (skipPrompt.type === 'ending') {
+ finishBySkip(skipPrompt);
return;
}
- finishBySkip();
+ const from = artRef.current?.currentTime ?? 0;
+ if (skipTo(skipPrompt.end)) {
+ handledSegmentsRef.current.add(segmentKey(skipPrompt));
+ rememberSkip(from, skipPrompt);
+ updateSkipPrompt(null);
+ showHint(skipPrompt.type === 'opening' ? '已跳过片头' : '已跳过中段');
+ }
}}
>
- {skipPrompt === 'intro' ? '跳过片头' : '跳过片尾'}
+ {skipPrompt.type === 'ending'
+ ? '跳过片尾'
+ : skipPrompt.type === 'opening'
+ ? '跳过片头'
+ : '跳过中段'}
</button>
)}
{error && (
@@ -866,9 +1020,21 @@ export function PlayerShell({
</button>
</div>
)}
- {hint && (
- <div className="absolute top-4 left-1/2 -translate-x-1/2 bg-black/70 text-white text-sm px-3 py-1.5 rounded-full pointer-events-none animate-fade-in">
- {hint}
+ {(hint || undoSkip) && (
+ <div className="absolute top-4 left-1/2 -translate-x-1/2 z-10 flex items-center gap-2 rounded-full bg-black/70 px-3 py-1.5 text-sm text-white animate-fade-in">
+ {/* 撤销窗口比普通提示长:hint 已淡出时仍要让用户知道刚才跳过了什么 */}
+ <span className="pointer-events-none">
+ {hint || (undoSkip ? `已跳过${SEGMENT_LABELS[undoSkip.segment.type]}` : '')}
+ </span>
+ {undoSkip && (
+ <button
+ type="button"
+ className="pointer-events-auto shrink-0 rounded-full bg-white/20 px-2 py-0.5 text-xs font-medium transition-colors hover:bg-white/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
+ onClick={undoLastSkip}
+ >
+ 撤销
+ </button>
+ )}
</div>
)}
{autoplayNext && !error && (
diff --git a/src/components/skip-mark-panel.tsx b/src/components/skip-mark-panel.tsx
index 484c9e5..0577ff0 100644
--- a/src/components/skip-mark-panel.tsx
+++ b/src/components/skip-mark-panel.tsx
@@ -1,106 +1,390 @@
'use client';
+import { useEffect, useRef, useState } from 'react';
import { useAppStore } from '@/lib/store';
-import { validateIntroEnd, validateOutroStart } from '@/lib/skip-marks';
-import { formatTime } from '@/lib/utils';
+import {
+ SEGMENT_COLORS,
+ SEGMENT_LABELS,
+ validateSegment,
+ type SkipSegment,
+ type SkipSegmentType,
+} from '@/lib/skip-marks';
+import { cn, formatTime } from '@/lib/utils';
import { useToast } from './toast';
+import { Drawer } from './drawer';
/**
- * 播放页的片头/片尾标记面板。
+ * 播放页的「跳过标记」抽屉。
*
* 采集站不提供片头片尾元数据,边界只能由用户在看的时候标记一次,
- * 之后同剧各集与同名资源自动套用。面板只负责「记录当前 / 清除」两个动作,
+ * 之后同剧各集与同名资源自动套用。片段按位置归类:opening(片头)、
+ * middle(中段)、ending(片尾)。抽屉负责「记录/试跳/微调/删除」,
* 真正的跳过判定在 player-shell.tsx,存储与校验在 lib/skip-marks.ts。
+ *
+ * 交互约定:
+ * - 记录/试跳前先暂停:抽屉贴在播放器旁边,点击到读取之间视频还在走,容易偏 1–2 秒;
+ * - 顶部常驻「当前 12:34 / 45:00」,试跳与微调都有参照;
+ * - 中段两步态的起点由播放页持有(pendingStart),与 Shift+S/E 共用同一份状态;
+ * - 全局「自动跳过片段」在这里只读展示(层级不同,避免和「本剧跳过」并排成两个 checkbox)。
*/
interface PlayerClock {
currentTime: number;
duration: number;
+ seek(seconds: number): void;
+ pause(): void;
+ isPaused(): boolean;
}
-type MotionField = 'introEnd' | 'outroStart';
+const SEGMENT_TYPES: SkipSegmentType[] = ['opening', 'middle', 'ending'];
-const ROWS: { field: MotionField; label: string; hint: string }[] = [
- { field: 'introEnd', label: '片头结束', hint: '正片开始的位置' },
- { field: 'outroStart', label: '片尾开始', hint: '片尾曲开始的位置' },
-];
+const round1 = (v: number) => Math.round(v * 10) / 10;
export function SkipMarkPanel({
+ open,
+ onClose,
markKey,
+ pendingStart,
+ onPendingStart,
getPlayerClock,
}: {
+ open: boolean;
+ onClose: () => void;
/** 已归一化的标记键(watch 页按剧名计算) */
markKey: string;
- /** 读取播放器当前时间;播放器未就绪时返回 null */
+ /** 中段两步态起点(页面层持有) */
+ pendingStart: number | null;
+ onPendingStart: (start: number | null) => void;
+ /** 读取播放器当前时间/时长/跳转;播放器未就绪时返回 null */
getPlayerClock: () => PlayerClock | null;
}) {
const mark = useAppStore((s) => s.skipMarks[markKey]);
const setSkipMark = useAppStore((s) => s.setSkipMark);
+ const setSkipMarkEnabled = useAppStore((s) => s.setSkipMarkEnabled);
+ const autoSkipSegments = useAppStore((s) => s.autoSkipSegments);
const { toast } = useToast();
- const record = (field: MotionField) => {
- const clock = getPlayerClock();
- if (!clock || clock.currentTime <= 0) {
+ const segments = (mark?.segments ?? []).slice().sort((a, b) => a.start - b.start);
+ const enabled = mark ? mark.enabled !== false : false;
+
+ // 当前进度:抽屉打开时每秒刷新一次;用 ref 拿最新的取数函数,避免每秒重置定时器
+ const clockFnRef = useRef(getPlayerClock);
+ clockFnRef.current = getPlayerClock;
+ const [clock, setClock] = useState({ current: 0, duration: 0, paused: true });
+ useEffect(() => {
+ if (!open) return;
+ const tick = () => {
+ const c = clockFnRef.current();
+ setClock({
+ current: c?.currentTime ?? 0,
+ duration: c?.duration ?? 0,
+ paused: c ? c.isPaused() : true,
+ });
+ };
+ tick();
+ const timer = setInterval(tick, 1000);
+ return () => clearInterval(timer);
+ }, [open]);
+
+ const write = (next: SkipSegment[]) => setSkipMark(markKey, next);
+
+ // 记录/试跳前统一「先暂停再取时间」:暂停后 currentTime 才是用户看到的画面位置
+ const pauseAndSnap = (): { t: number; duration: number } | null => {
+ const c = getPlayerClock();
+ if (!c) {
toast('播放器尚未就绪,请稍后再试', 'warning');
+ return null;
+ }
+ if (!c.isPaused()) c.pause();
+ setClock({ current: c.currentTime, duration: c.duration, paused: true });
+ return { t: round1(c.currentTime), duration: c.duration };
+ };
+
+ /** 记录一条片段;成功返回 true(失败时保留两步态,用户可以改位置重试) */
+ const tryRecord = (segment: SkipSegment, label: string, duration: number): boolean => {
+ const error = validateSegment(segment, duration, segments);
+ if (error) {
+ toast(error, 'error');
+ return false;
+ }
+ write([...segments, segment]);
+ const effect = autoSkipSegments
+ ? segment.type === 'ending'
+ ? ',越过起点后自动结束本集'
+ : ',命中时将自动跳过'
+ : segment.type === 'ending'
+ ? ',命中时显示「跳过片尾」按钮'
+ : ',命中时显示跳过按钮';
+ const at =
+ segment.type === 'ending'
+ ? formatTime(segment.start)
+ : segment.type === 'middle'
+ ? `${formatTime(segment.start)} → ${formatTime(segment.end)}`
+ : formatTime(segment.end);
+ toast(`已记录${label} ${at}${effect}`, 'success');
+ return true;
+ };
+
+ const recordAt = (type: 'opening' | 'ending') => {
+ const snap = pauseAndSnap();
+ if (!snap) return;
+ if (snap.t <= 0) {
+ toast(type === 'opening' ? '请先播放到片头结束的位置' : '请先播放到片尾开始的位置', 'warning');
+ return;
+ }
+ if (type === 'opening') tryRecord({ type, start: 0, end: snap.t }, '片头结束', snap.duration);
+ else tryRecord({ type, start: snap.t, end: -1 }, '片尾开始', snap.duration);
+ };
+
+ const markMiddleStart = () => {
+ const snap = pauseAndSnap();
+ if (!snap) return;
+ if (snap.t <= 0) {
+ toast('请先播放到片段起点', 'warning');
+ return;
+ }
+ onPendingStart(snap.t);
+ toast(`已暂停并记录起点 ${formatTime(snap.t)},播放到终点后点「标记中段终点」`, 'info');
+ };
+
+ const markMiddleEnd = () => {
+ if (pendingStart === null) return;
+ const snap = pauseAndSnap();
+ if (!snap) return;
+ if (snap.t <= pendingStart) {
+ toast('终点需晚于起点', 'warning');
return;
}
- // 保留 0.1s:显示按秒取整,但跳转位置不因取整而漂移
- const value = Math.round(clock.currentTime * 10) / 10;
- const error =
- field === 'introEnd'
- ? validateIntroEnd(value, clock.duration, mark)
- : validateOutroStart(value, clock.duration, mark);
+ if (tryRecord({ type: 'middle', start: pendingStart, end: snap.t }, '中段片段', snap.duration)) {
+ onPendingStart(null);
+ }
+ };
+
+ const remove = (index: number) => {
+ const seg = segments[index];
+ if (!seg) return;
+ const wasDisabled = mark?.enabled === false;
+ write(segments.filter((_, i) => i !== index));
+ // 删除可撤销:误删后不必再拖回原位置重标
+ toast(`已删除${SEGMENT_LABELS[seg.type]}片段`, 'info', {
+ action: {
+ label: '撤销',
+ onClick: () => {
+ setSkipMark(markKey, segments);
+ if (wasDisabled) setSkipMarkEnabled(markKey, false);
+ },
+ },
+ });
+ };
+
+ const nudge = (index: number, delta: number) => {
+ const seg = segments[index];
+ if (!seg) return;
+ const changed: SkipSegment =
+ seg.type === 'ending'
+ ? { ...seg, start: round1(seg.start + delta) }
+ : seg.type === 'opening'
+ ? { ...seg, end: round1(seg.end + delta) }
+ : { ...seg, start: round1(seg.start + delta), end: round1(seg.end + delta) };
+ const clockNow = getPlayerClock();
+ const others = segments.filter((_, i) => i !== index);
+ const error = validateSegment(changed, clockNow?.duration ?? 0, others);
if (error) {
toast(error, 'error');
return;
}
- setSkipMark(markKey, { [field]: value });
- toast(
- `已将${field === 'introEnd' ? '片头结束' : '片尾开始'}设为 ${formatTime(value)}`,
- 'success'
- );
+ write(segments.map((s, i) => (i === index ? changed : s)));
};
- const clear = (field: MotionField) => {
- setSkipMark(markKey, { [field]: null });
- toast(`已清除${field === 'introEnd' ? '片头' : '片尾'}标记`, 'info');
+ /** 试跳:跳到后保持暂停,让用户先确认画面(终点落在片段末尾前 1s) */
+ const jump = (seg: SkipSegment, to: 'start' | 'end') => {
+ const c = getPlayerClock();
+ if (!c) {
+ toast('播放器尚未就绪,请稍后再试', 'warning');
+ return;
+ }
+ c.pause();
+ c.seek(to === 'start' ? seg.start : Math.max(0, seg.end - 1));
+ setClock({ current: to === 'start' ? seg.start : Math.max(0, seg.end - 1), duration: c.duration, paused: true });
};
+ /** 当前播放位置落在哪个片段里:列表里高亮出来,方便核对边界 */
+ const currentKey = segments.find((s) => {
+ if (clock.current < s.start) return false;
+ if (s.type === 'ending') return true;
+ return clock.current < s.end;
+ });
+
return (
- <div className="mt-3 rounded-lg border border-line bg-surface-raised p-3">
- <div className="space-y-2">
- {ROWS.map(({ field, label, hint }) => {
- const value = mark?.[field];
- return (
- <div key={field} className="flex flex-wrap items-center justify-between gap-2">
- <div className="flex items-baseline gap-2 min-w-0">
- <span className="text-sm text-content">{label}</span>
- <span className="text-xs text-faint">{hint}</span>
- <span className="text-xs font-mono text-muted">
- {value !== undefined ? formatTime(value) : '未设置'}
- </span>
- </div>
- <div className="flex items-center gap-1.5">
- <button type="button" className="btn-ghost btn-sm" onClick={() => record(field)}>
- 记录当前
- </button>
- <button
- type="button"
- className="btn-ghost btn-sm"
- disabled={value === undefined}
- onClick={() => clear(field)}
- >
- 清除
- </button>
- </div>
- </div>
- );
- })}
+ <Drawer open={open} onClose={onClose} title="跳过标记" width="max-w-sm">
+ {/* 当前进度 + 本剧开关:本剧作用域放最上,全局开关在底部只读展示,避免两个层级并排 */}
+ <div className="flex items-start justify-between gap-2">
+ <div>
+ <p className="text-xs text-muted">
+ 当前{' '}
+ <span className="font-mono text-content">{formatTime(clock.current)}</span>
+ <span className="text-faint"> / {formatTime(clock.duration)}</span>
+ {clock.paused && <span className="ml-1 text-faint">· 已暂停</span>}
+ </p>
+ <p className="mt-1 text-[11px] text-faint">
+ 已标记 {segments.length} 段 · 按剧名对本剧各集与同名资源生效
+ </p>
+ </div>
+ <label
+ className={cn(
+ 'flex shrink-0 items-center gap-1.5 text-xs',
+ mark ? 'cursor-pointer text-muted hover:text-content' : 'cursor-not-allowed text-faint/70'
+ )}
+ title={mark ? '关闭后保留标记但完全不生效' : '还没有可开关的标记'}
+ >
+ <input
+ type="checkbox"
+ className="h-3.5 w-3.5 accent-accent"
+ checked={enabled}
+ disabled={!mark}
+ onChange={(e) => setSkipMarkEnabled(markKey, e.target.checked)}
+ />
+ 本剧跳过
+ </label>
+ </div>
+
+ {segments.length === 0 ? (
+ <p className="mt-3 rounded-lg border border-dashed border-line px-3 py-3 text-xs leading-relaxed text-faint">
+ 尚未标记跳过片段。播放到目标位置后,用下方按钮记录,或使用快捷键:
+ Shift+I 片头结束 / Shift+O 片尾开始 / Shift+S · Shift+E 中段区间。
+ </p>
+ ) : (
+ <ul className="mt-3 space-y-2">
+ {segments.map((seg, i) => {
+ const isCurrent = currentKey === seg;
+ return (
+ <li
+ key={`${seg.type}:${seg.start}`}
+ className={cn(
+ 'rounded-lg border px-2.5 py-2 transition-colors',
+ isCurrent ? 'border-accent/60 bg-chip/60' : 'border-line/70'
+ )}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex min-w-0 items-center gap-1.5 text-xs">
+ <span
+ aria-hidden
+ className="inline-block h-2 w-2 shrink-0 rounded-sm"
+ style={{ backgroundColor: SEGMENT_COLORS[seg.type] }}
+ />
+ <span className="text-muted">[{SEGMENT_LABELS[seg.type]}]</span>
+ <span className="font-mono text-muted">
+ {formatTime(seg.start)} → {seg.type === 'ending' ? '结尾' : formatTime(seg.end)}
+ </span>
+ </span>
+ {isCurrent && <span className="shrink-0 text-[10px] text-accent">当前</span>}
+ </div>
+ <div className="mt-1.5 flex flex-wrap items-center gap-1">
+ <button
+ type="button"
+ className="btn-ghost btn-sm"
+ title="跳到片段起点,验证起点是否准确"
+ onClick={() => jump(seg, 'start')}
+ >
+ 起点
+ </button>
+ {seg.type !== 'ending' && (
+ <button
+ type="button"
+ className="btn-ghost btn-sm"
+ title="跳到终点前 1 秒,验证是否会切掉正片或漏掉一段"
+ onClick={() => jump(seg, 'end')}
+ >
+ 终点
+ </button>
+ )}
+ <button type="button" className="btn-ghost btn-sm" title="边界提前 1 秒" onClick={() => nudge(i, -1)}>
+ -1s
+ </button>
+ <button type="button" className="btn-ghost btn-sm" title="边界推后 1 秒" onClick={() => nudge(i, 1)}>
+ +1s
+ </button>
+ <button
+ type="button"
+ className="btn-ghost btn-sm"
+ title="删除(可在提示中撤销)"
+ onClick={() => remove(i)}
+ >
+ 删
+ </button>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+
+ <div className="mt-4 border-t border-line pt-3">
+ <p className="mb-1.5 text-[11px] text-faint">记录(会先暂停在当前画面)</p>
+ <div className="flex flex-wrap items-center gap-1.5">
+ <button
+ type="button"
+ className="btn-ghost btn-sm"
+ title="把当前画面记为片头结束位置"
+ onClick={() => recordAt('opening')}
+ >
+ 记为片头结束
+ </button>
+ <button
+ type="button"
+ className="btn-ghost btn-sm"
+ title="把当前画面记为片尾开始位置"
+ onClick={() => recordAt('ending')}
+ >
+ 记为片尾开始
+ </button>
+ {pendingStart === null ? (
+ <button type="button" className="btn-ghost btn-sm" onClick={markMiddleStart}>
+ 标记中段起点
+ </button>
+ ) : (
+ <>
+ <button type="button" className="btn-ghost btn-sm" onClick={markMiddleEnd}>
+ 标记中段终点(自 {formatTime(pendingStart)})
+ </button>
+ <button type="button" className="btn-ghost btn-sm" title="放弃这个起点" onClick={() => onPendingStart(null)}>
+ 取消
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* 全局开关:只读展示(层级与本剧开关不同,改起来去设置里更不容易误解) */}
+ <div className="mt-3 rounded-lg border border-line bg-surface px-3 py-2.5">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs text-muted">全局 · 自动跳过片段</span>
+ <span className={cn('text-xs font-medium', autoSkipSegments ? 'text-accent' : 'text-faint')}>
+ {autoSkipSegments ? '已开启' : '已关闭'}
+ </span>
+ </div>
+ <p className="mt-1 text-[11px] leading-relaxed text-faint">
+ {autoSkipSegments
+ ? '命中片头/中段自动跳段,片尾结束本集(是否连播看「自动连播」)。'
+ : '命中片段只显示按钮,不自动跳。'}
+ 影响所有剧,在「设置 → 偏好设置」修改。
+ </p>
+ </div>
+
+ <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-faint">
+ <span>进度条色带:</span>
+ {SEGMENT_TYPES.map((t) => (
+ <span key={t} className="inline-flex items-center gap-1">
+ <span
+ aria-hidden
+ className="inline-block h-2 w-2 rounded-sm"
+ style={{ backgroundColor: SEGMENT_COLORS[t] }}
+ />
+ {SEGMENT_LABELS[t]}
+ </span>
+ ))}
+ <span className="w-full">跳过时播放器顶部会出现「撤销」,可回退刚跳过的那一次。</span>
</div>
- <p className="mt-2.5 text-[11px] text-faint leading-relaxed">
- 标记按剧名记忆,对本剧所有剧集与同名资源生效;命中时播放器底部显示「跳过片头/片尾」按钮,
- 自动跳过可在「设置 → 播放与过滤」中关闭。
- </p>
- </div>
+ </Drawer>
);
}
diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsx
index f6a886e..79ab920 100644
--- a/src/components/source-manager.tsx
+++ b/src/components/source-manager.tsx
@@ -578,24 +578,18 @@ function PlaybackPanel() {
onChange={(v) => store.updateSettings({ autoplayNext: v })}
/>
<ToggleRow
- label="自动跳过片头"
- description="命中片头标记时自动跳到片头结束位置;关闭后仍显示「跳过片头」按钮(标记在播放页「片头片尾」中设置)"
- checked={store.autoSkipIntro}
- onChange={(v) => store.updateSettings({ autoSkipIntro: v })}
- />
- <ToggleRow
- label="自动跳过片尾"
- description="到达片尾标记时自动结束本集(开启自动连播则继续下一集);关闭后仍显示「跳过片尾」按钮"
- checked={store.autoSkipOutro}
- onChange={(v) => store.updateSettings({ autoSkipOutro: v })}
+ label="自动跳过片段"
+ description="命中片头/中段标记时跳到片段末尾,命中片尾标记时结束本集(是否连播下一集由「自动连播」决定);关闭后三类都只显示跳过按钮(标记在播放页「跳过标记」中设置)"
+ checked={store.autoSkipSegments}
+ onChange={(v) => store.updateSettings({ autoSkipSegments: v })}
/>
</div>
{markCount > 0 && (
<div className="flex items-center justify-between gap-3 pt-3 mt-3 border-t border-line">
<div className="min-w-0">
- <div className="text-sm text-content">片头片尾标记</div>
- <div className="text-xs text-faint">已记录 {markCount} 部;在播放页「片头片尾」中设置</div>
+ <div className="text-sm text-content">跳过片段标记</div>
+ <div className="text-xs text-faint">已记录 {markCount} 部;在播放页「跳过标记」中设置,可逐剧关闭</div>
</div>
<button className="btn-ghost btn-sm shrink-0" onClick={() => setClearMarksOpen(true)}>
清除全部
@@ -606,14 +600,14 @@ function PlaybackPanel() {
<ConfirmDialog
open={clearMarksOpen}
danger
- title="清除全部片头片尾标记?"
- message={`将删除已记录的 ${markCount} 部剧的片头片尾标记,之后播放不再自动跳过;可重新在播放页标记。`}
+ title="清除全部跳过片段?"
+ message={`将删除已记录的 ${markCount} 部剧的跳过片段,之后播放不再自动跳过;可重新在播放页标记。`}
confirmLabel="清除全部"
onCancel={() => setClearMarksOpen(false)}
onConfirm={() => {
store.clearAllSkipMarks();
setClearMarksOpen(false);
- toast('已清除全部片头片尾标记', 'success');
+ toast('已清除全部跳过片段标记', 'success');
}}
/>
diff --git a/src/lib/skip-marks.test.ts b/src/lib/skip-marks.test.ts
index a8e1f4b..b8e6e41 100644
--- a/src/lib/skip-marks.test.ts
+++ b/src/lib/skip-marks.test.ts
@@ -1,21 +1,18 @@
import { describe, expect, it } from 'vitest';
import {
MAX_CONTINUOUS_STEP_SECONDS,
- MIN_MARK_GAP_SECONDS,
- hasCrossedOutro,
- isIntroActive,
- resolveSkipWindow,
+ MIN_SEGMENT_GAP_SECONDS,
+ findActiveSegment,
+ findCrossedEnding,
+ migrateSkipMarks,
+ resolveSegments,
skipMarkKey,
- validateIntroEnd,
- validateOutroStart,
+ validateSegment,
type SkipMark,
+ type SkipSegment,
} from './skip-marks';
-const mark = (introEnd?: number, outroStart?: number): SkipMark => ({
- introEnd,
- outroStart,
- updatedAt: 0,
-});
+const mark = (...segments: SkipSegment[]): SkipMark => ({ segments, enabled: true, updatedAt: 0 });
describe('skipMarkKey', () => {
it('空白、标点、大小写归一后指向同一个标记', () => {
@@ -38,116 +35,209 @@ describe('skipMarkKey', () => {
});
});
-describe('resolveSkipWindow', () => {
- it('合法标记原样返回', () => {
- expect(resolveSkipWindow(mark(45, 1200), 2400)).toEqual({ introEnd: 45, outroStart: 1200 });
+describe('migrateSkipMarks', () => {
+ it('v3 的片头/片尾双标记转成 opening + ending', () => {
+ const result = migrateSkipMarks({
+ 't:abc': { introEnd: 45, outroStart: 1200, updatedAt: 111 },
+ });
+ expect(result['t:abc']).toEqual({
+ segments: [
+ { type: 'opening', start: 0, end: 45 },
+ { type: 'ending', start: 1200, end: -1 },
+ ],
+ enabled: true,
+ updatedAt: 111,
+ });
+ });
+
+ it('只有单边字段时只生成对应片段', () => {
+ expect(migrateSkipMarks({ 't:a': { introEnd: 45, updatedAt: 1 } })['t:a']?.segments).toEqual([
+ { type: 'opening', start: 0, end: 45 },
+ ]);
+ expect(migrateSkipMarks({ 't:b': { outroStart: 1200, updatedAt: 1 } })['t:b']?.segments).toEqual([
+ { type: 'ending', start: 1200, end: -1 },
+ ]);
});
- it('无标记、时长缺失或非有限时返回空窗口', () => {
- expect(resolveSkipWindow(undefined, 2400)).toEqual({});
- expect(resolveSkipWindow(mark(45, 1200), 0)).toEqual({});
- expect(resolveSkipWindow(mark(45, 1200), Number.NaN)).toEqual({});
- expect(resolveSkipWindow(mark(45, 1200), Number.POSITIVE_INFINITY)).toEqual({});
+ it('已是 segments 结构直接保留', () => {
+ const segments = [{ type: 'middle', start: 100, end: 200 }] as SkipSegment[];
+ expect(migrateSkipMarks({ 't:x': { segments, updatedAt: 2 } })['t:x']).toEqual({
+ segments,
+ enabled: true,
+ updatedAt: 2,
+ });
});
- it('越界/过小的字段被逐项剔除', () => {
- // 片头 >= 总时长 - 2、片尾 >= 总时长 - 2、片头 < 3、片尾 < 5
- expect(resolveSkipWindow(mark(2399), 2400)).toEqual({});
- expect(resolveSkipWindow(mark(undefined, 2399), 2400)).toEqual({});
- expect(resolveSkipWindow(mark(2), 2400)).toEqual({});
- expect(resolveSkipWindow(mark(undefined, 4), 2400)).toEqual({});
+ it('缺省 enabled 视为开启,显式 false 时保留', () => {
+ expect(migrateSkipMarks({ 't:a': { introEnd: 20 } })['t:a']?.enabled).toBe(true);
+ expect(
+ migrateSkipMarks({ 't:b': { segments: [], enabled: false, updatedAt: 1 } })['t:b']?.enabled
+ ).toBe(false);
});
- it('片头与片尾间隔不足时保留片头、丢弃片尾', () => {
- expect(resolveSkipWindow(mark(45, 45 + MIN_MARK_GAP_SECONDS - 1), 2400)).toEqual({ introEnd: 45 });
- expect(resolveSkipWindow(mark(45, 45 + MIN_MARK_GAP_SECONDS), 2400)).toEqual({
- introEnd: 45,
- outroStart: 45 + MIN_MARK_GAP_SECONDS,
+ it('损坏条目丢弃,其余正常迁移', () => {
+ const result = migrateSkipMarks({
+ bad1: null,
+ bad2: 'oops',
+ bad3: 123,
+ good: { introEnd: 30, updatedAt: 5 },
+ });
+ expect(Object.keys(result)).toEqual(['good']);
+ expect(result.good?.segments).toEqual([{ type: 'opening', start: 0, end: 30 }]);
+ });
+
+ it('非对象输入返回空对象', () => {
+ expect(migrateSkipMarks(undefined)).toEqual({});
+ expect(migrateSkipMarks(null)).toEqual({});
+ expect(migrateSkipMarks([])).toEqual({});
+ expect(migrateSkipMarks('x')).toEqual({});
+ });
+
+ it('segments 里的损坏条目逐条剔除(面板会直接渲染原始列表)', () => {
+ const result = migrateSkipMarks({
+ 't:a': {
+ segments: [
+ { type: 'middle', start: 100, end: 200 },
+ { type: 'unknown', start: 1, end: 2 },
+ { type: 'opening', start: 0, end: Number.NaN },
+ null,
+ 'x',
+ ],
+ updatedAt: 1,
+ },
});
+ expect(result['t:a']?.segments).toEqual([{ type: 'middle', start: 100, end: 200 }]);
});
- it('损坏的持久化数据(负数/NaN)不会抛错', () => {
- expect(resolveSkipWindow(mark(-5, Number.NaN), 2400)).toEqual({});
+ it('缺失 updatedAt 时补当前时间', () => {
+ expect(migrateSkipMarks({ 't:a': { introEnd: 20 } })['t:a']?.updatedAt).toBeGreaterThan(0);
});
});
-describe('isIntroActive', () => {
- const window = { introEnd: 45 };
-
- it('片头区间内为真,收尾余量内为假', () => {
- expect(isIntroActive(0, window)).toBe(true);
- expect(isIntroActive(43.5, window)).toBe(true);
- expect(isIntroActive(44.5, window)).toBe(false);
- expect(isIntroActive(45, window)).toBe(false);
- expect(isIntroActive(46, window)).toBe(false);
+describe('resolveSegments', () => {
+ it('合法片段按 start 升序返回,ending 的 end 用时长填充', () => {
+ expect(
+ resolveSegments(
+ mark(
+ { type: 'ending', start: 1200, end: -1 },
+ { type: 'opening', start: 0, end: 45 },
+ { type: 'middle', start: 500, end: 530 }
+ ),
+ 2400
+ )
+ ).toEqual([
+ { type: 'opening', start: 0, end: 45 },
+ { type: 'middle', start: 500, end: 530 },
+ { type: 'ending', start: 1200, end: 2400 },
+ ]);
+ });
+
+ it('空标记、时长缺失或非法时返回空列表', () => {
+ expect(resolveSegments(undefined, 2400)).toEqual([]);
+ expect(resolveSegments(mark(), 0)).toEqual([]);
+ expect(resolveSegments(mark(), Number.NaN)).toEqual([]);
+ });
+
+ it('本剧总开关关闭时一律返回空列表(标记保留但不生效)', () => {
+ expect(
+ resolveSegments({ ...mark({ type: 'opening', start: 0, end: 45 }), enabled: false }, 2400)
+ ).toEqual([]);
});
- it('没有片头标记或位置非法时为假', () => {
- expect(isIntroActive(10, {})).toBe(false);
- expect(isIntroActive(Number.NaN, window)).toBe(false);
- expect(isIntroActive(-1, window)).toBe(false);
+ it('越界/过短的片段被逐项剔除', () => {
+ // 片头 < 3s
+ expect(resolveSegments(mark({ type: 'opening', start: 0, end: 2 }), 2400)).toEqual([]);
+ // 片尾贴结尾
+ expect(resolveSegments(mark({ type: 'ending', start: 2399, end: -1 }), 2400)).toEqual([]);
+ // 中段终点贴结尾
+ expect(resolveSegments(mark({ type: 'middle', start: 2300, end: 2400 }), 2400)).toEqual([]);
});
-});
-describe('hasCrossedOutro', () => {
- const window = { outroStart: 1200 };
-
- it('连续小步前进越过片尾起点才触发', () => {
- expect(hasCrossedOutro(1199.5, 1200.25, window)).toBe(true);
- expect(hasCrossedOutro(1200.2, 1201, window)).toBe(false); // 已经越过
- expect(hasCrossedOutro(1199.5, 1199.9, window)).toBe(false); // 尚未到达
- expect(hasCrossedOutro(1201, 1200.5, window)).toBe(false); // 倒退
+ it('重叠或过近时保留靠前者、丢弃后者', () => {
+ const a: SkipSegment = { type: 'middle', start: 100, end: 200 };
+ const b: SkipSegment = { type: 'middle', start: 100 + MIN_SEGMENT_GAP_SECONDS - 1, end: 300 };
+ expect(resolveSegments(mark(a, b), 2400)).toEqual([{ ...a }]);
});
- it('大跨度拖动/进度恢复不触发自动跳', () => {
- expect(hasCrossedOutro(0, 1300, window)).toBe(false);
- expect(hasCrossedOutro(1190, 1200 + MAX_CONTINUOUS_STEP_SECONDS, window)).toBe(false);
+ it('损坏的持久化数据(负数/NaN/类型不对)不会抛错', () => {
expect(
- hasCrossedOutro(1200 - MAX_CONTINUOUS_STEP_SECONDS / 2, 1200 + MAX_CONTINUOUS_STEP_SECONDS / 2, window)
- ).toBe(true);
+ resolveSegments(
+ {
+ segments: [{ type: 'middle', start: -5, end: Number.NaN } as unknown as SkipSegment],
+ enabled: true,
+ updatedAt: 0,
+ },
+ 2400
+ )
+ ).toEqual([]);
+ });
+});
+
+describe('findActiveSegment', () => {
+ const segments = resolveSegments(mark({ type: 'opening', start: 0, end: 45 }), 2400);
+
+ it('区间内命中,收尾余量内不命中', () => {
+ expect(findActiveSegment(segments, 0)?.type).toBe('opening');
+ expect(findActiveSegment(segments, 43.5)?.type).toBe('opening');
+ expect(findActiveSegment(segments, 44.5)).toBeUndefined(); // 距末尾 0.5s
+ expect(findActiveSegment(segments, 45)).toBeUndefined();
});
- it('没有片尾标记或时间非法时为假', () => {
- expect(hasCrossedOutro(1199, 1201, {})).toBe(false);
- expect(hasCrossedOutro(Number.NaN, 1201, window)).toBe(false);
- expect(hasCrossedOutro(1199, Number.NaN, window)).toBe(false);
+ it('非法位置或空列表返回 undefined', () => {
+ expect(findActiveSegment(segments, Number.NaN)).toBeUndefined();
+ expect(findActiveSegment([], 10)).toBeUndefined();
});
});
-describe('validateIntroEnd', () => {
- it('接受合理值', () => {
- expect(validateIntroEnd(30, 2400)).toBeNull();
- expect(validateIntroEnd(MIN_MARK_GAP_SECONDS, 0, mark(undefined, MIN_MARK_GAP_SECONDS * 2))).toBeNull();
+describe('findCrossedEnding', () => {
+ const segments = resolveSegments(mark({ type: 'ending', start: 1200, end: -1 }), 2400);
+
+ it('连续小步前进越过片尾起点才触发', () => {
+ expect(findCrossedEnding(segments, 1199.5, 1200.25)).toBe(true);
+ expect(findCrossedEnding(segments, 1200.2, 1201)).toBe(false); // 已经越过
+ expect(findCrossedEnding(segments, 1199.5, 1199.9)).toBe(false); // 尚未到达
+ expect(findCrossedEnding(segments, 1201, 1200.5)).toBe(false); // 倒退
});
- it('拒绝过早、非法与贴近结尾的值', () => {
- expect(validateIntroEnd(Number.NaN, 2400)).not.toBeNull();
- expect(validateIntroEnd(0, 2400)).not.toBeNull();
- expect(validateIntroEnd(2, 2400)).not.toBeNull();
- expect(validateIntroEnd(2399, 2400)).not.toBeNull();
+ it('大跨度拖动/进度恢复不触发自动结束', () => {
+ expect(findCrossedEnding(segments, 0, 1300)).toBe(false);
+ expect(findCrossedEnding(segments, 1190, 1200 + MAX_CONTINUOUS_STEP_SECONDS)).toBe(false);
});
- it('与已有片尾标记间隔不足时拒绝', () => {
- expect(validateIntroEnd(30, 2400, mark(undefined, 35))).toContain(String(MIN_MARK_GAP_SECONDS));
- expect(validateIntroEnd(25, 2400, mark(undefined, 35))).toBeNull();
+ it('无结尾片段或时间非法时为假', () => {
+ const noEnding = resolveSegments(mark({ type: 'opening', start: 0, end: 45 }), 2400);
+ expect(findCrossedEnding(noEnding, 1199, 1201)).toBe(false);
+ expect(findCrossedEnding(segments, Number.NaN, 1201)).toBe(false);
});
});
-describe('validateOutroStart', () => {
- it('接受合理值', () => {
- expect(validateOutroStart(1200, 2400)).toBeNull();
- expect(validateOutroStart(MIN_MARK_GAP_SECONDS + 5, 0, mark(5))).toBeNull();
+describe('validateSegment', () => {
+ it('接受合理的片头/片尾/中段', () => {
+ expect(validateSegment({ type: 'opening', start: 0, end: 30 }, 2400)).toBeNull();
+ expect(validateSegment({ type: 'ending', start: 1200, end: -1 }, 2400)).toBeNull();
+ expect(validateSegment({ type: 'middle', start: 500, end: 530 }, 2400)).toBeNull();
+ });
+
+ it('拒绝过短、非法与贴结尾的片段', () => {
+ expect(validateSegment({ type: 'opening', start: 0, end: 2 }, 2400)).not.toBeNull();
+ expect(validateSegment({ type: 'middle', start: 500, end: 501 }, 2400)).not.toBeNull();
+ expect(validateSegment({ type: 'middle', start: Number.NaN, end: 500 }, 2400)).not.toBeNull();
+ expect(validateSegment({ type: 'ending', start: 2399, end: -1 }, 2400)).not.toBeNull();
});
- it('拒绝过早、非法与贴近结尾的值', () => {
- expect(validateOutroStart(Number.NaN, 2400)).not.toBeNull();
- expect(validateOutroStart(0, 2400)).not.toBeNull();
- expect(validateOutroStart(4, 2400)).not.toBeNull();
- expect(validateOutroStart(2399, 2400)).not.toBeNull();
+ it('opening 起点必须为 0,ending 无需指定终点', () => {
+ expect(validateSegment({ type: 'opening', start: 5, end: 30 }, 2400)).not.toBeNull();
+ expect(validateSegment({ type: 'ending', start: 1200, end: 1300 }, 2400)).not.toBeNull();
});
- it('与已有片头标记间隔不足时拒绝', () => {
- expect(validateOutroStart(35, 2400, mark(30))).toContain(String(MIN_MARK_GAP_SECONDS));
- expect(validateOutroStart(40, 2400, mark(30))).toBeNull();
+ it('与已有片段重叠或过近时拒绝,刚好够间隔时接受', () => {
+ const existing = [{ type: 'middle', start: 500, end: 530 } as SkipSegment];
+ expect(validateSegment({ type: 'middle', start: 520, end: 560 }, 2400, existing)).not.toBeNull();
+ expect(
+ validateSegment({ type: 'middle', start: 530 + MIN_SEGMENT_GAP_SECONDS - 1, end: 600 }, 2400, existing)
+ ).not.toBeNull();
+ expect(
+ validateSegment({ type: 'middle', start: 530 + MIN_SEGMENT_GAP_SECONDS, end: 600 }, 2400, existing)
+ ).toBeNull();
});
});
diff --git a/src/lib/skip-marks.ts b/src/lib/skip-marks.ts
index b4f12ce..0e1e300 100644
--- a/src/lib/skip-marks.ts
+++ b/src/lib/skip-marks.ts
@@ -1,47 +1,76 @@
import { normalizeTitle } from './cms-parser';
/**
- * 片头/片尾跳过:标记的归一化、校验与「当前是否命中」判定。
+ * 跳过片段:标记的归一化、校验与「当前是否命中」判定。
*
* 采集站的详情接口不提供片头片尾元数据(vod_play_url 只有分集地址),
* 因此边界只能由用户手动标记一次、按剧名记住,后续各集与同名资源自动套用。
+ *
+ * 相比固定的「片头/片尾」两个标记,这里泛化为任意数量的跳过片段(SkipSegment),
+ * 每个片段用位置归类:opening(开头/片头)、middle(中间)、ending(结尾/片尾)。
* 本模块只做纯计算,播放器接入与 UI 见 player-shell.tsx / skip-mark-panel.tsx。
*/
-/** 一条剧的跳过标记;时间单位为秒(播放时间轴,与广告过滤后的时间轴一致) */
+/** 片段位置类型:开头 / 中间 / 结尾 */
+export type SkipSegmentType = 'opening' | 'middle' | 'ending';
+
+/** 一条跳过片段;时间单位为秒(播放时间轴,与广告过滤后的时间轴一致) */
+export interface SkipSegment {
+ type: SkipSegmentType;
+ /** 片段起点;opening 恒为 0 */
+ start: number;
+ /** 片段终点;ending 用 -1 表示「到视频结尾」,运行时以实际时长填充 */
+ end: number;
+}
+
+/** 一部剧的跳过标记;按归一化剧名持久化 */
export interface SkipMark {
- /** 片头结束位置(正片开始) */
- introEnd?: number;
- /** 片尾开始位置(正片结束、片尾曲开始) */
- outroStart?: number;
+ segments: SkipSegment[];
+ /** 本剧总开关:关掉后保留标记但完全不生效(误标时不必删掉重标) */
+ enabled: boolean;
/** 最近一次修改时间(epoch ms),便于后续做清理/展示 */
updatedAt: number;
}
-/** 某集经过时长校验后的有效跳过窗口;非法字段会被剔除 */
-export interface SkipWindow {
- introEnd?: number;
- outroStart?: number;
+/** 三类片段在进度条色带与图例中的颜色(player-shell / skip-mark-panel 共用) */
+export const SEGMENT_COLORS: Record<SkipSegmentType, string> = {
+ opening: 'rgba(37,99,235,0.45)',
+ middle: 'rgba(148,163,184,0.45)',
+ ending: 'rgba(249,115,22,0.45)',
+};
+
+/** 三类片段的展示名(面板列表 / 进度条 tooltip 共用) */
+export const SEGMENT_LABELS: Record<SkipSegmentType, string> = {
+ opening: '片头',
+ middle: '中段',
+ ending: '片尾',
+};
+
+/** 某集经过时长校验后的有效片段;ending 的 end 已填充为实际时长 */
+export interface ResolvedSegment {
+ type: SkipSegmentType;
+ start: number;
+ end: number;
}
-/** 片头结束与片尾开始之间至少保留的正片时长:贴太近说明两个标记至少有一个错了 */
-export const MIN_MARK_GAP_SECONDS = 10;
-/** 片头结束的合法下限:刚起播时误点不会写入无意义标记 */
-export const MIN_INTRO_SECONDS = 3;
-/** 片尾开始的合法下限 */
-export const MIN_OUTRO_SECONDS = 5;
-/** 标记至少要比总时长提前的秒数,贴着结尾的标记没有跳过价值 */
+/** 跳过片段的最短时长:比这更短的区间没有跳过价值 */
+export const MIN_SEGMENT_SECONDS = 3;
+/** 相邻片段之间的最小间隔:贴太近说明某个标记错了 */
+export const MIN_SEGMENT_GAP_SECONDS = 5;
+/** 片段终点(ending 为起点)至少要比总时长提前的秒数,贴着结尾的片段没有跳过价值 */
export const END_GUARD_SECONDS = 2;
-/** 片头提示的收尾余量:距片头结束不足 1s 时不再打扰 */
-export const INTRO_PROMPT_GUARD_SECONDS = 1;
+/** 命中提示的收尾余量:距片段末尾不足 1s 时不再打扰 */
+export const PROMPT_GUARD_SECONDS = 1;
/** 两次 timeupdate 之间超过该秒数视为 seek,不使用「连续越过」判定 */
export const MAX_CONTINUOUS_STEP_SECONDS = 10;
-/** 播放页在拿不到真实标题时使用的占位文案(与 watch/page.tsx 保持一致) */
-const UNKNOWN_TITLE = '未知视频';
+/** 播放页在拿不到真实标题时使用的占位文案(watch/page.tsx 复用,避免双处硬编码) */
+export const UNKNOWN_TITLE = '未知视频';
+
+const SEGMENT_TYPES: ReadonlySet<string> = new Set<SkipSegmentType>(['opening', 'middle', 'ending']);
-function isValidTime(value: unknown): value is number {
- return typeof value === 'number' && Number.isFinite(value) && value > 0;
+function isFiniteNumber(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value);
}
/**
@@ -59,83 +88,177 @@ export function skipMarkKey(title: string | undefined, fallback: string): string
}
/**
- * 把持久化标记裁剪成当前这集可用的窗口。
+ * 把持久化快照里的 skipMarks 归一化为当前结构(persist v3 → v4)。
+ * - 已是 segments 结构的直接保留(按结构探测,兼容后续再升级);
+ * - 旧的 { introEnd, outroStart } 转成 opening + ending 两条;
+ * - 损坏条目(null/非对象)直接丢弃,绝不能让恢复过程抛错。
+ */
+export function migrateSkipMarks(raw: unknown): Record<string, SkipMark> {
+ const result: Record<string, SkipMark> = {};
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return result;
+
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
+ if (!value || typeof value !== 'object') continue;
+ const mark = value as {
+ segments?: unknown;
+ enabled?: unknown;
+ introEnd?: unknown;
+ outroStart?: unknown;
+ updatedAt?: unknown;
+ };
+ const updatedAt = typeof mark.updatedAt === 'number' ? mark.updatedAt : Date.now();
+ // 缺省视为开启:v4 及更早的快照没有这个字段
+ const enabled = mark.enabled !== false;
+
+ if (Array.isArray(mark.segments)) {
+ // 逐条校验结构:面板直接渲染 segments,损坏条目会显示成 NaN:NaN
+ const valid = (mark.segments as unknown[]).flatMap((s): SkipSegment[] => {
+ if (!s || typeof s !== 'object') return [];
+ const seg = s as { type?: unknown; start?: unknown; end?: unknown };
+ if (typeof seg.type !== 'string' || !SEGMENT_TYPES.has(seg.type)) return [];
+ if (!isFiniteNumber(seg.start) || !isFiniteNumber(seg.end)) return [];
+ return [{ type: seg.type as SkipSegmentType, start: seg.start, end: seg.end }];
+ });
+ result[key] = { segments: valid, enabled, updatedAt };
+ continue;
+ }
+
+ const segments: SkipSegment[] = [];
+ if (typeof mark.introEnd === 'number' && mark.introEnd > 0) {
+ segments.push({ type: 'opening', start: 0, end: mark.introEnd });
+ }
+ if (typeof mark.outroStart === 'number' && mark.outroStart > 0) {
+ segments.push({ type: 'ending', start: mark.outroStart, end: -1 });
+ }
+ result[key] = { segments, enabled, updatedAt };
+ }
+ return result;
+}
+
+/**
+ * 把一条原始片段归一化成当前这集的有效区间;非法/越界/损坏时返回 null。
*
* 必须是「读取侧」校验:标记按剧共享,不同集/不同源的时长可能不同,
* 旧标记完全可能越界;损坏的持久化数据也不应让播放报错。
- * 片头与片尾冲突(间隔不足)时保留片头、丢弃片尾——片头通常更早也更稳定。
*/
-export function resolveSkipWindow(mark: SkipMark | undefined, duration: number): SkipWindow {
- if (!mark || !Number.isFinite(duration) || duration <= 0) return {};
-
- const introEnd =
- isValidTime(mark.introEnd) &&
- mark.introEnd >= MIN_INTRO_SECONDS &&
- mark.introEnd <= duration - END_GUARD_SECONDS
- ? mark.introEnd
- : undefined;
-
- let outroStart =
- isValidTime(mark.outroStart) &&
- mark.outroStart >= MIN_OUTRO_SECONDS &&
- mark.outroStart <= duration - END_GUARD_SECONDS
- ? mark.outroStart
- : undefined;
-
- if (introEnd !== undefined && outroStart !== undefined && outroStart - introEnd < MIN_MARK_GAP_SECONDS) {
- outroStart = undefined;
+function normalizeSegment(seg: SkipSegment | undefined, duration: number): ResolvedSegment | null {
+ if (!seg || !SEGMENT_TYPES.has(seg.type)) return null;
+ if (!isFiniteNumber(seg.start) || seg.start < 0) return null;
+
+ const start = seg.type === 'opening' ? 0 : seg.start;
+ const end = seg.type === 'ending' ? duration : seg.end;
+
+ if (!isFiniteNumber(end)) return null;
+ if (end <= start) return null;
+ if (end - start < MIN_SEGMENT_SECONDS) return null;
+
+ if (seg.type === 'ending') {
+ if (start > duration - END_GUARD_SECONDS) return null;
+ } else if (end > duration - END_GUARD_SECONDS) {
+ return null;
+ }
+
+ return { type: seg.type, start, end };
+}
+
+/**
+ * 把持久化标记裁剪成当前这集可用的片段列表(按 start 升序、无重叠)。
+ * ending 的 end 用实际时长填充;重叠或过近的片段保留靠前者、丢弃后者。
+ */
+export function resolveSegments(mark: SkipMark | undefined, duration: number): ResolvedSegment[] {
+ if (!mark || !Array.isArray(mark.segments) || !isFiniteNumber(duration) || duration <= 0) return [];
+ // 本剧总开关关闭:保留标记但一格都不生效(缺省视为开启,兼容旧快照)
+ if (mark.enabled === false) return [];
+
+ const resolved: ResolvedSegment[] = [];
+ for (const seg of mark.segments) {
+ const r = normalizeSegment(seg, duration);
+ if (r) resolved.push(r);
}
+ resolved.sort((a, b) => a.start - b.start);
- return {
- ...(introEnd !== undefined ? { introEnd } : {}),
- ...(outroStart !== undefined ? { outroStart } : {}),
- };
+ const result: ResolvedSegment[] = [];
+ for (const seg of resolved) {
+ const last = result[result.length - 1];
+ if (last && seg.start - last.end < MIN_SEGMENT_GAP_SECONDS) continue;
+ result.push(seg);
+ }
+ return result;
}
-/** 当前是否仍处于片头(用于显示「跳过片头」按钮) */
-export function isIntroActive(position: number, window: SkipWindow): boolean {
- const { introEnd } = window;
- if (introEnd === undefined || !Number.isFinite(position)) return false;
- return position >= 0 && position < introEnd - INTRO_PROMPT_GUARD_SECONDS;
+/** 当前位置是否落在某个跳过片段内(用于显示「跳过」按钮与自动跳转) */
+export function findActiveSegment(
+ segments: ResolvedSegment[],
+ position: number
+): ResolvedSegment | undefined {
+ if (!isFiniteNumber(position)) return undefined;
+ return segments.find((s) => position >= s.start && position < s.end - PROMPT_GUARD_SECONDS);
}
/**
- * 是否在连续播放中越过了片尾起点。
+ * 是否在连续播放中越过了「结尾」片段的起点。
* 只认小步前进:用户拖动进度条、刚写入标记、以及进度恢复造成的大跳变
* 都不应触发自动结束;这些场景仍会显示按钮,由用户自己决定。
*/
-export function hasCrossedOutro(previous: number, current: number, window: SkipWindow): boolean {
- const { outroStart } = window;
- if (outroStart === undefined) return false;
- if (!Number.isFinite(previous) || !Number.isFinite(current)) return false;
+export function findCrossedEnding(
+ segments: ResolvedSegment[],
+ previous: number,
+ current: number
+): boolean {
+ if (!isFiniteNumber(previous) || !isFiniteNumber(current)) return false;
const step = current - previous;
- return previous < outroStart && current >= outroStart && step > 0 && step <= MAX_CONTINUOUS_STEP_SECONDS;
+ if (!(step > 0 && step <= MAX_CONTINUOUS_STEP_SECONDS)) return false;
+ return segments.some((s) => s.type === 'ending' && previous < s.start && current >= s.start);
}
-/** 校验「片头结束」;duration 未知(<=0)时只做相对校验。返回错误文案或 null */
-export function validateIntroEnd(value: number, duration: number, mark?: SkipMark): string | null {
- if (!isValidTime(value)) return '片头结束时间无效';
- if (value < MIN_INTRO_SECONDS) return '请播放几秒后再记录片头结束';
- if (Number.isFinite(duration) && duration > 0 && value > duration - END_GUARD_SECONDS) {
- return '片头结束不能接近视频末尾';
- }
- const outroStart = mark?.outroStart;
- if (isValidTime(outroStart) && value > outroStart - MIN_MARK_GAP_SECONDS) {
- return `片头结束需早于片尾开始至少 ${MIN_MARK_GAP_SECONDS} 秒`;
+/**
+ * 校验一条待写入的片段;duration 未知(<=0)时只做相对校验。返回错误文案或 null。
+ * existing 为当前已保存的片段(不含待写入这条)。
+ */
+export function validateSegment(
+ segment: SkipSegment,
+ duration: number,
+ existing: SkipSegment[] = []
+): string | null {
+ if (!segment || !SEGMENT_TYPES.has(segment.type)) return '片段类型无效';
+ if (!isFiniteNumber(segment.start) || segment.start < 0) return '片段起点无效';
+ if (segment.type === 'opening' && segment.start !== 0) return '片头片段起点必须为 0';
+
+ const start = segment.start;
+ let end: number;
+ if (segment.type === 'ending') {
+ if (segment.end !== -1) return '片尾片段无需指定终点';
+ end = isFiniteNumber(duration) && duration > 0 ? duration : Number.POSITIVE_INFINITY;
+ } else {
+ if (!isFiniteNumber(segment.end)) return '片段终点无效';
+ end = segment.end;
}
- return null;
-}
-/** 校验「片尾开始」;规则与 validateIntroEnd 对称 */
-export function validateOutroStart(value: number, duration: number, mark?: SkipMark): string | null {
- if (!isValidTime(value)) return '片尾开始时间无效';
- if (value < MIN_OUTRO_SECONDS) return '请播放到片尾附近再记录片尾开始';
- if (Number.isFinite(duration) && duration > 0 && value > duration - END_GUARD_SECONDS) {
- return '片尾开始需早于视频结束';
+ if (end - start < MIN_SEGMENT_SECONDS) {
+ return `跳过片段至少需要 ${MIN_SEGMENT_SECONDS} 秒`;
}
- const introEnd = mark?.introEnd;
- if (isValidTime(introEnd) && value < introEnd + MIN_MARK_GAP_SECONDS) {
- return `片尾开始需晚于片头结束至少 ${MIN_MARK_GAP_SECONDS} 秒`;
+ if (isFiniteNumber(duration) && duration > 0) {
+ if (segment.type === 'ending') {
+ if (start > duration - END_GUARD_SECONDS) return '片尾开始不能贴近视频末尾';
+ } else if (end > duration - END_GUARD_SECONDS) {
+ return '片段终点不能贴近视频末尾';
+ }
+ }
+
+ for (const other of existing) {
+ if (!other || !SEGMENT_TYPES.has(other.type)) continue;
+ const oStart = other.start;
+ let oEnd: number;
+ if (other.type === 'ending') {
+ oEnd = isFiniteNumber(duration) && duration > 0 ? duration : Number.POSITIVE_INFINITY;
+ } else {
+ oEnd = isFiniteNumber(other.end) ? other.end : other.start;
+ }
+ // 与已有片段的重叠/间隔判定:gap <= 0 为重叠,0 < gap < MIN_GAP 为过近
+ const gap = Math.max(oStart - end, start - oEnd);
+ if (gap < MIN_SEGMENT_GAP_SECONDS) {
+ return gap <= 0 ? '片段与已有片段重叠' : `片段之间至少间隔 ${MIN_SEGMENT_GAP_SECONDS} 秒`;
+ }
}
return null;
}
diff --git a/src/lib/store.test.ts b/src/lib/store.test.ts
index 5ecd799..b56f908 100644
--- a/src/lib/store.test.ts
+++ b/src/lib/store.test.ts
@@ -392,41 +392,54 @@ describe('订阅整体开关', () => {
});
});
-describe('片头片尾标记', () => {
+describe('跳过片段标记', () => {
beforeEach(() => {
useAppStore.setState({ skipMarks: {} });
});
- it('写入、合并字段并刷新 updatedAt', () => {
- store().setSkipMark('t:abc', { introEnd: 45 });
- expect(store().skipMarks['t:abc']?.introEnd).toBe(45);
+ it('写入片段列表并刷新 updatedAt', () => {
+ store().setSkipMark('t:abc', [{ type: 'opening', start: 0, end: 45 }]);
+ expect(store().skipMarks['t:abc']?.segments).toEqual([{ type: 'opening', start: 0, end: 45 }]);
const firstUpdatedAt = store().skipMarks['t:abc']?.updatedAt ?? 0;
expect(firstUpdatedAt).toBeGreaterThan(0);
- store().setSkipMark('t:abc', { outroStart: 1200 });
- expect(store().skipMarks['t:abc']).toMatchObject({ introEnd: 45, outroStart: 1200 });
+ store().setSkipMark('t:abc', [
+ { type: 'opening', start: 0, end: 45 },
+ { type: 'ending', start: 1200, end: -1 },
+ ]);
+ expect(store().skipMarks['t:abc']?.segments).toHaveLength(2);
expect(store().skipMarks['t:abc']?.updatedAt).toBeGreaterThanOrEqual(firstUpdatedAt);
});
- it('字段传 null 只清该字段,两个字段都清后删除整条', () => {
- store().setSkipMark('t:abc', { introEnd: 45, outroStart: 1200 });
+ it('写入空数组删除整条,不创建空壳条目', () => {
+ store().setSkipMark('t:abc', [{ type: 'opening', start: 0, end: 45 }]);
+ store().setSkipMark('t:abc', []);
+ expect(store().skipMarks['t:abc']).toBeUndefined();
- store().setSkipMark('t:abc', { introEnd: null });
- expect(store().skipMarks['t:abc']?.introEnd).toBeUndefined();
- expect(store().skipMarks['t:abc']?.outroStart).toBe(1200);
+ store().setSkipMark('t:missing', []);
+ expect(store().skipMarks).toEqual({});
+ });
- store().setSkipMark('t:abc', { outroStart: null });
- expect(store().skipMarks['t:abc']).toBeUndefined();
+ it('写入时默认开启本剧跳过,改片段不会重置已关闭状态', () => {
+ store().setSkipMark('t:abc', [{ type: 'opening', start: 0, end: 45 }]);
+ expect(store().skipMarks['t:abc']?.enabled).toBe(true);
+
+ store().setSkipMarkEnabled('t:abc', false);
+ expect(store().skipMarks['t:abc']?.enabled).toBe(false);
+
+ // 修一条标错的边界后,用户"关掉本剧"的选择要保留
+ store().setSkipMark('t:abc', [{ type: 'opening', start: 0, end: 30 }]);
+ expect(store().skipMarks['t:abc']?.enabled).toBe(false);
});
- it('对不存在的键写入空 patch 不会创建空壳条目', () => {
- store().setSkipMark('t:missing', { introEnd: null });
+ it('setSkipMarkEnabled 对不存在的条目无副作用', () => {
+ store().setSkipMarkEnabled('t:missing', false);
expect(store().skipMarks).toEqual({});
});
it('clearSkipMark 只删指定条目,clearAllSkipMarks 清空全部', () => {
- store().setSkipMark('t:a', { introEnd: 20 });
- store().setSkipMark('t:b', { outroStart: 200 });
+ store().setSkipMark('t:a', [{ type: 'opening', start: 0, end: 20 }]);
+ store().setSkipMark('t:b', [{ type: 'ending', start: 200, end: -1 }]);
store().clearSkipMark('t:a');
expect(store().skipMarks).not.toHaveProperty('t:a');
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 5a77c38..055eab5 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -3,7 +3,7 @@
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import type { QualityEntry, SourceConfig, LiveSourceConfig, SourceSearchOutcome } from './types';
-import type { SkipMark } from './skip-marks';
+import { migrateSkipMarks, type SkipMark, type SkipSegment } from './skip-marks';
import { isQualityEntryFresh, mergeQualityEntries, qualityKey } from './quality';
import { clearLiveProbeResultsDb, loadLiveProbeResults, saveLiveProbeResults } from './db';
import { PERSIST_KEY, createThrottledStorage } from './persist-storage';
@@ -24,12 +24,13 @@ export interface AppSettings {
/** 用户是否在设置中主动选择过推荐数据源;为 false 时部署者的 DEFAULT_RECOMMEND_SOURCE 默认值可生效 */
recommendSourceTouched: boolean;
autoplayNext: boolean;
- /** 片头/片尾标记:按归一化剧名持久化,详见 lib/skip-marks.ts */
+ /** 跳过片段:按归一化剧名持久化,详见 lib/skip-marks.ts */
skipMarks: Record<string, SkipMark>;
- /** 命中片头标记时自动跳到片头结束位置 */
- autoSkipIntro: boolean;
- /** 到达片尾标记时自动结束本集;是否连播下一集仍由 autoplayNext 决定 */
- autoSkipOutro: boolean;
+ /**
+ * 自动跳过标记的片段:片头/中段跳到片段末尾,片尾则直接结束本集。
+ * 三类都是「标记区间 → 不播」,所以共用同一个开关;是否连播下一集仍由 autoplayNext 决定。
+ */
+ autoSkipSegments: boolean;
imageProxyMode: 'direct' | 'proxy' | 'custom';
/** 用户是否在设置中主动选择过封面图加载方式;为 false 时部署者的 DEFAULT_IMAGE_MODE 默认值可生效 */
imageProxyModeTouched: boolean;
@@ -267,11 +268,13 @@ interface AppState extends AppSettings {
* 播放时的 videoHeight 才是真实分辨率,实测一旦拿到就覆盖探测结果。
*/
setQuality: (entries: Record<string, QualityEntry>) => void;
- /** 写入/更新一部剧的片头片尾标记;字段传 null 表示清除该字段 */
- setSkipMark: (key: string, patch: { introEnd?: number | null; outroStart?: number | null }) => void;
- /** 清除单部剧的片头片尾标记 */
+ /** 写入/更新一部剧的跳过片段(整体替换 segments,空数组表示清除) */
+ setSkipMark: (key: string, segments: SkipSegment[]) => void;
+ /** 本剧跳过总开关:关闭后保留标记但不生效 */
+ setSkipMarkEnabled: (key: string, enabled: boolean) => void;
+ /** 清除单部剧的跳过片段 */
clearSkipMark: (key: string) => void;
- /** 清除全部片头片尾标记(设置面板的「清除全部」入口) */
+ /** 清除全部跳过片段(设置面板的「清除全部」入口) */
clearAllSkipMarks: () => void;
markEnvSubsSeen: (urls: string[]) => void;
updateSettings: (patch: Partial<Omit<AppSettings, 'customAPIs' | 'selectedKeys'>>) => void;
@@ -319,9 +322,8 @@ export const useAppStore = create<AppState>()(
recommendSourceTouched: false,
autoplayNext: true,
skipMarks: {},
- // 自动跳过默认开启,但只有用户真正标记过片头/片尾才生效
- autoSkipIntro: true,
- autoSkipOutro: true,
+ // 自动跳过默认开启,但只有用户真正标记过片段才生效
+ autoSkipSegments: true,
// 直连优先:豆瓣封面有公共镜像 + 内置代理两级兜底(见 buildImageCandidates),
// 默认省服务器流量;老用户保持已持久化的选择不受影响。
// 部署者可用 DEFAULT_IMAGE_MODE=proxy 下发内置代理优先(最稳定,吃服务器流量)
@@ -740,27 +742,34 @@ export const useAppStore = create<AppState>()(
set({ qualityMap: mergeQualityEntries(get().qualityMap, entries) });
},
- setSkipMark: (key, patch) => {
+ setSkipMark: (key, segments) => {
const marks = get().skipMarks;
- const prev = marks[key];
- const next: SkipMark = { ...prev, updatedAt: Date.now() };
- if ('introEnd' in patch) {
- if (patch.introEnd == null) delete next.introEnd;
- else next.introEnd = patch.introEnd;
- }
- if ('outroStart' in patch) {
- if (patch.outroStart == null) delete next.outroStart;
- else next.outroStart = patch.outroStart;
- }
- // 两个字段都清空后整条删除,持久化快照里不留空壳条目
- if (next.introEnd === undefined && next.outroStart === undefined) {
- if (!prev) return;
+ // 空片段列表整条删除,持久化快照里不留空壳条目
+ if (!segments || segments.length === 0) {
+ if (!marks[key]) return;
const rest = { ...marks };
delete rest[key];
set({ skipMarks: rest });
return;
}
- set({ skipMarks: { ...marks, [key]: next } });
+ set({
+ skipMarks: {
+ ...marks,
+ [key]: {
+ segments,
+ // 改片段不重置本剧总开关:用户可能只是修一条标错的边界
+ enabled: marks[key]?.enabled ?? true,
+ updatedAt: Date.now(),
+ },
+ },
+ });
+ },
+
+ setSkipMarkEnabled: (key, enabled) => {
+ const marks = get().skipMarks;
+ const mark = marks[key];
+ if (!mark || mark.enabled === enabled) return;
+ set({ skipMarks: { ...marks, [key]: { ...mark, enabled, updatedAt: Date.now() } } });
},
clearSkipMark: (key) => {
@@ -806,18 +815,48 @@ export const useAppStore = create<AppState>()(
// v1:直播源新增归属字段、最近观看新增 sourceUrl。
// v2:直播源归属改为多引用(fromSubscription 单值 → fromSubscriptions 数组)。
// v3:新增片头片尾标记与自动跳过开关(旧快照缺字段时补默认值)。
+ // v4:片头/片尾双标记泛化为跳过片段 segments(opening/middle/ending)。
+ // v5:标记新增本剧总开关 enabled。
+ // v6:自动跳过由「片头 / 中段」合并为单一开关。
+ // v7:片尾结束也并入同一开关(不再单独提供 autoSkipOutro)。
// 此前未声明 version 的存量数据会被视为 v0 并走 migrate 补齐。
- version: 3,
+ version: 7,
migrate: (persisted, version) => {
const state = { ...((persisted ?? {}) as Partial<AppState>) };
if (!Array.isArray(state.liveRecent)) state.liveRecent = [];
if (!Array.isArray(state.liveSubscriptions)) state.liveSubscriptions = [];
- // 片头片尾标记必须是非数组对象;损坏的数据不能带进内存,否则读取时会抛错
- if (!state.skipMarks || typeof state.skipMarks !== 'object' || Array.isArray(state.skipMarks)) {
- state.skipMarks = {};
+
+ // v3 的片头/片尾双标记 → v4 的 segments(纯函数,脏数据在内部丢弃)
+ state.skipMarks = migrateSkipMarks(
+ (state as unknown as { skipMarks?: unknown }).skipMarks
+ );
+
+ // 「自动跳过」只有一个开关,覆盖片头/中段/片尾(都是「标记区间 → 不播」)。
+ // v3 autoSkipIntro / v4 autoSkipSegments / v5 autoSkipOpening / v5-v6 autoSkipOutro 统一归一:
+ // 以「跳过」开关为准,其次才看旧的分项开关,都没有时按默认开启。
+ const legacy = state as unknown as {
+ autoSkipIntro?: unknown;
+ autoSkipSegments?: unknown;
+ autoSkipOpening?: unknown;
+ autoSkipMiddle?: unknown;
+ autoSkipOutro?: unknown;
+ };
+ if (typeof legacy.autoSkipSegments !== 'boolean') {
+ state.autoSkipSegments =
+ typeof legacy.autoSkipOpening === 'boolean'
+ ? legacy.autoSkipOpening
+ : typeof legacy.autoSkipIntro === 'boolean'
+ ? legacy.autoSkipIntro
+ : typeof legacy.autoSkipOutro === 'boolean'
+ ? legacy.autoSkipOutro
+ : true;
}
- if (typeof state.autoSkipIntro !== 'boolean') state.autoSkipIntro = true;
- if (typeof state.autoSkipOutro !== 'boolean') state.autoSkipOutro = true;
+
+ // 迁移完成后清掉旧字段,避免内存里同时存在两套语义
+ for (const stale of ['autoSkipIntro', 'autoSkipOpening', 'autoSkipMiddle', 'autoSkipOutro']) {
+ delete (state as unknown as Record<string, unknown>)[stale];
+ }
+
if (version < 2) {
state.liveSubscriptions = state.liveSubscriptions.map((s) => {
const legacy = s as LiveSubscription & { fromSubscription?: unknown };
@@ -860,8 +899,7 @@ export const useAppStore = create<AppState>()(
recommendSourceTouched: s.recommendSourceTouched,
autoplayNext: s.autoplayNext,
skipMarks: s.skipMarks,
- autoSkipIntro: s.autoSkipIntro,
- autoSkipOutro: s.autoSkipOutro,
+ autoSkipSegments: s.autoSkipSegments,
imageProxyMode: s.imageProxyMode,
imageProxyModeTouched: s.imageProxyModeTouched,
customImageProxy: s.customImageProxy,