import { useQuery } from '@tanstack/react-query' import { type CSSProperties, type PointerEvent as ReactPointerEvent, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react' import { Link, useNavigate, useParams } from 'react-router' import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import type { ShortItem } from '@nalssigak/shared/api/client' import { IS_TOSS } from '../lib/platform' import { cx } from '../lib/utils' import { CloseIcon } from './svg' import { Rail, Skel, SkelRail, TAP44 } from './ui' import { track } from '../lib/analytics' // 유튜브는 플레이어가 200×200 이상이어야 해서, 카드 안 미리보기는 200px 너비로 띄우고 줄여 보인다. // 위 로고·아래 제목 줄이 작은 카드에서 겹쳐 보이지 않게 가운데를 1.4배로 키워 위아래를 잘라 낸다 const CARD_W = 120 const PLAYER_W = 200 const SCALE = (CARD_W / PLAYER_W) * 1.4 // 쇼츠 페이지의 영상 칸: 위 헤더(54px)·버튼 줄(48px)과 아래 탭 바(--shorts-tab) 사이 높이와 화면 너비 안에 9:16으로 맞춘다 const FIT = { width: 'min(100vw, calc((100dvh - env(safe-area-inset-top, 0px) - 54px - 48px - var(--shorts-tab, 0px)) * 9 / 16))', aspectRatio: '9 / 16' } /** 아래 탭 바가 가리는 높이: 탭 바 위로 솟은 가운데 홈 동그라미까지 (기기마다 안전 영역이 달라 실제로 잰다) */ function useTabBarHeight() { const [h, setH] = useState(0) useLayoutEffect(() => { const nav = document.querySelector('nav.b-tabbar') if (!nav) return const measure = () => { const bar = nav.getBoundingClientRect() const bump = nav.querySelector('.b-tab-main > *')?.getBoundingClientRect().top ?? bar.top setH(Math.round(bar.bottom - Math.min(bar.top, bump))) } const ro = new ResizeObserver(measure) ro.observe(nav) return () => ro.disconnect() }, []) return h } const YT_ORIGIN = 'https://www.youtube-nocookie.com' // 토스 웹뷰에는 플레이어가 보내는 재생 상태가 오지 않는다. 그래서 토스는 첫 장면이 나왔는지를 시간으로 보고 표지를 걷는다 (나머지는 웹과 같다) const PLAIN = IS_TOSS // 토스는 재생 상태가 안 오므로, 플레이어 문서가 뜨고 이만큼 지나면 첫 장면이 나왔다고 보고 표지를 걷는다 (그 전엔 플레이어의 검은 화면 대신 표지) const PLAIN_SHOW_MS = 1000 function embed(id: string) { const q = new URLSearchParams({ autoplay: '1', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: '0', rel: '0', modestbranding: '1', enablejsapi: '1', origin: window.location.origin, }) return `${YT_ORIGIN}/embed/${id}?${q}` } type Func = 'playVideo' | 'seekTo' | 'mute' | 'unMute' /** 이미 띄운 플레이어에 명령 (IFrame API 메시지) */ function command(frame: HTMLIFrameElement | null | undefined, func: Func, args: unknown[] = []) { frame?.contentWindow?.postMessage(JSON.stringify({ event: 'command', func, args }), YT_ORIGIN) } const PLAYING = 1 // 마우스로 이만큼 끌면 다음·이전 영상으로 넘긴다 const SWIPE_PX = 30 /** 화면에 보이는 동안만 true */ function useVisible(threshold = 0.5) { const [el, ref] = useState(null) const [visible, setVisible] = useState(false) useEffect(() => { if (!el) return const io = new IntersectionObserver(([e]) => setVisible(e.isIntersecting), { threshold }) io.observe(el) return () => io.disconnect() }, [el, threshold]) return [ref, visible] as const } // 마우스를 올릴 수 있는 기기(데스크톱)인지. 터치 기기는 올리기가 없어 첫 터치 뒤 첫 카드를 자동 재생한다 const CAN_HOVER = typeof window !== 'undefined' && window.matchMedia('(hover: hover) and (pointer: fine)').matches // 마우스가 줄 위를 지나가기만 할 땐 플레이어를 받지 않게, 이만큼 머물러야 재생한다 const HOVER_PLAY_MS = 200 // scroll 은 넣지 않는다: 브라우저가 스크롤 위치를 되돌릴 때도 나서 조작으로 볼 수 없다 const TOUCH_EVENTS = ['pointerdown', 'touchstart', 'keydown'] as const // 한 번 조작했으면 다른 화면에 다녀와도 그대로 둔다 let touchedOnce = false /** 터치 기기에서 사용자가 화면을 처음 조작(누르기·키)한 뒤부터 true. 유튜브 플레이어(약 850KB)를 첫 화면 로드에서 빼려고 쓴다 */ function useTouched(enabled: boolean) { const [touched, setTouched] = useState(touchedOnce) useEffect(() => { if (!enabled || touchedOnce) return const opts = { capture: true, passive: true } const off = () => TOUCH_EVENTS.forEach((t) => window.removeEventListener(t, on, opts)) const on = () => { touchedOnce = true setTouched(true) off() } TOUCH_EVENTS.forEach((t) => window.addEventListener(t, on, opts)) return off }, [enabled]) return touched } /** * 오늘 화면 히어로 아래 쇼츠 줄: 누르면 쇼츠 페이지(/shorts/영상ID)에서 위아래로 넘겨 본다. * 줄에서는 소리 없이 미리 보인다 — 데스크톱은 마우스를 올린 카드, 터치 기기는 첫 터치 뒤 첫 카드 */ export function ShortsRail() { const q = useQuery(listShortsOptions()) const items = q.data?.items ?? [] const [ref, visible] = useVisible() const touched = useTouched(!CAN_HOVER && !IS_TOSS) if (q.isPending) { return ( ) } if (!items.length) return null return (
{items.map((s, i) => ( // 토스 앱 웹뷰는 유튜브 플레이어가 무거워, 줄에선 표지만 보이고 누르면 재생 ))}
) } /** auto: 올리지 않아도 재생 (터치 기기의 첫 카드) */ function ShortCard({ s, first, auto }: { s: ShortItem; first: boolean; auto: boolean }) { const [hover, setHover] = useState(false) const hoverTimer = useRef(0) useEffect(() => () => window.clearTimeout(hoverTimer.current), []) const enter = () => { hoverTimer.current = window.setTimeout(() => setHover(true), HOVER_PLAY_MS) } const leave = () => { window.clearTimeout(hoverTimer.current) setHover(false) } const playing = auto || hover // 재생이 시작된 뒤에만 플레이어를 보인다: 자동재생이 막히면(아이폰 절전 등) 유튜브 재생 버튼 대신 표지 그대로 const [started, setStarted] = useState(false) const frame = useRef(null) // 플레이어는 반복 재생하며 재생 상태를 여러 번 보내고 마우스도 여러 번 올리므로, 미리보기 이벤트는 카드마다 한 번만 const previewSent = useRef(false) useEffect(() => { if (!playing) return const onMessage = (e: MessageEvent) => { if (e.origin !== YT_ORIGIN || typeof e.data !== 'string' || e.source !== frame.current?.contentWindow) return try { if ((JSON.parse(e.data) as { info?: { playerState?: number } }).info?.playerState !== PLAYING) return setStarted(true) if (previewSent.current) return previewSent.current = true track('shorts_preview', { video_id: s.id, trigger: auto ? 'auto' : 'hover' }) } catch { return } } window.addEventListener('message', onMessage) return () => { window.removeEventListener('message', onMessage) // 플레이어를 내렸다 다시 띄우면 첫 장면을 받을 때까지 다시 표지 setStarted(false) } }, [playing, auto, s.id]) return ( {/* 첫 카드 표지는 첫 화면에서 가장 큰 그림(LCP)이라 미루지 않고 먼저 받는다 */} {playing && (