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

338 lines
15 KiB
TypeScript

import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery, useQueryClient } from '@tanstack/react-query'
import { authConfigOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils'
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
import './b.css'
import { AuthProvider } from './auth'
import { RegionProvider } from './region'
import { useAuth } from './authContext'
import { preloadGoogle } from './googleScript'
import { currentHoliday } from './holiday'
import { LevelBadge, LevelWatcher } from './level'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { SheetProvider } from './Sheets'
import { SkyContext, useSky } from './skyContext'
import { TossIntro } from './tossIntro'
import { PinIcon, TabIcon } from './svg'
import { Avatar, Ic, Skel } from './ui'
const TABS = [
{ to: '/sky', key: 'sky', label: '노을', title: '노을' },
{ to: '/gak', key: 'gak', label: '각', title: '오늘의 각' },
// 메인인 오늘 탭을 가운데에
{ to: '/', key: 'today', label: '오늘', title: null },
{ to: '/week', key: 'week', label: '주말·행사', title: '주말·행사' },
{ to: '/season', key: 'season', label: '계절·상식', title: '계절·상식' },
] as const
/** 로고 옆 계절 칩: 계절 이름과 지금 절기. 누르면 이번 주 절기 창. 좁은 화면에선 절기를 뺀다 */
function SeasonChip() {
const { open } = useSheet()
const week = useQuery(getSeasonWeekOptions())
const [month] = useState(() => kst(new Date()).mo)
const [name, icon] = seasonOf(month)
const term = week.data?.term_now?.name
return (
<button type="button" onClick={() => open({ type: 'seasonWeek' })} aria-label={`지금 ${name}${term ? `, ${term}` : ''}. 이번 주 절기 보기`} className="flex shrink-0 cursor-pointer items-center gap-1 rounded-full bg-white/70 py-1 pr-2.5 pl-1.5 text-[13px] font-extrabold whitespace-nowrap shadow-[0_4px_10px_rgb(40_48_74/0.06)]">
<Ic name={icon} className="size-[18px]" />
{name}
{term && <span className="hidden font-bold opacity-70 min-[400px]:inline">· {term}</span>}
</button>
)
}
function TopBar() {
const { pathname } = useLocation()
const { region, locateStatus } = useRegion()
const { open } = useSheet()
const { me, mePending } = useAuth()
const queryClient = useQueryClient()
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
const loggedOut = !mePending && !me
// 로그인 창을 처음 열 때 버벅이지 않게 구글 로그인 준비물을 미리 받아 둔다
useEffect(() => {
if (!loggedOut) return
void queryClient.prefetchQuery({ ...authConfigOptions(), staleTime: Infinity })
return preloadGoogle()
}, [loggedOut, queryClient])
return (
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
{tab?.title ? <h1 className="shrink-0 font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="shrink-0 font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
<SeasonChip />
<button
type="button"
onClick={() => open({ type: 'region' })}
aria-label={`위치 바꾸기, 지금 ${region.name}`}
className="ml-auto flex shrink-0 cursor-pointer items-center gap-1 rounded-full bg-white px-3 pt-1 pb-2 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
>
<PinIcon className="size-3.5 shrink-0" />
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : <span className="truncate whitespace-nowrap"><span className="max-[399px]:hidden">{region.name}</span><span className="min-[400px]:hidden">{region.name.split(' ').at(-1)}</span></span>}
</button>
{mePending ? (
<Skel shape className="size-9 shrink-0 rounded-full" />
) : me ? (
<button type="button" onClick={() => open({ type: 'me' })} aria-label={`내 정보, ${me.nickname}`} className="relative shrink-0 cursor-pointer rounded-full shadow-[0_6px_12px_rgb(40_48_74/0.12)]">
<Avatar character={me.character} color={me.color} mood={me.mood} size={36} />
<LevelBadge />
</button>
) : (
<button type="button" onClick={() => open({ type: 'login' })} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[13px] font-extrabold text-white">
로그인
</button>
)}
</header>
)
}
const STARS = Array.from({ length: 46 }, (_, i) => ({
left: `${(i * 41 + 7) % 100}%`,
top: `${(i * 67 + 3) % 96}%`,
'--s': `${1 + (i % 3) * 0.8}px`,
'--tw': `${3 + (i % 5)}s`,
'--dl': `-${(i * 0.7) % 6}s`,
}))
// 별똥별: 위치·길이·주기를 엇갈려 몇 초마다 하나씩 떨어지게
const SHOOTS = [
{ top: '8%', left: '78%', '--len': '110px', '--dur': '7s', '--dl': '1s' },
{ top: '22%', left: '46%', '--len': '80px', '--dur': '9s', '--dl': '3.5s' },
{ top: '5%', left: '30%', '--len': '95px', '--dur': '8s', '--dl': '5.5s' },
{ top: '36%', left: '88%', '--len': '70px', '--dur': '10s', '--dl': '2.2s' },
{ top: '52%', left: '62%', '--len': '90px', '--dur': '11s', '--dl': '7s' },
{ top: '14%', left: '96%', '--len': '120px', '--dur': '12s', '--dl': '9s' },
]
const HOLIDAY = currentHoliday()
/** 화면 전체 하늘: 시간대별 색, 아주 느리게 일렁이는 색 덩어리, 밤에는 별 */
function SkyBg() {
const { kind } = useSky()
const [hidden, setHidden] = useState(false)
useEffect(() => {
const onVis = () => setHidden(document.hidden)
document.addEventListener('visibilitychange', onVis)
return () => document.removeEventListener('visibilitychange', onVis)
}, [])
return (
<div className={cx('b-skybg pointer-events-none fixed inset-0 overflow-hidden', hidden && 'b-paused')} data-t={kind} data-h={HOLIDAY?.key} aria-hidden="true">
{(['morning', 'day', 'sunset', 'night'] as const).map((k) => (
<div key={k} className={cx('b-sky-lay absolute inset-0', `b-sky-${k}`)} />
))}
{HOLIDAY && <div className="b-sky-lay b-sky-holiday absolute inset-0" />}
<span className="b-blob b-blob-1" />
<span className="b-blob b-blob-2" />
<span className="b-blob b-blob-3" />
<div className="b-skystars absolute inset-0">
{STARS.map((s, i) => (
<i key={i} style={s} />
))}
{SHOOTS.map((s, i) => (
<span key={i} className="b-shoot" style={s} />
))}
</div>
</div>
)
}
const PREVIEW_KEY = 'nalssigak.b.skyPreview'
const KINDS: readonly string[] = ['morning', 'day', 'sunset', 'night'] satisfies TimeKind[]
function readPreview(): TimeKind | null {
try {
const v = sessionStorage.getItem(PREVIEW_KEY)
return v && KINDS.includes(v) ? (v as TimeKind) : null
} catch {
// 저장소가 막힌 브라우저는 '지금'으로 시작한다
return null
}
}
function SkyProvider({ children }: { children: ReactNode }) {
// 고른 시간대는 탭을 옮겨도 이 창에서 유지한다
const [preview, setPreviewState] = useState<TimeKind | null>(readPreview)
const setPreview = useCallback((k: TimeKind | null) => {
setPreviewState(k)
try {
if (k) sessionStorage.setItem(PREVIEW_KEY, k)
else sessionStorage.removeItem(PREVIEW_KEY)
} catch {
// 저장이 막혀도 이번 화면에서는 메모리 값으로 쓴다
return
}
}, [])
const [serverKind, setServerKind] = useState<TimeKind | null>(null)
const [now, setNow] = useState(() => new Date())
useEffect(() => {
const id = setInterval(() => setNow(new Date()), 60000)
return () => clearInterval(id)
}, [])
const t = kst(now)
const kind = preview ?? serverKind ?? kindOfHour(t.h, t.mo, t.mi)
const api = useMemo(() => ({ kind, preview, setPreview, setServerKind }), [kind, preview, setPreview])
return (
<SkyContext value={api}>{children}</SkyContext>
)
}
// 노치 띠·상태바 색: 하늘 맨 위 색에 .b-topbg 를 겹친 색
const NOTCH_BG: Record<TimeKind, string> = {
morning: '#ffe6cf',
day: '#d6ebff',
sunset: '#ffd8c2',
night: '#0e1433',
}
/** 처음 들어올 때만: 첫 데이터를 다 받을 때까지 하늘 위에 캐릭터와 '날씨 불러오는 중…'. 한 번 사라지면 다시 안 뜬다 */
function FirstLoad() {
const fetching = useIsFetching()
const { kind } = useSky()
const [started, setStarted] = useState(false)
const [done, setDone] = useState(false)
const [gone, setGone] = useState(false)
// 받기 시작했다가 받는 게 없어지면 끝 (렌더 중에 바로 맞춘다)
if (fetching > 0 && !started) setStarted(true)
if (fetching === 0 && started && !done) setDone(true)
// 앱이 떴으니 index.html 의 첫 화면은 걷는다 (이 덮개가 이어받는다)
useEffect(() => document.getElementById('boot')?.remove(), [])
// 느린 망에서도 10초 넘게 막지 않는다 (그 뒤는 화면 안 스켈레톤이 맡는다)
useEffect(() => {
const id = setTimeout(() => setDone(true), 10000)
return () => clearTimeout(id)
}, [])
if (gone) return null
return (
<div
role="status"
aria-live="polite"
onTransitionEnd={() => done && setGone(true)}
className={cx('fixed inset-0 z-50 flex flex-col items-center justify-center gap-3 backdrop-blur-[6px] transition-opacity duration-400', done && 'pointer-events-none opacity-0')}
style={{ backgroundColor: `color-mix(in srgb, ${NOTCH_BG[kind]} 72%, transparent)` }}
>
<Ic name={kind === 'night' ? 'bear' : 'rabbit'} className="b-hop w-[88px]" />
<p className="m-0 font-jua text-[19px]">날씨 불러오는 중…</p>
</div>
)
}
// 페이지마다 마지막 스크롤 위치: 뒤로 가기로 돌아오면 그 자리로
const scrolled = new Map<string, number>()
function Shell() {
const { pathname, key } = useLocation()
const navType = useNavigationType()
const { kind } = useSky()
useEffect(() => {
const save = () => scrolled.set(key, window.scrollY)
window.addEventListener('scroll', save, { passive: true })
return () => window.removeEventListener('scroll', save)
}, [key])
useEffect(() => {
const top = navType === 'POP' ? scrolled.get(key) : undefined
if (top == null) {
window.scrollTo({ top: 0 })
return
}
// 피드가 다시 그려져 그 높이가 될 때까지 최대 3초 맞추고, 그 사이 사람이 화면을 만지면 멈춘다
let tries = 0
let raf = 0
const stop = () => cancelAnimationFrame(raf)
const go = () => {
window.scrollTo({ top })
if (Math.abs(window.scrollY - top) > 2 && ++tries < 180) raf = requestAnimationFrame(go)
}
go()
window.addEventListener('touchstart', stop, { once: true, passive: true })
window.addEventListener('wheel', stop, { once: true, passive: true })
return () => {
stop()
window.removeEventListener('touchstart', stop)
window.removeEventListener('wheel', stop)
}
}, [pathname, key, navType])
// 지금 보고 있는 탭을 다시 누르면 맨 위로
const toTopIfHere = (to: string) => () => {
if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' })
}
useEffect(() => {
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', NOTCH_BG[kind])
}, [kind])
return (
<div className="min-h-dvh text-(--ink)">
<SkyBg />
<FirstLoad />
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
{HOLIDAY && (
<div className="b-holiday-head pointer-events-none fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] overflow-hidden" data-h={HOLIDAY.key} data-t={kind} aria-hidden="true">
<i />
</div>
)}
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(104px+env(safe-area-inset-bottom,0px))]">
<TopBar />
<main className="relative z-[1]">
<Outlet />
</main>
<nav aria-label="주요 메뉴" className="b-tabbar fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t px-[max(4px,calc((100%-432px)/2))] pt-[7px] pb-[calc(8px+env(safe-area-inset-bottom,0px))] backdrop-blur-[10px]">
{TABS.map((t) =>
t.key === 'today' ? (
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') || pathname.startsWith('/tomorrow/') ? 'text-(--orange)' : 'text-(--ink3)')}>
<span className="b-keep-bg grid size-[60px] place-items-center rounded-full bg-[linear-gradient(160deg,#ffb067,var(--orange)_55%,var(--orange-deep))] text-white shadow-[0_8px_18px_rgb(255_122_69/0.45),inset_0_-4px_0_rgb(0_0_0/0.12)] ring-4 ring-white/85 [&_svg]:stroke-[2.6]">
<TabIcon name={t.key} className="size-[30px]" />
</span>
{t.label}
</NavLink>
) : (
<NavLink key={t.key} to={t.to} onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
<TabIcon name={t.key} className="size-[25px]" />
{t.label}
</NavLink>
),
)}
</nav>
</div>
</div>
)
}
/** .b-app 에 지금 시간대를 달아 밤에는 바깥 글자를 밝게 바꾼다 */
function SkyRoot({ children }: { children: ReactNode }) {
return (
<SkyProvider>
<SkyApp>{children}</SkyApp>
</SkyProvider>
)
}
function SkyApp({ children }: { children: ReactNode }) {
const { kind } = useSky()
return (
<div className="b-app" data-t={kind}>
{children}
</div>
)
}
export function BLayout() {
return (
<SkyRoot>
<AuthProvider>
<RegionProvider>
<SheetProvider>
<Shell />
<TossIntro />
<LevelWatcher />
</SheetProvider>
</RegionProvider>
</AuthProvider>
</SkyRoot>
)
}