refactor: 重构作品播放页性能、媒体同步与内存管理
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,16 +1,17 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { RefObject } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { RefObject } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { ImageData, LoopMode, Neighbors } from "../types.ts";
|
||||
import { releaseMediaElement } from "../utils";
|
||||
|
||||
const MIN_SEGMENT_MS = 250;
|
||||
const UI_UPDATE_INTERVAL_MS = 33;
|
||||
const PROGRESS_EPSILON = 0.0001;
|
||||
const PROGRESS_EPSILON = 0.001;
|
||||
|
||||
function normalizeDuration(
|
||||
duration: number | null | undefined,
|
||||
fallback: number,
|
||||
) {
|
||||
): number {
|
||||
if (
|
||||
typeof duration !== "number" ||
|
||||
!Number.isFinite(duration) ||
|
||||
@@ -21,7 +22,7 @@ function normalizeDuration(
|
||||
return Math.max(MIN_SEGMENT_MS, Math.round(duration));
|
||||
}
|
||||
|
||||
function sumDurations(durations: number[], end: number) {
|
||||
function sumDurations(durations: number[], end: number): number {
|
||||
let total = 0;
|
||||
for (let i = 0; i < end; i++) total += durations[i] ?? 0;
|
||||
return total;
|
||||
@@ -39,6 +40,26 @@ interface UseImageCarouselProps {
|
||||
segmentMs?: number;
|
||||
}
|
||||
|
||||
export interface UseImageCarouselReturn {
|
||||
idx: number;
|
||||
setIdx: (idx: number) => void;
|
||||
segProgress: number;
|
||||
segProgressRef: RefObject<number>;
|
||||
segmentDurations: number[];
|
||||
totalDurationMs: number;
|
||||
mediaSyncToken: number;
|
||||
segStartRef: RefObject<number | null>;
|
||||
idxRef: RefObject<number>;
|
||||
failedAnimatedMap: Record<string, boolean>;
|
||||
setSegmentDuration: (imageId: string, durationMs: number) => void;
|
||||
markMediaReady: (imageId: string) => void;
|
||||
markAnimatedFailed: (imageId: string) => void;
|
||||
handleAnimatedProgress: (imageId: string, progress: number) => void;
|
||||
handleAnimatedEnded: (imageId: string) => void;
|
||||
goToIndex: (index: number, segmentProgress?: number) => void;
|
||||
seekTo: (ratio: number) => void;
|
||||
}
|
||||
|
||||
export function useImageCarousel({
|
||||
images,
|
||||
isPlaying,
|
||||
@@ -48,13 +69,19 @@ export function useImageCarousel({
|
||||
audioRef,
|
||||
setProgress,
|
||||
segmentMs = 5000,
|
||||
}: UseImageCarouselProps) {
|
||||
}: UseImageCarouselProps): UseImageCarouselReturn {
|
||||
const router = useRouter();
|
||||
const [idx, setIdx] = useState(0);
|
||||
const [segProgress, setSegProgress] = useState(0);
|
||||
const [durationOverrides, setDurationOverrides] = useState<
|
||||
Record<string, number>
|
||||
>({});
|
||||
const [readyMediaMap, setReadyMediaMap] = useState<Record<string, boolean>>(
|
||||
{},
|
||||
);
|
||||
const [failedAnimatedMap, setFailedAnimatedMap] = useState<
|
||||
Record<string, boolean>
|
||||
>({});
|
||||
const [mediaSyncToken, setMediaSyncToken] = useState(0);
|
||||
|
||||
const segStartRef = useRef<number | null>(null);
|
||||
@@ -85,7 +112,7 @@ export function useImageCarousel({
|
||||
);
|
||||
|
||||
const syncProgress = useCallback(
|
||||
(index: number, segmentProgress: number, force = false) => {
|
||||
(index: number, segmentProgress: number, force = false): void => {
|
||||
const segmentDuration = segmentDurations[index] ?? fallbackDuration;
|
||||
const completedMs = sumDurations(segmentDurations, index);
|
||||
const totalProgress =
|
||||
@@ -116,7 +143,7 @@ export function useImageCarousel({
|
||||
);
|
||||
|
||||
const setSegmentDuration = useCallback(
|
||||
(imageId: string, durationMs: number) => {
|
||||
(imageId: string, durationMs: number): void => {
|
||||
if (!Number.isFinite(durationMs) || durationMs <= 0) return;
|
||||
const normalizedDuration = normalizeDuration(
|
||||
durationMs,
|
||||
@@ -131,8 +158,95 @@ export function useImageCarousel({
|
||||
[fallbackDuration],
|
||||
);
|
||||
|
||||
const markMediaReady = useCallback((imageId: string): void => {
|
||||
setReadyMediaMap((current) => {
|
||||
if (current[imageId]) return current;
|
||||
return { ...current, [imageId]: true };
|
||||
});
|
||||
}, []);
|
||||
|
||||
const markAnimatedFailed = useCallback((imageId: string): void => {
|
||||
setFailedAnimatedMap((current) => {
|
||||
if (current[imageId]) return current;
|
||||
return { ...current, [imageId]: true };
|
||||
});
|
||||
setReadyMediaMap((current) => {
|
||||
if (current[imageId]) return current;
|
||||
return { ...current, [imageId]: true };
|
||||
});
|
||||
}, []);
|
||||
|
||||
const advanceSegment = useCallback(
|
||||
(fromIndex: number): void => {
|
||||
if (!images.length || idxRef.current !== fromIndex) return;
|
||||
|
||||
const now = performance.now();
|
||||
|
||||
if (loopMode === "single") {
|
||||
segStartRef.current = now;
|
||||
lastUiUpdateRef.current = now;
|
||||
syncProgress(fromIndex, 0, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (fromIndex >= images.length - 1) {
|
||||
if (loopMode === "sequential" && neighbors?.next) {
|
||||
router.push(`/aweme/${neighbors.next.aweme_id}`);
|
||||
return;
|
||||
}
|
||||
idxRef.current = 0;
|
||||
setIdx(0);
|
||||
segStartRef.current = now;
|
||||
lastUiUpdateRef.current = now;
|
||||
syncProgress(0, 0, true);
|
||||
if (images.length === 1) {
|
||||
setMediaSyncToken((token) => token + 1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const nextIndex = fromIndex + 1;
|
||||
idxRef.current = nextIndex;
|
||||
setIdx(nextIndex);
|
||||
segStartRef.current = now;
|
||||
lastUiUpdateRef.current = now;
|
||||
syncProgress(nextIndex, 0, true);
|
||||
},
|
||||
[images.length, loopMode, neighbors?.next, router, syncProgress],
|
||||
);
|
||||
|
||||
const handleAnimatedProgress = useCallback(
|
||||
(imageId: string, progress: number): void => {
|
||||
const currentImage = images[idxRef.current];
|
||||
if (!currentImage || currentImage.id !== imageId) return;
|
||||
|
||||
const now = performance.now();
|
||||
const clamped = Math.max(0, Math.min(1, progress));
|
||||
const wrapped = clamped < segProgressRef.current - 0.2;
|
||||
|
||||
if (
|
||||
wrapped ||
|
||||
clamped >= 0.995 ||
|
||||
now - lastUiUpdateRef.current >= UI_UPDATE_INTERVAL_MS
|
||||
) {
|
||||
lastUiUpdateRef.current = now;
|
||||
syncProgress(idxRef.current, clamped, wrapped);
|
||||
}
|
||||
},
|
||||
[images, syncProgress],
|
||||
);
|
||||
|
||||
const handleAnimatedEnded = useCallback(
|
||||
(imageId: string): void => {
|
||||
const currentImage = images[idxRef.current];
|
||||
if (!currentImage || currentImage.id !== imageId) return;
|
||||
advanceSegment(idxRef.current);
|
||||
},
|
||||
[advanceSegment, images],
|
||||
);
|
||||
|
||||
const goToIndex = useCallback(
|
||||
(index: number, segmentProgress = 0) => {
|
||||
(index: number, segmentProgress = 0): void => {
|
||||
if (!images.length) return;
|
||||
|
||||
const nextIndex = Math.max(0, Math.min(images.length - 1, index));
|
||||
@@ -151,7 +265,7 @@ export function useImageCarousel({
|
||||
);
|
||||
|
||||
const seekTo = useCallback(
|
||||
(ratio: number) => {
|
||||
(ratio: number): void => {
|
||||
if (!images.length || totalDurationMs <= 0) return;
|
||||
|
||||
const clampedRatio = Math.max(0, Math.min(1, ratio));
|
||||
@@ -197,25 +311,9 @@ export function useImageCarousel({
|
||||
idxRef.current = idx;
|
||||
}, [idx]);
|
||||
|
||||
// 切换作品或图片集合变化时重置所有轮播状态
|
||||
useEffect(() => {
|
||||
const validIds = new Set(images.map((img) => img.id));
|
||||
setDurationOverrides((current) => {
|
||||
let changed = false;
|
||||
const next: Record<string, number> = {};
|
||||
|
||||
for (const [id, duration] of Object.entries(current)) {
|
||||
if (validIds.has(id)) {
|
||||
next[id] = duration;
|
||||
} else {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return changed ? next : current;
|
||||
});
|
||||
}, [images]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!imageKey) return;
|
||||
idxRef.current = 0;
|
||||
setIdx(0);
|
||||
segStartRef.current = null;
|
||||
@@ -223,6 +321,9 @@ export function useImageCarousel({
|
||||
totalProgressRef.current = 0;
|
||||
setSegProgress(0);
|
||||
setProgress(0);
|
||||
setDurationOverrides({});
|
||||
setReadyMediaMap({});
|
||||
setFailedAnimatedMap({});
|
||||
setMediaSyncToken((token) => token + 1);
|
||||
}, [imageKey, setProgress]);
|
||||
|
||||
@@ -239,90 +340,77 @@ export function useImageCarousel({
|
||||
}, [audioRef, isPlaying, volume]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = audioRef.current;
|
||||
return () => {
|
||||
audioRef.current?.pause();
|
||||
releaseMediaElement(el);
|
||||
};
|
||||
}, [audioRef]);
|
||||
|
||||
// 自动切页
|
||||
// 静态图自动切页(仅在当前静态图已加载完成后开始计时;动图由 <video> 自身进度与 onEnded 驱动)
|
||||
const currentImage = images[idx];
|
||||
const isCurrentAnimated =
|
||||
Boolean(currentImage?.animated) &&
|
||||
!failedAnimatedMap[currentImage?.id ?? ""];
|
||||
const isCurrentStaticReady = currentImage
|
||||
? Boolean(readyMediaMap[currentImage.id])
|
||||
: false;
|
||||
|
||||
useEffect(() => {
|
||||
if (!images?.length || !segmentDurations.length || totalDurationMs <= 0)
|
||||
if (!images?.length || !segmentDurations.length || totalDurationMs <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 当前页为正常动图时,交由 ImageCarousel 内 <video> 的真实播放进度和 ended 事件推进
|
||||
if (isCurrentAnimated) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 静态图尚未加载完成或处于暂停态时,冻结分段进度,避免未加载完就偷跑进度裁切展示时长
|
||||
if (!isPlaying || !isCurrentStaticReady) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = performance.now();
|
||||
const currentSegmentDuration =
|
||||
segmentDurations[idxRef.current] ?? fallbackDuration;
|
||||
const currentSegmentDuration = segmentDurations[idx] ?? fallbackDuration;
|
||||
segStartRef.current = now - segProgressRef.current * currentSegmentDuration;
|
||||
lastUiUpdateRef.current = now;
|
||||
|
||||
if (!isPlaying) return;
|
||||
|
||||
const tick = () => {
|
||||
const tick = (): void => {
|
||||
if (!images?.length) return;
|
||||
|
||||
const ts = performance.now();
|
||||
const start = segStartRef.current ?? ts;
|
||||
const activeIdx = idxRef.current;
|
||||
const duration = segmentDurations[activeIdx] ?? fallbackDuration;
|
||||
const elapsed = ts - start;
|
||||
|
||||
let start = segStartRef.current!;
|
||||
let localIdx = idxRef.current;
|
||||
|
||||
let elapsed = ts - start;
|
||||
let currentSegmentDuration =
|
||||
segmentDurations[localIdx] ?? fallbackDuration;
|
||||
|
||||
while (elapsed >= currentSegmentDuration) {
|
||||
if (loopMode === "single") {
|
||||
elapsed %= currentSegmentDuration;
|
||||
break;
|
||||
}
|
||||
|
||||
elapsed -= currentSegmentDuration;
|
||||
|
||||
if (localIdx >= images.length - 1) {
|
||||
if (loopMode === "sequential" && neighbors?.next) {
|
||||
router.push(`/aweme/${neighbors.next.aweme_id}`);
|
||||
return;
|
||||
}
|
||||
localIdx = 0;
|
||||
} else {
|
||||
localIdx = localIdx + 1;
|
||||
}
|
||||
|
||||
currentSegmentDuration = segmentDurations[localIdx] ?? fallbackDuration;
|
||||
}
|
||||
segStartRef.current = ts - elapsed;
|
||||
|
||||
const indexChanged = localIdx !== idxRef.current;
|
||||
if (indexChanged) {
|
||||
idxRef.current = localIdx;
|
||||
setIdx(localIdx);
|
||||
if (elapsed >= duration) {
|
||||
advanceSegment(activeIdx);
|
||||
return;
|
||||
}
|
||||
|
||||
const localSeg = Math.max(
|
||||
0,
|
||||
Math.min(1, elapsed / currentSegmentDuration),
|
||||
);
|
||||
|
||||
if (
|
||||
indexChanged ||
|
||||
ts - lastUiUpdateRef.current >= UI_UPDATE_INTERVAL_MS
|
||||
) {
|
||||
const localSeg = Math.max(0, Math.min(1, elapsed / duration));
|
||||
if (ts - lastUiUpdateRef.current >= UI_UPDATE_INTERVAL_MS) {
|
||||
lastUiUpdateRef.current = ts;
|
||||
syncProgress(localIdx, localSeg, indexChanged);
|
||||
syncProgress(activeIdx, localSeg, false);
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
timerRef.current = window.setInterval(tick, UI_UPDATE_INTERVAL_MS);
|
||||
return () => {
|
||||
if (timerRef.current) window.clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
if (timerRef.current !== null) {
|
||||
window.clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [
|
||||
advanceSegment,
|
||||
fallbackDuration,
|
||||
idx,
|
||||
images,
|
||||
isCurrentAnimated,
|
||||
isCurrentStaticReady,
|
||||
isPlaying,
|
||||
loopMode,
|
||||
neighbors?.next,
|
||||
router,
|
||||
segmentDurations,
|
||||
syncProgress,
|
||||
totalDurationMs,
|
||||
@@ -332,12 +420,18 @@ export function useImageCarousel({
|
||||
idx,
|
||||
setIdx,
|
||||
segProgress,
|
||||
segProgressRef,
|
||||
segmentDurations,
|
||||
totalDurationMs,
|
||||
mediaSyncToken,
|
||||
segStartRef,
|
||||
idxRef,
|
||||
failedAnimatedMap,
|
||||
setSegmentDuration,
|
||||
markMediaReady,
|
||||
markAnimatedFailed,
|
||||
handleAnimatedProgress,
|
||||
handleAnimatedEnded,
|
||||
goToIndex,
|
||||
seekTo,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user