fix: 토스판 쇼츠도 릴스처럼 다음 영상을 미리 받아 둠 — 다음 영상은 멈춘 채 띄워 두고 넘어오면 재생, 지난 영상은 내려 소리가 겹치지 않게

This commit is contained in:
minaChoi committed 2026-10-27 19:22:26 +09:00
1 parent 4875ea4333
commit 7ffeecbb4f
1 file changed
+40 -15
+40 -15
View File
@@ -43,9 +43,9 @@ const PLAIN = IS_TOSS
// 토스는 재생 상태가 안 오므로, 플레이어 문서가 뜨고 이만큼 지나면 첫 장면이 나왔다고 보고 표지를 걷는다 (그 전엔 플레이어의 검은 화면 대신 표지)
const PLAIN_SHOW_MS = 1000
function embed(id: string, plain = false) {
function embed(id: string, plain = false, autoplay = true) {
const q = new URLSearchParams({
autoplay: '1', mute: plain ? '0' : '1', playsinline: '1', loop: '1', playlist: id, controls: plain ? '1' : '0', rel: '0', modestbranding: '1',
autoplay: autoplay ? '1' : '0', mute: plain ? '0' : '1', playsinline: '1', loop: '1', playlist: id, controls: plain ? '1' : '0', rel: '0', modestbranding: '1',
enablejsapi: '1', origin: window.location.origin,
})
return `${YT_ORIGIN}/embed/${id}?${q}`
@@ -153,10 +153,24 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
const tabH = useTabBarHeight()
// 첫 장면을 받은 플레이어. 그 전엔 플레이어의 검은 화면 대신 표지를 보인다
const [ready, setReady] = useState<ReadonlySet<number>>(new Set())
// 토스: 표지를 걷은 플레이어 번호 (하나만 띄우므로 하나)
const [plainShownAt, setPlainShownAt] = useState(-1)
const plainTimer = useRef(0)
useEffect(() => () => window.clearTimeout(plainTimer.current), [])
// 토스: 표지를 걷은 플레이어들. 다음 영상도 미리 띄워 두므로 여럿
const [plainShown, setPlainShown] = useState<ReadonlySet<number>>(new Set())
const plainTimers = useRef(new Set<number>())
useEffect(() => {
const timers = plainTimers.current
return () => timers.forEach((t) => window.clearTimeout(t))
}, [])
// 토스: 플레이어마다 처음 띄울 때 지금 영상이면 자동재생, 미리 받아 두는 다음 영상은 멈춘 채로. 한 번 정하면 주소가 바뀌어 다시 받지 않게 기억한다
const [plainAutoplay, setPlainAutoplay] = useState<ReadonlyMap<number, boolean>>(() => new Map([[start, true], [start + 1, false]]))
/** 지금 영상이 n 으로 바뀔 때: 새로 띄울 지금 영상은 자동재생, 다음 영상은 멈춘 채로 (이미 띄운 것은 그대로) */
const keepAutoplay = (n: number) =>
setPlainAutoplay((m) => {
const next = new Map([...m].filter(([i]) => i === n || i === n + 1))
if (!next.has(n)) next.set(n, true)
if (!next.has(n + 1)) next.set(n + 1, false)
return next
})
const autoplayOnMount = (i: number) => plainAutoplay.get(i) ?? i === at
const frames = useRef(new Map<number, HTMLIFrameElement>())
const atRef = useRef(start)
const soundRef = useRef(false)
@@ -188,7 +202,12 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
if (!box) return
const io = new IntersectionObserver(
(entries) => {
for (const e of entries) if (e.isIntersecting) setAt(Number((e.target as HTMLElement).dataset.i))
for (const e of entries) {
if (!e.isIntersecting) continue
const n = Number((e.target as HTMLElement).dataset.i)
setAt(n)
if (PLAIN) keepAutoplay(n)
}
},
{ root: box, threshold: 0.6 },
)
@@ -224,14 +243,14 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
if (atRef.current !== at) moved(items[at])
atRef.current = at
paused.current = false
if (PLAIN) return
for (const [i, f] of frames.current) {
// 토스는 소리를 켠 채 유튜브 기본 플레이어로 두므로 재생·멈춤만 (소리 명령 없음)
if (i === at) {
command(f, soundRef.current ? 'unMute' : 'mute')
if (!PLAIN) command(f, soundRef.current ? 'unMute' : 'mute')
command(f, 'playVideo')
} else {
command(f, 'pauseVideo')
command(f, 'mute')
if (!PLAIN) command(f, 'mute')
}
}
}, [at, items])
@@ -330,20 +349,26 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
<div key={s.id} data-i={i} className="relative grid h-full snap-start place-items-center">
<div className="relative" style={FIT}>
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" className="absolute inset-0 size-full object-cover" />
{(PLAIN ? i === at : Math.abs(i - at) <= 1) && (
{/* 릴스처럼 다음 영상을 미리 받아 둔다. 토스는 재생 상태가 안 와 멈추게 할 수 없을 수 있어, 지난 영상은 내려 소리가 겹치지 않게 지금·다음만 */}
{(PLAIN ? i === at || i === at + 1 : Math.abs(i - at) <= 1) && (
<iframe
ref={(f) => {
if (f) frames.current.set(i, f)
else frames.current.delete(i)
}}
src={embed(s.id, PLAIN)}
src={embed(s.id, PLAIN, !PLAIN || autoplayOnMount(i))}
title={s.title}
allow="autoplay; encrypted-media; picture-in-picture"
// 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다
onLoad={(e) => {
if (PLAIN) {
window.clearTimeout(plainTimer.current)
plainTimer.current = window.setTimeout(() => setPlainShownAt(i), PLAIN_SHOW_MS)
const t = window.setTimeout(() => {
plainTimers.current.delete(t)
setPlainShown((r) => (r.has(i) ? r : new Set(r).add(i)))
}, PLAIN_SHOW_MS)
plainTimers.current.add(t)
// 미리 받아 둔 영상으로 넘어온 뒤 뜬 경우엔 바로 재생
if (i === atRef.current) command(e.currentTarget, 'playVideo')
}
e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN)
// 앞뒤 밖으로 밀려나 내려갔다 다시 뜬 플레이어는 첫 장면을 새로 받을 때까지 다시 숨긴다
@@ -354,7 +379,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
return next
})
}}
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', (PLAIN ? plainShownAt !== i : !ready.has(i)) && 'opacity-0')}
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', (PLAIN ? !plainShown.has(i) : !ready.has(i)) && 'opacity-0')}
/>
)}
{!PLAIN && (