fix: 토스판 쇼츠는 유튜브 기본 플레이어로 자동재생 — 토스 웹뷰엔 플레이어 재생 상태가 안 와서 숨기기·명령·재생 아이콘을 쓰지 않고, 소리 켠 채 재생(막히면 유튜브 재생 버튼), 넘기기는 이전·다음 버튼. 웹은 그대로
This commit is contained in:
1 parent
21bfa2a3ff
commit
b240ecb180
2 files changed
+23
-89
No files matched your search
+22
-89
@@ -31,12 +31,13 @@ function useTabBarHeight() {
|
||||
|
||||
const YT_ORIGIN = 'https://www.youtube-nocookie.com'
|
||||
|
||||
// 토스 웹뷰에서는 플레이어가 보내는 재생 상태가 오지 않아, 숨기기·자동재생 없이 유튜브 기본 플레이어(재생 버튼 포함)를 그대로 쓴다
|
||||
// 토스 웹뷰에는 플레이어가 보내는 재생 상태가 오지 않아, 쇼츠 페이지는 플레이어를 숨기거나 명령하지 않고 유튜브 기본 조작(재생 버튼)과 소리를 켠 채 그대로 보인다.
|
||||
// 영상 위 터치는 유튜브가 가져가므로 넘기기는 버튼으로
|
||||
const PLAIN = IS_TOSS
|
||||
|
||||
function embed(id: string) {
|
||||
function embed(id: string, plain = false) {
|
||||
const q = new URLSearchParams({
|
||||
autoplay: PLAIN ? '0' : '1', mute: PLAIN ? '0' : '1', playsinline: '1', loop: '1', playlist: id, controls: PLAIN ? '1' : '0', rel: '0', modestbranding: '1',
|
||||
autoplay: '1', 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}`
|
||||
@@ -50,25 +51,6 @@ 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
|
||||
|
||||
@@ -108,7 +90,7 @@ export function ShortsRail() {
|
||||
<section ref={ref} aria-label="날씨각 쇼츠">
|
||||
<Rail label="쇼츠 목록">
|
||||
{items.map((s, i) => (
|
||||
<ShortCard key={s.id} s={s} playing={!PLAIN && i === 0 && visible} />
|
||||
<ShortCard key={s.id} s={s} playing={i === 0 && visible} />
|
||||
))}
|
||||
</Rail>
|
||||
</section>
|
||||
@@ -116,29 +98,11 @@ 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" />
|
||||
{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"
|
||||
@@ -147,7 +111,6 @@ 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>
|
||||
@@ -184,19 +147,8 @@ 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 [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 [directAt, setDirectAt] = useState(-1)
|
||||
const direct = directAt === at
|
||||
const showPlay = stalledAt === at && !running
|
||||
// 누르기로 멈춘 상태. 다른 영상으로 넘어가면 다시 재생 중으로
|
||||
const paused = useRef(false)
|
||||
|
||||
// 처음 한 번: 시작 영상으로 맞추고, 뒤 페이지 스크롤을 잠근다
|
||||
const startRef = useRef(start)
|
||||
@@ -234,12 +186,16 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
|
||||
// 미리 띄운 영상이 재생되기 시작하면(첫 장면을 받음) 보이는 영상이 아닐 때 멈추고 처음으로
|
||||
useEffect(() => {
|
||||
const onMessage = (e: MessageEvent) => {
|
||||
const state = playerState(e)
|
||||
if (state === undefined) return
|
||||
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
|
||||
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')
|
||||
@@ -254,6 +210,8 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
|
||||
useEffect(() => {
|
||||
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')
|
||||
@@ -265,27 +223,14 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
|
||||
}
|
||||
}, [at, items])
|
||||
|
||||
useEffect(() => {
|
||||
const t = window.setTimeout(() => setStalledAt(at), STALL_MS)
|
||||
return () => window.clearTimeout(t)
|
||||
}, [at])
|
||||
|
||||
// 마우스로도 끌어 넘긴다: 영상 위는 유튜브 iframe 이 마우스를 가져가서, 그 위에 투명한 판을 깔고 끈 만큼 목록을 옮긴다.
|
||||
// 손가락은 브라우저 스크롤에 맡기고, 끌지 않고 누르기만 하면 재생·일시정지
|
||||
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 = () => {
|
||||
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)
|
||||
paused.current = !paused.current
|
||||
command(frames.current.get(atRef.current), paused.current ? 'pauseVideo' : 'playVideo')
|
||||
}
|
||||
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
lastPointer.current = e.pointerType
|
||||
@@ -377,7 +322,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
|
||||
if (f) frames.current.set(i, f)
|
||||
else frames.current.delete(i)
|
||||
}}
|
||||
src={embed(s.id)}
|
||||
src={embed(s.id, PLAIN)}
|
||||
title={s.title}
|
||||
allow="autoplay; encrypted-media; picture-in-picture"
|
||||
// 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다
|
||||
@@ -391,7 +336,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 && !ready.has(i) && !(i === at && direct) && 'opacity-0')}
|
||||
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', !PLAIN && !ready.has(i) && 'opacity-0')}
|
||||
/>
|
||||
)}
|
||||
{!PLAIN && (
|
||||
@@ -405,10 +350,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 && direct && !running && 'pointer-events-none')}
|
||||
className={cx('absolute inset-0 touch-pan-y select-none', dragging ? 'cursor-grabbing' : 'cursor-grab')}
|
||||
/>
|
||||
)}
|
||||
{!PLAIN && i === at && showPlay && <PlayIcon />}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
@@ -416,14 +360,3 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 재생 아이콘. 누름은 아래 플레이어가 받는다 */
|
||||
function PlayIcon() {
|
||||
return (
|
||||
<span aria-hidden="true" className="pointer-events-none absolute top-1/2 left-1/2 grid size-12 -translate-1/2 place-items-center rounded-full bg-black/45 text-white">
|
||||
<svg viewBox="0 0 24 24" className="ml-0.5 size-6" fill="currentColor">
|
||||
<path d="M8 5.5v13l10.5-6.5z" />
|
||||
</svg>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user