fix: 쇼츠 재생 아이콘을 플레이어가 보낸 재생 상태로만 판단 — 늦은 자동재생과 누르기가 겹쳐도 어긋나지 않게, 카드 아이콘은 플레이어 위에, 넘기기 판은 재생 명령이 막힌 때만 치움

This commit is contained in:
minaChoi committed 2026-10-26 16:18:09 +09:00
1 parent 2fd6fcbd06
commit 61023d090e
1 file changed
+66 -20
+66 -20
View File
@@ -46,8 +46,25 @@ function command(frame: HTMLIFrameElement | null | undefined, func: Func, args:
}
const PLAYING = 1
// 이만큼 지나도 재생이 시작되지 않으면(자동재생이 막힌 웹뷰) 플레이어를 보이고 재생 아이콘을 띄워 직접 누르게 한다
const BUFFERING = 3
// 이만큼 지나도 재생되지 않으면(자동재생이 막힌 웹뷰) 재생 아이콘을 띄운다
const STALL_MS = 2000
// 아이콘을 눌러 보낸 재생 명령도 이만큼 안에 재생이 안 되면 웹뷰가 막은 것 → 플레이어를 직접 누르게 한다
const DIRECT_MS = 1500
/** 플레이어가 보낸 재생 상태 (onStateChange·infoDelivery). 없으면 undefined */
function playerState(e: MessageEvent): number | undefined {
if (e.origin !== YT_ORIGIN || typeof e.data !== 'string') return undefined
try {
const msg = JSON.parse(e.data) as { event?: string; info?: number | { playerState?: number } }
if (msg.event === 'onStateChange' && typeof msg.info === 'number') return msg.info
return typeof msg.info === 'object' ? msg.info?.playerState : undefined
} catch {
return undefined
}
}
const isRunning = (state: number | undefined) => state === PLAYING || state === BUFFERING
// 마우스로 이만큼 끌면 다음·이전 영상으로 넘긴다
const SWIPE_PX = 30
@@ -95,12 +112,29 @@ export function ShortsRail() {
}
function ShortCard({ s, playing }: { s: ShortItem; playing: boolean }) {
const frame = useRef<HTMLIFrameElement>(null)
const [state, setState] = useState<number>()
useEffect(() => {
if (!playing) return
const onMessage = (e: MessageEvent) => {
if (e.source !== frame.current?.contentWindow) return
const next = playerState(e)
if (next !== undefined) setState(next)
}
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [playing])
return (
<Link to={`/shorts/${s.id}`} aria-label={`${s.title} 보기`} className="relative block aspect-[9/16] w-[120px] cursor-pointer overflow-hidden rounded-xl bg-[#1d2233] p-0 text-left text-white">
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" loading="lazy" className="absolute inset-0 size-full object-cover" />
<PlayIcon />
{playing && (
<iframe
ref={frame}
onLoad={(e) => {
setState(undefined)
e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN)
}}
src={embed(s.id)}
title={s.title}
allow="autoplay; encrypted-media; picture-in-picture"
@@ -109,6 +143,7 @@ function ShortCard({ s, playing }: { s: ShortItem; playing: boolean }) {
style={{ width: PLAYER_W, height: (PLAYER_W * 16) / 9, transform: `translate(-50%, -50%) scale(${SCALE})` }}
/>
)}
{!(playing && isRunning(state)) && <PlayIcon />}
<span className="b-keep-bg absolute inset-0 bg-[linear-gradient(180deg,transparent_55%,rgba(0,0,0,.65))]" aria-hidden="true" />
<span className="absolute inset-x-2 bottom-2 line-clamp-3 text-[12px] leading-[1.3] font-bold">{s.title}</span>
</Link>
@@ -145,11 +180,19 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
const frames = useRef(new Map<number, HTMLIFrameElement>())
const atRef = useRef(start)
const soundRef = useRef(false)
// 누르기로 멈춘 상태. 다른 영상으로 넘어가면 다시 재생 중으로
const paused = useRef(false)
// 보이는 영상이 저절로 재생되지 않음
// 플레이어마다 마지막으로 받은 재생 상태. 재생 중인지는 이것만 보고 정한다
const [states, setStates] = useState<ReadonlyMap<number, number>>(new Map())
const statesRef = useRef(states)
useEffect(() => {
statesRef.current = states
}, [states])
const running = isRunning(states.get(at))
// 들어오고 STALL_MS 가 지난 영상 (그때도 재생 중이 아니면 재생 아이콘)
const [stalledAt, setStalledAt] = useState(-1)
const stalledHere = stalledAt === at && !ready.has(at)
// 재생 명령이 막혀 플레이어를 직접 누르게 한 영상
const [directAt, setDirectAt] = useState(-1)
const direct = directAt === at
const showPlay = stalledAt === at && !running
// 처음 한 번: 시작 영상으로 맞추고, 뒤 페이지 스크롤을 잠근다
const startRef = useRef(start)
@@ -187,16 +230,12 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
// 미리 띄운 영상이 재생되기 시작하면(첫 장면을 받음) 보이는 영상이 아닐 때 멈추고 처음으로
useEffect(() => {
const onMessage = (e: MessageEvent) => {
if (e.origin !== YT_ORIGIN || typeof e.data !== 'string') return
let msg: { info?: { playerState?: number } }
try {
msg = JSON.parse(e.data)
} catch {
return
}
if (msg.info?.playerState !== PLAYING) return
const state = playerState(e)
if (state === undefined) return
for (const [i, f] of frames.current) {
if (f.contentWindow !== e.source) continue
setStates((m) => (m.get(i) === state ? m : new Map(m).set(i, state)))
if (state !== PLAYING) continue
setReady((r) => (r.has(i) ? r : new Set(r).add(i)))
if (i === atRef.current) continue
command(f, 'pauseVideo')
@@ -211,7 +250,6 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
useEffect(() => {
if (atRef.current !== at) moved(items[at])
atRef.current = at
paused.current = false
for (const [i, f] of frames.current) {
if (i === at) {
command(f, soundRef.current ? 'unMute' : 'mute')
@@ -233,9 +271,17 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
const drag = useRef<{ y: number; top: number; moved: boolean } | null>(null)
const lastPointer = useRef('')
const [dragging, setDragging] = useState(false)
const directTimer = useRef(0)
useEffect(() => () => window.clearTimeout(directTimer.current), [])
const togglePause = () => {
paused.current = !paused.current
command(frames.current.get(atRef.current), paused.current ? 'pauseVideo' : 'playVideo')
const i = atRef.current
const frame = frames.current.get(i)
if (isRunning(statesRef.current.get(i))) return command(frame, 'pauseVideo')
command(frame, 'playVideo')
window.clearTimeout(directTimer.current)
directTimer.current = window.setTimeout(() => {
if (atRef.current === i && !isRunning(statesRef.current.get(i))) setDirectAt(i)
}, DIRECT_MS)
}
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
lastPointer.current = e.pointerType
@@ -325,7 +371,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', !ready.has(i) && !(i === at && stalledHere) && 'opacity-0')}
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', !ready.has(i) && !(i === at && direct) && 'opacity-0')}
/>
)}
<div
@@ -338,9 +384,9 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
setDragging(false)
}}
onClick={() => lastPointer.current !== 'mouse' && togglePause()}
className={cx('absolute inset-0 touch-pan-y select-none', dragging ? 'cursor-grabbing' : 'cursor-grab', i === at && stalledHere && 'pointer-events-none')}
className={cx('absolute inset-0 touch-pan-y select-none', dragging ? 'cursor-grabbing' : 'cursor-grab', i === at && direct && !running && 'pointer-events-none')}
/>
{i === at && stalledHere && <PlayIcon />}
{i === at && showPlay && <PlayIcon />}
</div>
</div>
))}