From 1622ff1672fd75189b2e3ea093bada93f340fba4 Mon Sep 17 00:00:00 2001 From: LNP <90243050+LNPANDY@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:13:57 +0000 Subject: [PATCH] feat(feed): add mobile single-tap clean mode, double-tap pause, pinch-to-zoom, and seamless fullscreen transition --- src/App.tsx | 12 +- src/components/Feed.tsx | 746 +++++++++++++++++++++++--------- src/components/VideoSurface.tsx | 313 ++++++++++++-- src/index.css | 25 +- src/store.tsx | 30 +- 5 files changed, 870 insertions(+), 256 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 933989c..6b1bcc4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -82,7 +82,8 @@ function StackPage({ page, onBack, wide, top, bottomInset }: { /* ============ 应用主体 ============ */ function AppBody() { - const { platform, tab, setTab, stack, pop, loginOpen, setLoginOpen, fs } = useStore(); + const { platform, tab, setTab, stack, pop, loginOpen, setLoginOpen, fs, clean } = useStore(); + const isMobile = platform === "android" || platform === "ios"; const mainRef = useRef(null); const [wide, setWide] = useState(!isMobile); const [collapsed, setCollapsed] = useState(false); @@ -117,7 +118,7 @@ function AppBody() { const vis = (k: Tab) => (tab === k ? "absolute inset-0" : "absolute inset-0 invisible pointer-events-none"); const pageActive = stack.length === 0 && !loginOpen; - const bottomInset = isMobile ? (fs ? 0 : 40) : 14; + const bottomInset = isMobile ? (fs || clean ? 0 : 40) : 14; /* 栈页(从搜索/分类/我的进入的播放页、图文页)没有底栏, 底部只让出安全区。之前多留了 20px,视频底边会露出一条 「底栏」似的窄缝(底部的压暗渐变到不了屏幕最底)。 */ @@ -138,7 +139,7 @@ function AppBody() { ))} - {isMobile && !fs && stack.length === 0 && } + {isMobile && !fs && !clean && stack.length === 0 && } ); @@ -215,9 +216,10 @@ function ShellInner({ collapsed, theater }: { collapsed: boolean; theater: boole /* ============ 移动端(无壳) ============ */ function MobileShell() { + const { platform } = useStore(); return ( -
+
diff --git a/src/components/Feed.tsx b/src/components/Feed.tsx index 4dad411..be82412 100644 --- a/src/components/Feed.tsx +++ b/src/components/Feed.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { api, cover, fmt, fmtTime, isMobile, mediaUrl } from "../api"; +import { invoke } from "@tauri-apps/api/core"; +import { api, cover, fmt, fmtTime, isMobile } from "../api"; import type { Detail, Episode, Post, VideoCard } from "../types"; import { useStore } from "../store"; import { Avatar, Img, Sheet } from "./ui"; @@ -28,10 +29,6 @@ type Props = { startTime?: number; }; -const RATES = [1, 1.25, 1.5, 2]; - -const stripHtml = (s: string) => s.replace(/<[^>]+>/g, " ").replace(/ /g, " ").replace(/\s+/g, " ").trim(); - export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind = "video", active, bottomInset, onBack, onNearEnd, startEp, startTime }: Props) { const store = useStore(); const { isLiked, isFav, toggleLikeLocal, toggleFavLocal, toggleFollowLocal, muted, setMuted, volume, setVolume, toast, addHistory, user, setLoginOpen } = store; @@ -43,7 +40,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const [epMap, setEpMap] = useState>(() => (startEp ? { [videoIds[startIndex]]: startEp } : {})); const [details, setDetails] = useState>({}); const [playUrls, setPlayUrls] = useState>({}); - const [cards, setCards] = useState>({}); + const [cards] = useState>({}); const [posts, setPosts] = useState>({}); const [time, setTime] = useState(0); @@ -68,6 +65,22 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const setTheater = store.setTheater; const fs = store.fs; const setFs = store.setFs; + const clean = store.clean; + const setClean = store.setClean; + + /* 追踪手机视口是否已处于物理/系统横屏状态(window.innerWidth > window.innerHeight) */ + const [vpLandscape, setVpLandscape] = useState( + () => typeof window !== "undefined" && window.innerWidth > window.innerHeight, + ); + + /* 单击清屏 vs 双击暂停计时器 */ + const lastTapRef = useRef<{ time: number; timer: number | null }>({ time: 0, timer: null }); + const clearTapTimer = () => { + if (lastTapRef.current.timer) { + window.clearTimeout(lastTapRef.current.timer); + lastTapRef.current.timer = null; + } + }; /* 桌面:鼠标闲置 2.8s 自动隐藏播放器 UI(沉浸) */ const [idle, setIdle] = useState(false); @@ -87,7 +100,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind }, [paused]); const [fullscreen, setFullscreen] = useState(false); const [heartBurst, setHeartBurst] = useState(0); - /* —— 移动端手势 —— */ + /* —— 移动端手势 & 竖屏横片缩放 —— */ const [holdSpeed, setHoldSpeed] = useState(false); const [speedLock, setSpeedLock] = useState(false); const [lockArmed, setLockArmed] = useState(false); @@ -95,12 +108,17 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const lockArmedRef = useRef(false); const [scrub, setScrub] = useState<{ pct: number; target: number } | null>(null); const scrubTarget = useRef(null); + /* 竖屏下横屏视频适应模式 + 双指无级缩放/平移 */ + const [portraitFit, setPortraitFit] = useState<"contain" | "cover">("contain"); + const [zoom, setZoom] = useState({ scale: 1, x: 0, y: 0, gesturing: false }); + const pinchRef = useRef<{ + dist0: number; midX0: number; midY0: number; scale0: number; x0: number; y0: number; + } | null>(null); /* 进度条拖动 */ - const barRef = useRef(null); const barScrub = useRef(false); const [barPct, setBarPct] = useState(null); const gesture = useRef<{ - x: number; y: number; startY: number; t: number; timer: number | null; + x: number; y: number; startX: number; startY: number; t: number; timer: number | null; mode: "idle" | "hold" | "scrub" | "pan"; base: number; width: number; playing: boolean; } | null>(null); @@ -113,10 +131,12 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const episodes = detail?.episodes || []; const post = posts[curId]; - /* 观看进度:onTime 里每 5 秒落一次;退出播放页时再用 liveRef 兜一次 */ + /* 观看进度:onTime 里每 5 秒落一次;拖动进度条期间忽略底层 timeupdate 防止进度条回跳 */ const onTimeTick = (t: number) => { liveRef.current = { id: curId, ep: curEp, dur: duration, t }; - setTime(t); + if (!barScrub.current && gesture.current?.mode !== "scrub") { + setTime(t); + } const now = Date.now(); if (duration > 0 && now - lastSaveRef.current > 5000) { lastSaveRef.current = now; @@ -179,18 +199,122 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const effRate = holdSpeed || speedLock ? 2 : rate; /* 进度条显示百分比(拖动时用拖动值) */ const barProgress = barPct ?? (duration ? time / duration : 0); - /* 沉浸全屏 + 横屏视频 → 舞台旋转 90°,看起来就是横屏 */ - const rotated = !isDesktop && fs && vsize.w > vsize.h && vsize.h > 0; + /* 是否为横屏视频(16:9 等宽大于高) */ + const isLandscapeVideo = vsize.w > vsize.h && vsize.h > 0; + /* 仅当「全屏 + 横屏视频 + 手机系统视口尚未横过来 (!vpLandscape)」时才用 CSS 旋转 90° 兜底; + 一旦系统屏幕已经横过来了 (vpLandscape === true),不再叠加 CSS 旋转,彻底解决手机横置后视频反而竖过去的问题! */ + const rotated = !isDesktop && fs && isLandscapeVideo && !vpLandscape; - /* 滚动定位 */ + /* 借鉴 stclock1988/hghub-ios (PlayerView.swift keepPlayingThroughTransition): + iOS 在横竖屏几何旋转或全屏视图层级切换期间,系统底层 AVPlayer / WebKit 视频层可能被短暂挂起暂停。 + 在过渡窗口期内分批重申 play(),确保旋转/全屏切换不中断播放。 */ + const keepPlayingTimers = useRef([]); + const keepPlayingThroughTransition = useCallback(() => { + keepPlayingTimers.current.forEach((id) => window.clearTimeout(id)); + keepPlayingTimers.current = []; + const el = videoRef.current?.el(); + const shouldPlay = el ? !el.paused : !paused; + if (!shouldPlay) return; + for (const delay of [50, 150, 300, 500, 800, 1200]) { + const tid = window.setTimeout(() => { + const v = videoRef.current?.el(); + if (v && v.paused && !v.ended) { + videoRef.current?.play(); + } + }, delay); + keepPlayingTimers.current.push(tid); + } + }, [paused]); + + useEffect(() => () => { + keepPlayingTimers.current.forEach((id) => window.clearTimeout(id)); + }, []); + + /* 监听手机屏幕横竖屏变化:物理横置手机时自动进入全屏,竖回时自动退出全屏 */ + useEffect(() => { + if (isDesktop) return undefined; + const onViewportChange = () => { + const isLand = window.innerWidth > window.innerHeight; + setVpLandscape((prev) => { + if (prev !== isLand && active) { + setFs(isLand); + keepPlayingThroughTransition(); + } + return isLand; + }); + }; + window.addEventListener("resize", onViewportChange); + window.addEventListener("orientationchange", onViewportChange); + return () => { + window.removeEventListener("resize", onViewportChange); + window.removeEventListener("orientationchange", onViewportChange); + }; + }, [isDesktop, active, setFs, keepPlayingThroughTransition]); + + /* 进入 / 退出全屏:对横屏视频直接调用原生屏幕方向切换,让手机系统界面真正横过来 */ + const enterFs = useCallback(() => { + keepPlayingThroughTransition(); + setClean(false); + setFs(true); + if (isLandscapeVideo) { + invoke("set_orientation", { landscape: true }).catch(() => {}); + try { + (screen.orientation as unknown as { lock?: (o: string) => Promise })?.lock?.("landscape")?.catch(() => {}); + } catch { /* ignore */ } + } + }, [isLandscapeVideo, setClean, setFs, keepPlayingThroughTransition]); + + const exitFs = useCallback(() => { + keepPlayingThroughTransition(); + setClean(false); + setFs(false); + invoke("set_orientation", { landscape: false }).catch(() => {}); + try { screen.orientation?.unlock?.(); } catch { /* ignore */ } + }, [setClean, setFs, keepPlayingThroughTransition]); + + /* 全屏状态下若视频宽高刚加载出来且为横屏,自动补发一次横屏指令 */ + useEffect(() => { + if (!isDesktop && fs && isLandscapeVideo) { + invoke("set_orientation", { landscape: true }).catch(() => {}); + } + }, [isDesktop, fs, isLandscapeVideo]); + + /* 全屏切换或视口旋转后校准滚动容器 scrollTop: + - 进入全屏时非当前项已隐藏,当前项位于顶部 scrollTop = 0; + - 退出全屏回到竖屏列表时,立即将 scrollTop 重新对齐到 index * clientHeight,防止错位到其它视频封面。 */ + useEffect(() => { + const el = boxRef.current; + if (!el) return undefined; + if (fs) { + el.scrollTop = 0; + return undefined; + } + const syncScroll = () => { + const box = boxRef.current; + if (!box || fs) return; + box.scrollTop = index * (box.clientHeight || 1); + }; + syncScroll(); + const raf = requestAnimationFrame(syncScroll); + const t1 = window.setTimeout(syncScroll, 120); + const t2 = window.setTimeout(syncScroll, 350); + return () => { + cancelAnimationFrame(raf); + window.clearTimeout(t1); + window.clearTimeout(t2); + }; + }, [fs, vpLandscape, index]); + + /* 滚动定位(全屏或缩放手势期间锁定索引,避免容器尺寸变化误触发翻页) */ const onScroll = useCallback(() => { + if (fs || pinchRef.current) return; const el = boxRef.current; if (!el) return; const h = el.clientHeight || 1; const i = Math.max(0, Math.min(videoIds.length - 1, Math.round(el.scrollTop / h))); setIndex((prev) => (prev === i ? prev : i)); if (onNearEnd && i >= videoIds.length - 3) onNearEnd(); - }, [videoIds.length, onNearEnd]); + }, [videoIds.length, onNearEnd, fs]); const go = useCallback((delta: number) => { const el = boxRef.current; @@ -251,20 +375,35 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind // eslint-disable-next-line react-hooks/exhaustive-deps }, [curId, curEp]); - /* 切换条目/集数时重置播放状态 */ + /* 切换条目/集数时重置播放与缩放状态 */ useEffect(() => { setTime(0); setDuration(0); setBuffered(0); setErr(""); setWaiting(true); setPaused(false); setDescOpen(false); setVsize({ w: 0, h: 0 }); + setPortraitFit("contain"); + setZoom({ scale: 1, x: 0, y: 0, gesturing: false }); }, [playKey]); + /* 进出全屏时复位双指缩放并校准滚动条位置 */ + useEffect(() => { + setZoom({ scale: 1, x: 0, y: 0, gesturing: false }); + if (!fs && boxRef.current) { + const el = boxRef.current; + requestAnimationFrame(() => { + el.scrollTop = index * (el.clientHeight || 1); + }); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [fs]); + /* 音量/静音同步 */ useEffect(() => { videoRef.current?.mute(muted); }, [muted]); useEffect(() => { videoRef.current?.volume(volume); }, [volume]); /* 倍速同步(长按 2x / 锁定 2x / 基准倍速) */ useEffect(() => { videoRef.current?.rate(effRate); }, [effRate, playKey]); - /* 离开播放页时把最后位置落盘 */ + /* 离开播放页时把最后位置落盘并清理计时器 */ useEffect(() => () => { + clearTapTimer(); const s = liveRef.current; if (s.id && s.dur) addHistory(s.id, s.ep, s.t, s.dur); // eslint-disable-next-line react-hooks/exhaustive-deps @@ -318,19 +457,91 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind else el.requestFullscreen().catch(() => {}); }; - /* —— 长按 2x(上滑锁定) / 横拖定位 / 单击暂停 —— */ + /* —— 双指捏合缩放 & 平移(Pinch-to-Zoom & Pan) —— */ + const cancelSingleGesture = () => { + clearTapTimer(); + const g = gesture.current; + if (g?.timer) window.clearTimeout(g.timer); + gesture.current = null; + if (holdRef.current) { + holdRef.current = false; + setHoldSpeed(false); + } + lockArmedRef.current = false; + setLockArmed(false); + setScrub(null); + scrubTarget.current = null; + }; + + const onTouchStart = (e: React.TouchEvent) => { + if (isDesktop || controlsLocked) return; + if (e.touches.length === 2) { + cancelSingleGesture(); + const t0 = e.touches[0]; + const t1 = e.touches[1]; + const dist0 = Math.max(12, Math.hypot(t1.clientX - t0.clientX, t1.clientY - t0.clientY)); + const midX0 = (t0.clientX + t1.clientX) / 2; + const midY0 = (t0.clientY + t1.clientY) / 2; + pinchRef.current = { + dist0, + midX0, + midY0, + scale0: zoom.scale, + x0: zoom.x, + y0: zoom.y, + }; + } + }; + + const onTouchMove = (e: React.TouchEvent) => { + if (isDesktop || controlsLocked) return; + if (e.touches.length === 2 && pinchRef.current) { + const p = pinchRef.current; + const t0 = e.touches[0]; + const t1 = e.touches[1]; + const dist = Math.max(12, Math.hypot(t1.clientX - t0.clientX, t1.clientY - t0.clientY)); + const midX = (t0.clientX + t1.clientX) / 2; + const midY = (t0.clientY + t1.clientY) / 2; + const nextScale = Math.max(0.85, Math.min(3.5, p.scale0 * (dist / p.dist0))); + const rawDx = midX - p.midX0; + const rawDy = midY - p.midY0; + const dx = rotated ? rawDy : rawDx; + const dy = rotated ? -rawDx : rawDy; + const maxX = Math.max(0, (nextScale - 1) * window.innerWidth * 0.55); + const maxY = Math.max(0, (nextScale - 1) * window.innerHeight * 0.55); + const nextX = Math.max(-maxX, Math.min(maxX, p.x0 + dx)); + const nextY = Math.max(-maxY, Math.min(maxY, p.y0 + dy)); + setZoom({ scale: nextScale, x: nextX, y: nextY, gesturing: true }); + } + }; + + const onTouchEnd = (e: React.TouchEvent) => { + if (isDesktop) return; + if (pinchRef.current && e.touches.length < 2) { + pinchRef.current = null; + setZoom((prev) => + prev.scale < 1.08 + ? { scale: 1, x: 0, y: 0, gesturing: false } + : { ...prev, gesturing: false }, + ); + } + }; + + /* —— 长按 2x(上滑锁定) / 横拖定位 / 单击清屏 / 双击暂停 —— */ const onDown = (e: React.PointerEvent) => { - if (isDesktop || controlsLocked || !active || gesture.current || e.button !== 0) return; + if (isDesktop || controlsLocked || !active || !e.isPrimary || pinchRef.current || gesture.current || e.button !== 0) return; const el = e.currentTarget; - const width = el.clientWidth || 1; + const span = rotated ? (el.clientHeight || window.innerHeight || 1) : (el.clientWidth || 1); try { el.setPointerCapture(e.pointerId); } catch { /* ignore */ } const g = { - x: e.clientX, y: e.clientY, startY: e.clientY, t: Date.now(), base: time, width, - mode: "idle" as "idle" | "hold" | "scrub" | "pan", + x: e.clientX, y: e.clientY, startX: e.clientX, startY: e.clientY, + t: Date.now(), base: time, width: span, playing: videoRef.current?.el()?.paused === false, + mode: "idle" as "idle" | "hold" | "scrub" | "pan", timer: window.setTimeout(() => { const cur = gesture.current; - if (!cur || cur.mode !== "idle") return; + if (!cur || cur.mode !== "idle" || pinchRef.current) return; + clearTapTimer(); cur.mode = "hold"; holdRef.current = true; setHoldSpeed(true); @@ -343,14 +554,21 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind }; const onMove = (e: React.PointerEvent) => { + if (pinchRef.current) { + cancelSingleGesture(); + return; + } const g = gesture.current; - if (!g || isDesktop) return; - const dx = e.clientX - g.x; - const dy = e.clientY - g.y; + if (!g || isDesktop || !e.isPrimary) return; + const rawDx = e.clientX - g.x; + const rawDy = e.clientY - g.y; + const dx = rotated ? rawDy : rawDx; + const dy = rotated ? -rawDx : rawDy; /* 长按中:上滑 64px 进入「松开即锁定」 */ if (g.mode === "hold") { - const armed = g.startY - e.clientY > 64; + const upDist = rotated ? (e.clientX - g.startX) : (g.startY - e.clientY); + const armed = upDist > 64; if (armed !== lockArmedRef.current) { lockArmedRef.current = armed; setLockArmed(armed); @@ -359,11 +577,12 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind } if (g.mode === "idle") { - if (Math.abs(dx) > 14 && Math.abs(dx) > Math.abs(dy)) { + if (Math.abs(dx) > 16 && Math.abs(dx) > Math.abs(dy) * 1.2) { + clearTapTimer(); if (g.timer) window.clearTimeout(g.timer); g.mode = "scrub"; - videoRef.current?.pause(); - } else if (Math.abs(dy) > 14) { + } else if (Math.abs(dy) > 16) { + clearTapTimer(); if (g.timer) window.clearTimeout(g.timer); g.mode = "pan"; } @@ -373,13 +592,14 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind if (g.mode === "scrub") { const total = duration || 0; if (!total) return; - const target = Math.max(0, Math.min(total, g.base + (dx / g.width) * total)); + const target = Math.max(0, Math.min(total - 0.2, g.base + (dx / g.width) * total)); scrubTarget.current = target; setScrub({ pct: (target / total) * 100, target }); } }; - const onUp = (cancelled = false) => { + const onUp = (e?: React.PointerEvent, cancelled = false) => { + if (pinchRef.current) return; const g = gesture.current; gesture.current = null; if (!g) return; @@ -398,17 +618,40 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind } if (g.mode === "scrub") { const target = scrubTarget.current; - if (!cancelled && target != null) videoRef.current?.seek(target, "mobile_gesture"); setScrub(null); scrubTarget.current = null; + if (!cancelled && target != null) { + setErr(""); + setTime(target); + videoRef.current?.seek(target, "mobile_gesture"); + } if (g.playing && active) videoRef.current?.play(); return; } - if (!cancelled && g.mode === "idle" && Date.now() - g.t < 260) videoRef.current?.toggle(); + + if (cancelled || g.mode !== "idle") return; + const moveDist = e ? Math.hypot(e.clientX - g.x, e.clientY - g.y) : 0; + if (Date.now() - g.t < 260 && moveDist < 16) { + const now = Date.now(); + if (now - lastTapRef.current.time < 280) { + // 双击屏幕:切换暂停 / 播放 + clearTapTimer(); + lastTapRef.current.time = 0; + videoRef.current?.toggle(); + } else { + // 单击屏幕:切换清屏模式(消除或恢复所有界面控件,只显示视频内容) + lastTapRef.current.time = now; + clearTapTimer(); + lastTapRef.current.timer = window.setTimeout(() => { + lastTapRef.current.timer = null; + setClean((c) => !c); + }, 250) as unknown as number; + } + } }; useEffect(() => { - if (!active || controlsLocked) onUp(true); + if (!active || controlsLocked) onUp(undefined, true); // Cancel pending gestures when the page is hidden or controls are locked. // eslint-disable-next-line react-hooks/exhaustive-deps }, [active, controlsLocked]); @@ -420,28 +663,32 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const lockControls = () => { setPanel(null); setControlsLocked(true); }; - /* 长按倍速期间禁止原生滚动,否则上滑会被列表吃掉、锁不住倍速 */ + /* 长按倍速 / 双指缩放 / 全屏期间禁止外层列表原生滚动 */ useEffect(() => { if (isDesktop) return undefined; const el = boxRef.current; if (!el) return undefined; - const fn = (e: TouchEvent) => { if (holdRef.current) e.preventDefault(); }; + const fn = (e: TouchEvent) => { + if (holdRef.current || pinchRef.current || fs || e.touches.length >= 2) { + e.preventDefault(); + } + }; el.addEventListener("touchmove", fn, { passive: false }); return () => el.removeEventListener("touchmove", fn); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isDesktop, videoIds.length]); + }, [isDesktop, videoIds.length, fs]); - /* —— 进度条拖动(旋转舞台下按 Y 轴换算) —— */ - const barPctAt = (clientX: number, clientY: number) => { - const r = barRef.current?.getBoundingClientRect(); + /* —— 进度条拖动(直接用当前触发元素的 BoundingRect,旋转舞台下按 Y 轴换算) —— */ + const barPctAt = (barEl: HTMLElement | null, clientX: number, clientY: number) => { + const r = barEl?.getBoundingClientRect(); if (!r) return null; const span = rotated ? r.height : r.width; if (!span) return null; const raw = rotated ? (clientY - r.top) / span : (clientX - r.left) / span; return Math.max(0, Math.min(1, raw)); }; - const barSeekTo = (clientX: number, clientY: number) => { - const pct = barPctAt(clientX, clientY); + const barSeekTo = (barEl: HTMLElement | null, clientX: number, clientY: number) => { + const pct = barPctAt(barEl, clientX, clientY); if (pct == null) return null; setBarPct(pct); return pct; @@ -450,27 +697,29 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind e.stopPropagation(); videoRef.current?.trace("seek.input.down", { input: "mobile_bar" }); barScrub.current = true; - try { (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); } catch { /* ignore */ } - barSeekTo(e.clientX, e.clientY); + const el = e.currentTarget as HTMLElement; + try { el.setPointerCapture(e.pointerId); } catch { /* ignore */ } + barSeekTo(el, e.clientX, e.clientY); }; const onBarMove = (e: React.PointerEvent) => { if (!barScrub.current) return; e.stopPropagation(); videoRef.current?.trace("seek.input.move", { input: "mobile_bar" }); - barSeekTo(e.clientX, e.clientY); + barSeekTo(e.currentTarget as HTMLElement, e.clientX, e.clientY); }; const onBarUp = (e: React.PointerEvent) => { if (!barScrub.current) return; barScrub.current = false; e.stopPropagation(); - const pct = barPctAt(e.clientX, e.clientY); - if (pct != null && duration) { - const target = pct * duration; + const pct = barPctAt(e.currentTarget as HTMLElement, e.clientX, e.clientY) ?? barPct; + setBarPct(null); + if (pct != null && duration > 0) { + const target = Math.max(0, Math.min(duration - 0.15, pct * duration)); + setErr(""); + setTime(target); videoRef.current?.trace("seek.input.up", { input: "mobile_bar", target }); videoRef.current?.seek(target, "mobile_bar"); - setTime(target); } - setBarPct(null); }; const togglePip = async () => { @@ -521,43 +770,194 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind return
; } + const effectiveFit: "contain" | "cover" = isDesktop + ? "contain" + : isLandscapeVideo + ? (fs || vpLandscape ? "contain" : portraitFit) + : (vpLandscape ? "contain" : "cover"); + return (
{ if (isDesktop) wake(); }}>
- {/* 氛围背景 */} -
- {posterUrl && } -
+ {/* 氛围背景(全屏时隐藏,避免透出封面底图) */} + {!fs && ( +
+ {posterUrl && } +
+ )}
{videoIds.map((vid, i) => { const isActive = i === index; return ( -
+
{isActive && playUrl ? ( -
onUp()} onPointerCancel={() => onUp(true)} onLostPointerCapture={() => onUp(true)}> - 0 && vsize.w > vsize.h) ? "contain" : "cover"} - onClick={() => { if (isDesktop) videoRef.current?.toggle(); }} - onTime={onTimeTick} - onDuration={onDurationTick} - onSize={(w, h) => setVsize({ w, h })} - onPlaying={() => { setPaused(false); setWaiting(false); }} - onPause={() => setPaused(true)} - onWaiting={() => setWaiting(true)} - onEnded={() => { const next = episodes.find((e) => e.ep_num === curEp + 1); if (next) pickEp(next.ep_num); }} - onError={(m) => setErr(m)} /> +
+
1.05 ? "none" : "pan-y" }} + onTouchStart={onTouchStart} + onTouchMove={onTouchMove} + onTouchEnd={onTouchEnd} + onTouchCancel={onTouchEnd} + onPointerDown={onDown} + onPointerMove={onMove} + onPointerUp={(e) => onUp(e, false)} + onPointerCancel={(e) => onUp(e, true)} + onLostPointerCapture={(e) => onUp(e, true)}> + { if (isDesktop) videoRef.current?.toggle(); }} + onTime={onTimeTick} + onDuration={onDurationTick} + onSize={(w, h) => setVsize({ w, h })} + onPlaying={() => { setPaused(false); setWaiting(false); setErr(""); }} + onPause={() => setPaused(true)} + onWaiting={() => setWaiting(true)} + onEnded={() => { const next = episodes.find((e) => e.ep_num === curEp + 1); if (next) pickEp(next.ep_num); }} + onError={(m) => setErr(m)} + /> +
+ + {/* 横拖定位浮层 */} + {!isDesktop && scrub && ( +
+ {fmtTime(scrub.target)} + / {fmtTime(duration)} +
+
+
+
+ )} + + {/* 暂停 / 缓冲 / 报错恢复 */} + {paused && !err && ( +
+ + + +
+ )} + {waiting && !err && !paused && ( +
+ )} + {err && ( +
+
+ 视频暂时无法加载 + {err} + +
+
+ )} + + {/* 移动端:倍速状态 / 锁定提示 */} + {!isDesktop && (!clean || holdSpeed) && (holdSpeed || speedLock || rate !== 1) && ( + + )} + {!isDesktop && holdSpeed && ( +
+ + {lockArmed ? "松开锁定 2.0x" : "上滑到此锁定倍速"} +
+ )} + + {/* 移动端:沉浸全屏控制栏(清屏 clean 模式下隐藏,单击屏幕可呼出/隐藏) */} + {!isDesktop && fs && !clean && !controlsLocked && ( + <> +
+ + +
+ {zoom.scale > 1.05 && ( + + )} +
+
+
+
+
+ {barPct !== null && ( +
+ {fmtTime(barPct * (duration || 0))} / {fmtTime(duration)} +
+ )} +
+
+
+ + {fmtTime(time)} + + {fmtTime(duration)} +
+ + )}
) : (
- +
)} @@ -573,12 +973,57 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
)} - {/* 渐变压暗,保证文字可读 */} -
+ {/* 渐变压暗,保证文字可读(清屏模式下不加压暗遮罩,只显示纯视频内容) */} + {!fs && !clean && ( +
+ )} + + {/* 竖屏下观看横屏视频:快捷「放大铺满 / 完整显示 / 全屏横屏」与双指缩放复位胶囊 */} + {isActive && !fs && !clean && !isDesktop && (isLandscapeVideo || zoom.scale > 1.05) && ( +
+ {isLandscapeVideo && ( + <> + + + + )} + {!isLandscapeVideo && zoom.scale > 1.05 && ( + + )} +
+ )} {/* 顶部 */} - {!fs && mode === "context" ? ( + {!fs && !clean && mode === "context" ? ( isDesktop ? (
@@ -596,7 +1041,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind {/* 右侧操作栏(移动端):收藏 / 评论 / 全屏 / 分享 颜色写死不跟主题走:浅色主题下这些字必须仍是白色 */} - {!fs && !isDesktop && ( + {!fs && !clean && !isDesktop && (
- @@ -692,63 +1137,32 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
)} - {/* 移动端:标题 + 详情标签 + 进度线(不加底色,只铺一层柔和压暗保证可读) */} - {!fs && !isDesktop && ( + {/* 移动端:标题 + 详情标签 + 进度线(清屏 clean 模式下隐藏) */} + {!fs && !clean && !isDesktop && (

{meta.title}

-
+
-
-
-
-
- {barPct !== null && ( -
- {fmtTime(barPct * (duration || 0))} + {isActive && ( +
+
+
- )} -
-
-
- )} - - - {/* 横拖定位浮层 */} - {!isDesktop && scrub && ( -
- {fmtTime(scrub.target)} - / {fmtTime(duration)} -
-
-
-
- )} - - {/* 暂停 / 缓冲 */} - {isActive && paused && !err && ( -
- - - -
- )} - {isActive && waiting && !err && !paused && ( -
- )} - {isActive && err && ( -
-
- 视频暂时无法加载 - {err} - + {barPct !== null && ( +
+ {fmtTime(barPct * (duration || 0))} / {fmtTime(duration)} +
+ )} +
+ )}
)} @@ -785,70 +1199,6 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind /> )} - {/* 移动端:倍速状态 / 锁定提示 */} - {!isDesktop && (holdSpeed || speedLock || rate !== 1) && ( - - )} - {!isDesktop && holdSpeed && ( -
- - {lockArmed ? "松开锁定 2.0x" : "上滑到此锁定倍速"} -
- )} - - {/* 移动端全屏模式下的进度条(普通模式的进度条在底部灰块里) */} - {!isDesktop && fs && ( -
-
-
-
-
-
-
- )} - - {/* 移动端:沉浸全屏(安卓 WebView 不支持 Fullscreen API,改用应用内沉浸层) */} - {!isDesktop && fs && ( - <> - -
- - {fmtTime(time)} - - {fmtTime(duration)} -
- - )} - {/* 选集 / 评论:桌面停靠在右侧(画面让位),移动端底部弹层 */} {isDesktop ? (
@@ -945,16 +1295,16 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind )}
- {!isDesktop && !controlsLocked && active && ( -
- {!fs && } + - {!fs && } +
)} {controlsLocked && { setControlsLocked(false); wake(); }} />} diff --git a/src/components/VideoSurface.tsx b/src/components/VideoSurface.tsx index b9045ec..607ec0a 100644 --- a/src/components/VideoSurface.tsx +++ b/src/components/VideoSurface.tsx @@ -1,6 +1,6 @@ -import { useEffect, useImperativeHandle, useRef, forwardRef, useState } from "react"; +import React, { useEffect, useImperativeHandle, useRef, forwardRef, useState } from "react"; import Hls from "hls.js"; -import { isLocalMedia, playlist } from "../api"; +import { isLocalMedia, platform, playlist } from "../api"; import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics"; import { usePlaybackActivity } from "../usePlaybackActivity"; @@ -9,11 +9,12 @@ export type VideoHandle = { play: () => void; pause: () => void; toggle: () => void; - seek: (t: number, source?: string) => void; + seek: (t: number, sourceOrAutoResume?: string | boolean) => void; trace: (event: string, data?: Record) => void; rate: (r: number) => void; mute: (m: boolean) => void; volume: (v: number) => void; + reload: () => void; }; type Props = { @@ -25,6 +26,11 @@ type Props = { muted?: boolean; loop?: boolean; fit?: "contain" | "cover"; + /** 缩放倍率与平移偏移(用于移动端竖屏下双指缩放横屏视频) */ + scale?: number; + panX?: number; + panY?: number; + isGesturing?: boolean; /** 换源后重新套用,避免切集时音量/倍速被浏览器重置 */ volume?: number; rate?: number; @@ -42,16 +48,75 @@ type Props = { /** 只负责「播」:hls.js + video 元素,控制条由外层渲染。 */ const VideoSurface = forwardRef(function VideoSurface( - { src, poster, autoPlay = true, active = true, diagnosticContext = {}, muted = false, loop = false, fit = "contain", volume = 1, rate = 1, + { src, poster, autoPlay = true, active = true, diagnosticContext = {}, muted = false, loop = false, fit = "contain", + scale = 1, panX = 0, panY = 0, isGesturing = false, + volume = 1, rate = 1, onTime, onDuration, onSize, onPlaying, onPause, onWaiting, onEnded, onError, onClick, className = "" }, ref, ) { const videoRef = useRef(null); const hlsRef = useRef(null); + const recoverCountRef = useRef(0); + const recoverTimerRef = useRef(null); + const lastSizeRef = useRef({ w: 0, h: 0 }); const [ready, setReady] = useState(false); const { trace, requestSeek } = usePlayerDiagnostics(videoRef, hlsRef, { ...diagnosticContext, active, resource: mediaResource(src) }); const activity = usePlaybackActivity(videoRef, hlsRef, { active, autoPlay, src, trace }); + const reportSizeAndDuration = (v: HTMLVideoElement) => { + if (v.duration && Number.isFinite(v.duration) && v.duration > 0) { + onDuration?.(v.duration); + } + const w = v.videoWidth || 0; + const h = v.videoHeight || 0; + if (w > 0 && h > 0 && (w !== lastSizeRef.current.w || h !== lastSizeRef.current.h)) { + lastSizeRef.current = { w, h }; + onSize?.(w, h); + } + }; + + const safeSeek = (t: number, sourceOrAutoResume: string | boolean = "handle") => { + const v = videoRef.current; + if (!v || !Number.isFinite(t)) return; + const dur = v.duration && Number.isFinite(v.duration) ? v.duration : 0; + const target = dur > 0 ? Math.max(0, Math.min(dur - 0.15, t)) : Math.max(0, t); + const source = typeof sourceOrAutoResume === "string" ? sourceOrAutoResume : "handle"; + const autoResume = typeof sourceOrAutoResume === "boolean" ? sourceOrAutoResume : !v.paused; + + requestSeek(target, source); + onWaiting?.(); + if (hlsRef.current) { + try { + hlsRef.current.startLoad(target); + } catch { /* ignore */ } + } + + try { + v.currentTime = target; + trace("seek.assigned", { target, source }); + } catch (e) { + trace("seek.rejected", { error_name: (e as Error).name }); + } + + if (autoResume && activity.isActive()) { + const resumeOnce = () => { + v.removeEventListener("seeked", resumeOnce); + v.removeEventListener("canplay", resumeOnce); + if (activity.isActive()) v.play().catch(() => {}); + }; + v.addEventListener("seeked", resumeOnce, { once: true }); + v.addEventListener("canplay", resumeOnce, { once: true }); + // 兜底:若 350ms 内已经就绪则直接播 + window.setTimeout(() => { + if (v.readyState >= 2 && v.paused && activity.isActive()) { + v.removeEventListener("seeked", resumeOnce); + v.removeEventListener("canplay", resumeOnce); + v.play().catch(() => {}); + } + }, 350); + } + }; + useImperativeHandle(ref, () => ({ el: () => videoRef.current, play: () => activity.play("handle"), @@ -62,29 +127,47 @@ const VideoSurface = forwardRef(function VideoSurface( trace("toggle.request"); if (v.paused) activity.play("toggle"); else activity.pause("toggle"); }, - seek: (t: number, source = "handle") => { - const v = videoRef.current; - if (v && Number.isFinite(t)) { - requestSeek(t, source); - try { v.currentTime = t; trace("seek.assigned", { target: t, source }); } - catch (e) { trace("seek.rejected", { error_name: (e as Error).name }); throw e; } - } - }, + seek: (t: number, sourceOrAutoResume: string | boolean = "handle") => safeSeek(t, sourceOrAutoResume), trace, rate: (r: number) => { const v = videoRef.current; if (v) v.playbackRate = r; }, mute: (m: boolean) => { const v = videoRef.current; if (v) v.muted = m; }, volume: (vol: number) => { const v = videoRef.current; if (v) v.volume = vol; }, - }), []); + reload: () => { + const v = videoRef.current; + if (!v) return; + recoverCountRef.current = 0; + const cur = v.currentTime || 0; + if (hlsRef.current) { + try { + hlsRef.current.startLoad(cur); + activity.play("reload"); + return; + } catch { /* ignore */ } + } + v.load(); + if (cur > 0) { + try { v.currentTime = cur; } catch { /* ignore */ } + } + activity.play("reload"); + }, + })); useEffect(() => { const video = videoRef.current; if (!video || !src) return; setReady(false); + recoverCountRef.current = 0; + lastSizeRef.current = { w: 0, h: 0 }; + if (recoverTimerRef.current) { + window.clearTimeout(recoverTimerRef.current); + recoverTimerRef.current = null; + } if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; } const proxied = isLocalMedia(src); const url = proxied ? src : playlist(src); const useHls = !url.includes("/seg?u="); + const isIos = platform === "ios"; trace("source.load", { engine: useHls && Hls.isSupported() ? "hls.js" : "native", auto_play: autoPlay, resource: mediaResource(src) }); /* 换源时先把音量/倍速套回去:hls 重新 attach 后浏览器会把它们重置成默认值 */ @@ -103,15 +186,27 @@ const VideoSurface = forwardRef(function VideoSurface( interstitialsController: undefined, contentSteeringController: undefined, enableInterstitialPlayback: false, - enableWorker: true, + // iOS WKWebView 下 WebWorker 跨自定义协议 hg:// 高频中断易死锁,关闭 Worker 走主线程加载更稳 + enableWorker: !isIos, // Prefer standard MSE on macOS; hls.js handles MMS-only fallback and seek recovery. preferManagedMediaSource: false, autoStartLoad: false, + lowLatencyMode: false, maxBufferLength: 30, + maxMaxBufferLength: 60, backBufferLength: 30, + maxBufferHole: 0.5, + highBufferWatchdogPeriod: 2, + nudgeOffset: 0.25, + nudgeMaxRetry: 6, manifestLoadingTimeOut: 20000, - manifestLoadingMaxRetry: 3, - fragLoadingMaxRetry: 4, + manifestLoadingMaxRetry: 4, + levelLoadingTimeOut: 20000, + levelLoadingMaxRetry: 4, + fragLoadingTimeOut: 25000, + fragLoadingMaxRetry: 6, + fragLoadingRetryDelay: 400, + startFragPrefetch: true, }); hlsRef.current = hls; observeHls(hls, trace); @@ -121,13 +216,63 @@ const VideoSurface = forwardRef(function VideoSurface( if (activity.isActive()) hls.startLoad(); if (autoPlay) activity.play("manifest_autoplay", true); }); + hls.on(Hls.Events.FRAG_BUFFERED, () => { + recoverCountRef.current = 0; + setReady(true); + }); hls.on(Hls.Events.ERROR, (_e, data) => { - if (!data.fatal) return; - onError?.(`${data.type}/${data.details}`); + // 非致命卡顿错误(常见于拖动进度条后缓冲空洞):主动触发加载与微调跳帧 + if (!data.fatal) { + if ( + activity.isActive() && ( + data.details === Hls.ErrorDetails.BUFFER_STALLED_ERROR || + data.details === Hls.ErrorDetails.FRAG_LOAD_ERROR || + data.details === Hls.ErrorDetails.FRAG_LOAD_TIMEOUT + ) + ) { + try { + hls.startLoad(video.currentTime || -1); + } catch { /* ignore */ } + } + return; + } + if (!activity.isActive()) return; - if (data.type === Hls.ErrorTypes.NETWORK_ERROR) hls.startLoad(); - else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError(); - else { hls.destroy(); hlsRef.current = null; } + + // 致命错误:优先自动重连/恢复解码器,最多静默恢复 4 次,避免拖动进度条直接弹报错层 + if (data.type === Hls.ErrorTypes.NETWORK_ERROR) { + if (recoverCountRef.current < 4) { + recoverCountRef.current += 1; + const delay = 250 * recoverCountRef.current; + if (recoverTimerRef.current) window.clearTimeout(recoverTimerRef.current); + recoverTimerRef.current = window.setTimeout(() => { + if (!hlsRef.current || !activity.isActive()) return; + try { + hlsRef.current.startLoad(video.currentTime || -1); + if (!video.paused) video.play().catch(() => {}); + } catch { /* ignore */ } + }, delay); + return; + } + onError?.(`${data.type}/${data.details}`); + hls.startLoad(); + } else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) { + if (recoverCountRef.current < 4) { + recoverCountRef.current += 1; + try { + if (recoverCountRef.current === 2) hls.swapAudioCodec(); + hls.recoverMediaError(); + video.play().catch(() => {}); + } catch { /* ignore */ } + return; + } + onError?.(`${data.type}/${data.details}`); + hls.recoverMediaError(); + } else { + onError?.(`${data.type}/${data.details}`); + hls.destroy(); + hlsRef.current = null; + } }); } else { video.src = url; @@ -136,6 +281,10 @@ const VideoSurface = forwardRef(function VideoSurface( return () => { trace("source.cleanup"); + if (recoverTimerRef.current) { + window.clearTimeout(recoverTimerRef.current); + recoverTimerRef.current = null; + } if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; } }; // eslint-disable-next-line react-hooks/exhaustive-deps @@ -151,30 +300,106 @@ const VideoSurface = forwardRef(function VideoSurface( v.playbackRate = rate; }; + const nearEndFiredRef = useRef(false); + useEffect(() => { + nearEndFiredRef.current = false; + }, [src]); + + // Native Resize Event listener for HTMLVideoElement (React doesn't always bind onResize on