176 lines
7.5 KiB
TypeScript
176 lines
7.5 KiB
TypeScript
import { useQuery } from '@tanstack/react-query'
|
||
import { useEffect, useRef, useState } from 'react'
|
||
import { listShortsOptions } from '../api/client/@tanstack/react-query.gen'
|
||
import type { ShortItem } from '../api/client'
|
||
import { cx } from '../lib/utils'
|
||
import { Rail, Sec, Skel, SkelRail, TAP44 } from './ui'
|
||
|
||
// 유튜브는 플레이어가 200×200 이상이어야 해서, 카드 안 미리보기는 200px 너비로 띄우고 줄여 보인다.
|
||
// 위 로고·아래 제목 줄이 작은 카드에서 겹쳐 보이지 않게 가운데를 1.4배로 키워 위아래를 잘라 낸다
|
||
const CARD_W = 120
|
||
const PLAYER_W = 200
|
||
const SCALE = (CARD_W / PLAYER_W) * 1.4
|
||
|
||
// 전체 화면 창의 영상 칸: 닫기 줄 아래 남은 높이와 화면 너비 안에 9:16으로 맞춘다
|
||
const FIT = { width: 'min(100vw, calc((100dvh - env(safe-area-inset-top, 0px) - 52px) * 9 / 16))', aspectRatio: '9 / 16' }
|
||
|
||
const YT_ORIGIN = 'https://www.youtube-nocookie.com'
|
||
|
||
function embed(id: string, controls: boolean, autoplay = true) {
|
||
const q = new URLSearchParams({
|
||
autoplay: autoplay ? '1' : '0', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: controls ? '1' : '0', rel: '0', modestbranding: '1',
|
||
enablejsapi: '1', origin: window.location.origin,
|
||
})
|
||
return `${YT_ORIGIN}/embed/${id}?${q}`
|
||
}
|
||
|
||
/** 이미 띄운 플레이어에 재생·일시정지 (IFrame API 메시지) */
|
||
function command(frame: HTMLIFrameElement | null | undefined, func: 'playVideo' | 'pauseVideo') {
|
||
frame?.contentWindow?.postMessage(JSON.stringify({ event: 'command', func, args: [] }), YT_ORIGIN)
|
||
}
|
||
|
||
/** 화면에 보이는 동안만 true */
|
||
function useVisible<T extends Element>(threshold = 0.5) {
|
||
const [el, ref] = useState<T | null>(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
|
||
}
|
||
|
||
/** 오늘 화면 히어로 아래 쇼츠 줄: 첫 카드만 소리 없이 재생, 누르면 전체 화면에서 위아래로 넘겨 본다 */
|
||
export function ShortsRail() {
|
||
const q = useQuery(listShortsOptions())
|
||
const items = q.data?.items ?? []
|
||
const [ref, visible] = useVisible<HTMLElement>()
|
||
const [openAt, setOpenAt] = useState<number | null>(null)
|
||
|
||
if (q.isPending) {
|
||
return (
|
||
<section aria-hidden="true">
|
||
<Sec title="날씨각 쇼츠" />
|
||
<SkelRail>
|
||
{[0, 1, 2, 3].map((i) => (
|
||
<Skel key={i} className="aspect-[9/16] w-[120px] rounded-xl" />
|
||
))}
|
||
</SkelRail>
|
||
</section>
|
||
)
|
||
}
|
||
if (!items.length) return null
|
||
|
||
return (
|
||
<section ref={ref} aria-label="날씨각 쇼츠">
|
||
<Sec title="날씨각 쇼츠" />
|
||
<Rail label="쇼츠 목록">
|
||
{items.map((s, i) => (
|
||
<ShortCard key={s.id} s={s} playing={i === 0 && visible && openAt == null} onOpen={() => setOpenAt(i)} />
|
||
))}
|
||
</Rail>
|
||
{openAt != null && <ShortsViewer items={items} start={openAt} onClose={() => setOpenAt(null)} />}
|
||
</section>
|
||
)
|
||
}
|
||
|
||
function ShortCard({ s, playing, onOpen }: { s: ShortItem; playing: boolean; onOpen: () => void }) {
|
||
return (
|
||
<button type="button" onClick={onOpen} aria-label={`${s.title} 보기`} className="relative 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
|
||
src={embed(s.id, false)}
|
||
title={s.title}
|
||
allow="autoplay; encrypted-media; picture-in-picture"
|
||
tabIndex={-1}
|
||
className="pointer-events-none absolute top-1/2 left-1/2 border-0"
|
||
style={{ width: PLAYER_W, height: (PLAYER_W * 16) / 9, transform: `translate(-50%, -50%) scale(${SCALE})` }}
|
||
/>
|
||
)}
|
||
<span className="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>
|
||
</button>
|
||
)
|
||
}
|
||
|
||
/** 전체 화면 재생 창: 네이티브 <dialog>라 ESC·포커스 가두기가 기본. 넘길 때 새로 띄우며 깜빡이지 않게 앞뒤 영상까지 미리 띄워 두고, 보이는 것만 재생한다 */
|
||
function ShortsViewer({ items, start, onClose }: { items: ShortItem[]; start: number; onClose: () => void }) {
|
||
const dialog = useRef<HTMLDialogElement>(null)
|
||
const list = useRef<HTMLDivElement>(null)
|
||
const [at, setAt] = useState(start)
|
||
const frames = useRef(new Map<number, HTMLIFrameElement>())
|
||
const atRef = useRef(start)
|
||
|
||
useEffect(() => {
|
||
const el = dialog.current
|
||
if (!el) return
|
||
el.showModal()
|
||
list.current?.children[start]?.scrollIntoView({ block: 'start' })
|
||
const root = document.documentElement
|
||
const before = root.style.overflow
|
||
root.style.overflow = 'hidden'
|
||
return () => {
|
||
root.style.overflow = before
|
||
}
|
||
}, [start])
|
||
|
||
useEffect(() => {
|
||
const box = list.current
|
||
if (!box) return
|
||
const io = new IntersectionObserver(
|
||
(entries) => {
|
||
for (const e of entries) if (e.isIntersecting) setAt(Number((e.target as HTMLElement).dataset.i))
|
||
},
|
||
{ root: box, threshold: 0.6 },
|
||
)
|
||
for (const c of box.children) io.observe(c)
|
||
return () => io.disconnect()
|
||
}, [])
|
||
|
||
useEffect(() => {
|
||
atRef.current = at
|
||
for (const [i, f] of frames.current) command(f, i === at ? 'playVideo' : 'pauseVideo')
|
||
}, [at])
|
||
|
||
return (
|
||
<dialog ref={dialog} aria-label="날씨각 쇼츠" onClose={onClose} className="fixed inset-0 m-0 size-full max-h-none max-w-none bg-black p-0 text-white">
|
||
{/* 유튜브 플레이어 위쪽 로고·소리 버튼을 가리지 않게 닫기 줄을 따로 둔다 */}
|
||
<div className="flex h-[calc(env(safe-area-inset-top,0px)+52px)] items-end px-3 pb-2">
|
||
<button type="button" onClick={onClose} aria-label="닫기" className={cx('relative grid size-9 cursor-pointer place-items-center rounded-full bg-white/15 text-xl text-white', TAP44)}>
|
||
×
|
||
</button>
|
||
</div>
|
||
<div ref={list} className="h-[calc(100dvh-env(safe-area-inset-top,0px)-52px)] snap-y snap-mandatory overflow-y-auto [scrollbar-width:none]">
|
||
{items.map((s, i) => (
|
||
<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" />
|
||
{Math.abs(i - at) <= 1 && (
|
||
<iframe
|
||
ref={(f) => {
|
||
if (f) frames.current.set(i, f)
|
||
else frames.current.delete(i)
|
||
}}
|
||
src={embed(s.id, true, i === start)}
|
||
title={s.title}
|
||
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
|
||
allowFullScreen
|
||
// 미리 띄운 플레이어가 다 뜨기 전에 넘어왔으면, 뜬 뒤에 재생을 건다
|
||
onLoad={(e) => {
|
||
const f = e.currentTarget
|
||
setTimeout(() => command(f, atRef.current === i ? 'playVideo' : 'pauseVideo'), 300)
|
||
}}
|
||
className="absolute inset-0 size-full border-0"
|
||
/>
|
||
)}
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
</dialog>
|
||
)
|
||
}
|