Files
o2o-weather/frontend/src/b/Shorts.tsx
T

339 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { cx } from '../lib/utils'
import { Rail, 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
// 쇼츠 페이지의 영상 칸: 위 헤더(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<HTMLElement>('nav.b-tabbar')
if (!nav) return
const ro = new ResizeObserver(() => setH(nav.offsetHeight))
ro.observe(nav)
return () => ro.disconnect()
}, [])
return h
}
const YT_ORIGIN = 'https://www.youtube-nocookie.com'
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' | 'pauseVideo' | '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<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
}
/** 오늘 화면 히어로 아래 쇼츠 줄: 첫 카드만 소리 없이 재생, 누르면 쇼츠 페이지(/shorts/영상ID)에서 위아래로 넘겨 본다 */
export function ShortsRail() {
const q = useQuery(listShortsOptions())
const items = q.data?.items ?? []
const [ref, visible] = useVisible<HTMLElement>()
if (q.isPending) {
return (
<section aria-hidden="true">
<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="날씨각 쇼츠">
<Rail label="쇼츠 목록">
{items.map((s, i) => (
<ShortCard key={s.id} s={s} playing={i === 0 && visible} />
))}
</Rail>
</section>
)
}
function ShortCard({ s, playing }: { s: ShortItem; playing: boolean }) {
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
src={embed(s.id)}
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="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>
)
}
/** 쇼츠 페이지(/shorts/영상ID): 그 영상부터 위아래로 넘겨 보고, 넘기면 주소도 그 영상으로 바뀌어 그대로 공유할 수 있다 */
export function ShortsPage() {
const { id } = useParams()
const navigate = useNavigate()
const q = useQuery(listShortsOptions())
// 처음 들어온 영상만 시작점으로 쓴다 (넘기며 주소가 바뀌어도 다시 맞추지 않는다)
const [firstId] = useState(id)
const listed = q.data?.items ?? []
const items = firstId && listed.length && !listed.some((s) => s.id === firstId) ? [{ id: firstId, title: '' }, ...listed] : listed
const start = Math.max(0, items.findIndex((s) => s.id === firstId))
// 앱 안에서 들어왔으면 뒤로, 링크로 바로 들어왔으면 오늘 화면으로
const close = () => ((window.history.state as { idx?: number } | null)?.idx ? navigate(-1) : navigate('/', { replace: true }))
if (!items.length) return <div className="fixed inset-0 z-[70] bg-[#1d2233]" aria-busy={q.isPending} />
return <ShortsViewer items={items} start={start} onClose={close} onAt={(s) => navigate(`/shorts/${s.id}`, { replace: true })} />
}
/**
* 처음 열 때·넘길 때 검은 화면이 보이지 않게, 첫 장면을 받을 때까지는 표지를 보이고 앞뒤 영상도 소리 없이 틀어 첫 장면을 받아 둔 뒤 멈춰 두고, 보이는 것만 처음부터 재생한다
*/
function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; start: number; onClose: () => void; onAt: (s: ShortItem) => void }) {
const list = useRef<HTMLDivElement>(null)
const [at, setAt] = useState(start)
const [sound, setSound] = useState(false)
const tabH = useTabBarHeight()
// 첫 장면을 받은 플레이어. 그 전엔 플레이어의 검은 화면 대신 표지를 보인다
const [ready, setReady] = useState<ReadonlySet<number>>(new Set())
const frames = useRef(new Map<number, HTMLIFrameElement>())
const atRef = useRef(start)
const soundRef = useRef(false)
// 누르기로 멈춘 상태. 다른 영상으로 넘어가면 다시 재생 중으로
const paused = useRef(false)
// 처음 한 번: 시작 영상으로 맞추고, 뒤 페이지 스크롤을 잠근다
const startRef = useRef(start)
useEffect(() => {
// scrollIntoView 는 바깥 칸까지 굴려 버튼 줄이 헤더 밑으로 숨으므로 목록만 옮긴다
const box = list.current
if (box) box.scrollTop = box.clientHeight * startRef.current
const root = document.documentElement
const before = root.style.overflow
root.style.overflow = 'hidden'
return () => {
root.style.overflow = before
}
}, [])
const onEscape = useEffectEvent((e: KeyboardEvent) => e.key === 'Escape' && onClose())
useEffect(() => {
window.addEventListener('keydown', onEscape)
return () => window.removeEventListener('keydown', onEscape)
}, [])
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(() => {
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
for (const [i, f] of frames.current) {
if (f.contentWindow !== e.source) continue
setReady((r) => (r.has(i) ? r : new Set(r).add(i)))
if (i === atRef.current) continue
command(f, 'pauseVideo')
command(f, 'seekTo', [0, true])
}
}
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [])
const moved = useEffectEvent((s: ShortItem) => onAt(s))
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')
command(f, 'playVideo')
} else {
command(f, 'pauseVideo')
command(f, 'mute')
}
}
}, [at, items])
// 마우스로도 끌어 넘긴다: 영상 위는 유튜브 iframe 이 마우스를 가져가서, 그 위에 투명한 판을 깔고 끈 만큼 목록을 옮긴다.
// 손가락은 브라우저 스크롤에 맡기고, 끌지 않고 누르기만 하면 재생·일시정지
const drag = useRef<{ y: number; top: number; moved: boolean } | null>(null)
const lastPointer = useRef('')
const [dragging, setDragging] = useState(false)
const togglePause = () => {
paused.current = !paused.current
command(frames.current.get(atRef.current), paused.current ? 'pauseVideo' : 'playVideo')
}
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
lastPointer.current = e.pointerType
const box = list.current
if (e.pointerType !== 'mouse' || !box) return
e.currentTarget.setPointerCapture(e.pointerId)
drag.current = { y: e.clientY, top: box.scrollTop, moved: false }
setDragging(true)
}
const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current
const box = list.current
if (!d || !box) return
const dy = e.clientY - d.y
if (Math.abs(dy) > 6) d.moved = true
box.scrollTop = d.top - dy
}
const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current
const box = list.current
drag.current = null
setDragging(false)
if (!d || !box) return
if (!d.moved) return togglePause()
// 30px 만 끌어도 다음·이전 영상으로, 그보다 덜 끌면 제자리로
const h = box.clientHeight
const dy = e.clientY - d.y
const base = Math.round(d.top / h)
const target = Math.min(items.length - 1, Math.max(0, base + (dy < -SWIPE_PX ? 1 : dy > SWIPE_PX ? -1 : 0)))
box.scrollTo({ top: target * h, behavior: 'smooth' })
}
const toggleSound = () => {
const on = !sound
soundRef.current = on
setSound(on)
command(frames.current.get(at), on ? 'unMute' : 'mute')
}
return (
// 헤더·탭 바는 그대로 두고 그 사이를 채운다. 흐린 배경은 반투명 헤더·탭 바 뒤까지 깐다
<div
role="region"
aria-label="날씨각 쇼츠"
className="fixed inset-0 flex flex-col overflow-hidden bg-[#1d2233] pt-[calc(54px+env(safe-area-inset-top,0px))] pb-(--shorts-tab) text-white"
style={{ '--shorts-tab': `${tabH}px` } as CSSProperties}
>
{/* 배경: 지금 영상 표지를 크게 흐려 깔아 영상 색이 번져 보이게 */}
<img
key={items[at].id}
src={`https://i.ytimg.com/vi/${items[at].id}/hqdefault.jpg`}
alt=""
aria-hidden="true"
className="absolute inset-0 size-full scale-125 object-cover opacity-70 blur-3xl"
/>
<div className="absolute inset-0 bg-black/35" aria-hidden="true" />
<div className="relative mx-auto flex h-12 w-full max-w-[440px] shrink-0 items-center justify-between px-3">
<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>
<button type="button" onClick={toggleSound} aria-pressed={sound} className="h-9 cursor-pointer rounded-full bg-white/15 px-3.5 text-[13px] font-bold text-white">
{sound ? '소리 끄기' : '소리 켜기'}
</button>
</div>
<div ref={list} className={cx('relative min-h-0 flex-1 overflow-y-auto [scrollbar-width:none]', !dragging && 'snap-y snap-mandatory')}>
{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)}
title={s.title}
allow="autoplay; encrypted-media; picture-in-picture"
// 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다
onLoad={(e) => {
e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN)
// 앞뒤 밖으로 밀려나 내려갔다 다시 뜬 플레이어는 첫 장면을 새로 받을 때까지 다시 숨긴다
setReady((r) => {
if (!r.has(i)) return r
const next = new Set(r)
next.delete(i)
return next
})
}}
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', !ready.has(i) && 'opacity-0')}
/>
)}
<div
aria-hidden="true"
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={() => {
drag.current = null
setDragging(false)
}}
onClick={() => lastPointer.current !== 'mouse' && togglePause()}
className={cx('absolute inset-0 touch-pan-y select-none', dragging ? 'cursor-grabbing' : 'cursor-grab')}
/>
</div>
</div>
))}
</div>
</div>
)
}