feat: 시안 B 화면을 기본 화면으로, Hey API로 백엔드 연결
- 예전 화면(/, /a)과 목업 데이터를 지우고 시안 B 를 / 로 - @hey-api/openapi-ts 로 타입·TanStack Query 함수 생성, 토큰·401 갱신 처리 - 공유는 기본 공유창, 없으면 링크 복사 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e134295ce5
commit
f8b47f064a
147 files changed
+12350
No files matched your search
@@ -0,0 +1,80 @@
|
||||
import { useEffect } from 'react'
|
||||
import { NavLink, Outlet, useLocation } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import './b.css'
|
||||
import { AuthProvider } from './auth'
|
||||
import { RegionProvider } from './region'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { SheetProvider } from './Sheets'
|
||||
import { PinIcon, TabIcon } from './svg'
|
||||
|
||||
const TABS = [
|
||||
{ to: '/', key: 'today', label: '오늘', title: null },
|
||||
{ to: '/gak', key: 'gak', label: '각', title: '오늘의 각' },
|
||||
{ to: '/sky', key: 'sky', label: '노을', title: '노을' },
|
||||
{ to: '/week', key: 'week', label: '주말·행사', title: '주말·행사' },
|
||||
{ to: '/season', key: 'season', label: '계절·상식', title: '계절·상식' },
|
||||
] as const
|
||||
|
||||
function TopBar() {
|
||||
const { pathname } = useLocation()
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-20 flex h-[54px] items-center justify-between gap-2.5 bg-[rgb(247_251_255/0.9)] px-4 backdrop-blur-md">
|
||||
{tab?.title ? <h1 className="font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => open({ type: 'region' })}
|
||||
aria-label={`위치 바꾸기, 지금 ${region.name}`}
|
||||
className="flex cursor-pointer items-center gap-1 rounded-full bg-white px-3 py-1.5 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" />
|
||||
{region.name}
|
||||
</button>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const { pathname } = useLocation()
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0 })
|
||||
}, [pathname])
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-(--outer) text-(--ink)">
|
||||
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip bg-(--page) pb-[calc(70px+env(safe-area-inset-bottom,0px))]">
|
||||
<TopBar />
|
||||
<main>
|
||||
<Outlet />
|
||||
</main>
|
||||
<nav aria-label="주요 메뉴" className="fixed bottom-0 left-1/2 z-30 grid w-full max-w-[440px] -translate-x-1/2 grid-cols-5 border-t border-(--line) bg-white/96 px-1 pt-[7px] pb-[calc(8px+env(safe-area-inset-bottom,0px))] backdrop-blur-[10px]">
|
||||
{TABS.map((t) => (
|
||||
<NavLink key={t.key} to={t.to} end={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>
|
||||
)
|
||||
}
|
||||
|
||||
export function BLayout() {
|
||||
return (
|
||||
<div className="b-app">
|
||||
<AuthProvider>
|
||||
<RegionProvider>
|
||||
<SheetProvider>
|
||||
<Shell />
|
||||
</SheetProvider>
|
||||
</RegionProvider>
|
||||
</AuthProvider>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { MEDALS } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, Sec, StateBox } from './ui'
|
||||
|
||||
type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core'
|
||||
|
||||
const CATS = [
|
||||
['all', '전체'],
|
||||
['out', '밖에서 놀기'],
|
||||
['food', '먹고 마시기'],
|
||||
['home', '집안일'],
|
||||
['life', '생활 고민'],
|
||||
['core', '가을 각'],
|
||||
] as const
|
||||
|
||||
const CAT_PARAM: Partial<Record<Cat, IndexCategory>> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE }
|
||||
|
||||
export function GakPage() {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const [cat, setCat] = useState<Cat>('all')
|
||||
const q = useQuery(listIndicesOptions({ query: { region: region.code, category: CAT_PARAM[cat], core: cat === 'core' ? true : undefined } }))
|
||||
const top = q.data?.top3 ?? []
|
||||
const items = q.data?.items ?? []
|
||||
const day = q.data?.day?.split('-').map(Number)
|
||||
const howto = useQuery(listArticlesOptions({ query: { category: ArticleCategory.GAK } })).data?.articles?.find((a) => a.code === 'howgak')
|
||||
|
||||
return (
|
||||
<section aria-label="각">
|
||||
<Sec title="오늘 1~3위" sub={`${day ? `${day[1]}월 ${day[2]}일 기준 · ` : ''}${region.name} · 칸 아래 막대는 오늘·내일·모레 점수`} />
|
||||
{top.length === 3 && (
|
||||
<div className="grid grid-cols-[1fr_1.15fr_1fr] items-end gap-1.5 px-3 pt-3">
|
||||
{[1, 0, 2].map((k) => {
|
||||
const g = top[k]
|
||||
return (
|
||||
<button
|
||||
key={g.index_id}
|
||||
type="button"
|
||||
onClick={() => open({ type: 'gak', indexId: g.index_id })}
|
||||
className={cx('flex cursor-pointer flex-col items-center rounded-3xl px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'bg-[linear-gradient(180deg,#fff1c4,#fff)] py-4' : 'bg-white py-3')}
|
||||
>
|
||||
<span className="relative">
|
||||
<Ic name={g.icon} className={cx('drop-shadow-[0_10px_12px_rgb(40_48_74/0.15)]', k === 0 ? 'w-20' : 'w-[62px]')} />
|
||||
<Ic name={MEDALS[k]} className="absolute -top-1.5 -left-3 w-7" />
|
||||
</span>
|
||||
<b className="mt-1.5 font-jua text-base font-normal">
|
||||
{k + 1}위 {g.name}
|
||||
</b>
|
||||
<em className="font-bagel text-[30px] leading-[1.05] text-(--orange) not-italic">{g.score}</em>
|
||||
<small className="text-[11.5px] font-semibold text-(--ink2)">{g.summary}</small>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<Chips items={CATS} value={cat} onChange={setCat} label="분야" />
|
||||
<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty={q.isSuccess && !items.length ? '이 분야는 오늘 계산된 각이 없어요.' : undefined} />
|
||||
<div className="grid grid-cols-3 gap-2 p-3">
|
||||
{items.map((g) => {
|
||||
const trend = g.trend ?? []
|
||||
const mx = Math.max(1, ...trend.map((t) => t.score))
|
||||
return (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={`${g.rank}위 ${g.name} ${g.score}점`} className="relative flex cursor-pointer flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<span className="absolute top-[7px] left-[9px] font-jua text-[13px] text-(--ink3)">{g.rank}</span>
|
||||
{g.is_core && <span className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">가을</span>}
|
||||
<Ic name={g.icon} className="w-[50px]" />
|
||||
<b className="mt-1 font-jua text-[15px] font-normal">{g.name}</b>
|
||||
<em className={cx('font-bagel text-[22px] leading-[1.1] not-italic', g.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{g.score}</em>
|
||||
<span className="mt-1 flex h-[18px] items-end gap-[3px]" aria-hidden="true">
|
||||
{trend.map((t, j) => (
|
||||
<i key={t.day} className={cx('w-[9px] rounded-[3px]', j ? 'bg-[#dbe4ef]' : 'bg-(--orange)')} style={{ height: Math.max(4, (t.score / mx) * 18) }} />
|
||||
))}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{howto && (
|
||||
<button type="button" onClick={() => open({ type: 'article', articleId: howto.article_id })} className="mx-3 mt-1.5 flex w-[calc(100%-24px)] cursor-pointer items-center gap-3 rounded-[22px] bg-[#ece7ff] p-3.5 text-left">
|
||||
<Ic name="bulb" className="w-11" />
|
||||
<span>
|
||||
<b className="block font-jua text-[17px] font-normal">각 점수는 어떻게 매길까?</b>
|
||||
<small className="text-[12.5px] font-semibold text-(--ink2)">기온·비·바람·습도·공기·시간대 6가지로 계산해요</small>
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import { useRef, useState, type MouseEvent, type ReactNode } from 'react'
|
||||
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PostData, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { ago, cardBg, clockShort, fall } from './lib'
|
||||
import type { SlideBg } from './types'
|
||||
import { deg } from './weatherText'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { likePostMutation, savePostMutation, unlikePostMutation, unsavePostMutation } from '../api/client/@tanstack/react-query.gen'
|
||||
import { useAuth } from './authContext'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { CommentIcon, HeartIcon, MoreIcon, SaveIcon, SendIcon } from './svg'
|
||||
import { Ic, Rows } from './ui'
|
||||
|
||||
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
|
||||
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
|
||||
[PostType.GAK]: ['오늘의 각', 'rabbit'],
|
||||
[PostType.SUNSET]: ['노을', 'sunset'],
|
||||
[PostType.SEASON]: ['계절 소식', 'maple'],
|
||||
[PostType.EVENT]: ['행사', 'fireworks'],
|
||||
[PostType.TIP]: ['날씨 상식', 'bulb'],
|
||||
[PostType.WEEK]: ['주말 추천', 'calendar'],
|
||||
}
|
||||
|
||||
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide
|
||||
|
||||
const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac']
|
||||
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach' }
|
||||
|
||||
/** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */
|
||||
function slideBg(post: PostData, slide: Slide): SlideBg {
|
||||
if (slide.kind === 'hours') return 'sky'
|
||||
if (slide.kind === 'sunset') return 'dusk'
|
||||
if (slide.kind === 'week') return 'mint'
|
||||
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length]
|
||||
if (post.post_type === PostType.EVENT) return 'night'
|
||||
if (post.post_type === PostType.TIP) return 'sky'
|
||||
return ROW_ICON_BG[slide.icon] ?? cardBg(slide.icon, post.post_id)
|
||||
}
|
||||
|
||||
const DARK = new Set<SlideBg>(['dusk', 'night'])
|
||||
|
||||
function Lines({ text }: { text: string }) {
|
||||
return text.split('\n').map((t, i) => (
|
||||
<span key={i}>
|
||||
{i > 0 && <br />}
|
||||
{t}
|
||||
</span>
|
||||
))
|
||||
}
|
||||
|
||||
function Eyebrow({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <p className={cx('m-0 text-[13px] font-extrabold opacity-75', className)}>{children}</p>
|
||||
}
|
||||
|
||||
function Big({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <p className={cx('mt-1.5 font-jua text-[29px] leading-tight', className)}>{children}</p>
|
||||
}
|
||||
|
||||
function Pic({ name, className }: { name: string; className?: string }) {
|
||||
return (
|
||||
<span className={cx('b-fall pointer-events-none absolute top-[30%] right-3.5 w-[42%]', className)} style={fall('.1s', '5s')}>
|
||||
<Ic name={name} className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const slideBase = 'relative flex h-full w-full shrink-0 snap-start flex-col px-5 py-[22px]'
|
||||
|
||||
function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
const { open } = useSheet()
|
||||
if (slide.kind === 'hours')
|
||||
return (
|
||||
<div className={cx(slideBase, 'b-bg-sky')}>
|
||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||
<Big>
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<div className="mt-3.5 grid flex-1 grid-cols-4 gap-2">
|
||||
{slide.hours.map((h) => (
|
||||
<div
|
||||
key={h.label}
|
||||
className={cx(
|
||||
'flex flex-col items-center justify-between rounded-[18px] px-1 pt-2.5 pb-[9px] text-xs font-bold text-(--ink2)',
|
||||
h.tone === SlotTone.NIGHT ? 'bg-[#e3e7ff] shadow-[inset_0_-5px_0_#c7cff5]' : h.tone === SlotTone.SUNSET ? 'bg-[#ffe3d2] shadow-[inset_0_-5px_0_#ffc19f]' : 'bg-white shadow-[inset_0_-5px_0_var(--shade)]',
|
||||
)}
|
||||
>
|
||||
<span>{h.label}</span>
|
||||
<Ic name={h.icon} className="w-[34px]" />
|
||||
<b className="font-bagel text-[21px] font-normal text-(--ink)">{deg(h.temp_c)}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
if (slide.kind === 'gak')
|
||||
return (
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)}>
|
||||
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
|
||||
<Big>{slide.line}</Big>
|
||||
<Pic name={slide.code} />
|
||||
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b>
|
||||
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
|
||||
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
|
||||
<button type="button" onClick={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 cursor-pointer self-start rounded-full bg-(--orange) px-4 py-[9px] font-jua text-[15px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]">
|
||||
계산 근거 보기 ⬡
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
if (slide.kind === 'sunset')
|
||||
return (
|
||||
<div className={cx(slideBase, 'b-bg-dusk')}>
|
||||
<Eyebrow className="opacity-90">{slide.eyebrow}</Eyebrow>
|
||||
<Big>
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<b className="mt-2 font-bagel text-[62px] leading-[0.9] font-normal">{slide.score}</b>
|
||||
<div className="mt-3 flex flex-1 flex-col gap-2">
|
||||
{slide.cuts.map((c, i) => (
|
||||
<div key={c.kind} className={cx('b-skyline relative flex-1 overflow-hidden rounded-2xl px-3 py-2 font-bagel text-[21px] text-white', `b-cut-${Math.min(i + 1, 3)}`)}>
|
||||
<span className="relative z-[1]">
|
||||
{clockShort(c.at)}
|
||||
<small className="ml-2 font-jua text-sm">{c.label}</small>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
if (slide.kind === 'week')
|
||||
return (
|
||||
<div className={cx(slideBase, 'b-bg-mint')}>
|
||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||
<Big>
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<div className="mt-auto grid grid-cols-2 gap-2.5">
|
||||
{slide.days.map((d) => (
|
||||
<div key={d.day} className="rounded-[18px] bg-white/80 px-3 py-2.5 shadow-[inset_0_-5px_0_rgb(217_229_244/0.9)]">
|
||||
<Ic name={d.icon} className="w-[38px]" />
|
||||
<b className="block font-jua text-lg font-normal">
|
||||
{d.weekday} {d.day.split('-').slice(1).map(Number).join('.')}
|
||||
</b>
|
||||
<small className="text-[12.5px] font-bold text-(--ink2)">{d.text}</small>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
return (
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)}>
|
||||
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
|
||||
<Big className="relative z-[1]">
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<Pic name={slide.icon} className="w-[36%]" />
|
||||
<Rows rows={slide.rows ?? []} dark={DARK.has(bg)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type PostProps = { post: PostData }
|
||||
|
||||
/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */
|
||||
export function PostCard({ post }: PostProps) {
|
||||
const { open } = useSheet()
|
||||
const { region } = useRegion()
|
||||
const { loggedIn } = useAuth()
|
||||
const [liked, setLiked] = useState(!!post.liked)
|
||||
const [likeCount, setLikeCount] = useState(post.like_count)
|
||||
const [saved, setSaved] = useState(!!post.saved)
|
||||
const like = useMutation(likePostMutation())
|
||||
const unlike = useMutation(unlikePostMutation())
|
||||
const save = useMutation(savePostMutation())
|
||||
const unsave = useMutation(unsavePostMutation())
|
||||
const [index, setIndex] = useState(0)
|
||||
const [pop, setPop] = useState(0)
|
||||
const lastTap = useRef(0)
|
||||
const [account, avatar] = ACCOUNTS[post.post_type]
|
||||
const n = post.slides.length
|
||||
const bgs = post.slides.map((sl) => slideBg(post, sl))
|
||||
const accountName = post.post_type === PostType.EVENT ? `${region.name.split(' ')[0]} ${account}` : account
|
||||
const share = () => open({ type: 'share', share: { title: post.title, icon: post.icon, bg: bgs[0] ?? 'sky', messages: post.share_messages ?? [] } })
|
||||
const comments = () => open({ type: 'comments', postId: post.post_id })
|
||||
|
||||
// 화면을 먼저 바꾸고, 실패하면 되돌린다
|
||||
const setLike = (next: boolean) => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (next === liked) return
|
||||
setLiked(next)
|
||||
setLikeCount((n) => n + (next ? 1 : -1))
|
||||
;(next ? like : unlike).mutate(
|
||||
{ path: { post_id: post.post_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (res.liked != null) setLiked(res.liked)
|
||||
if (res.like_count != null) setLikeCount(res.like_count)
|
||||
},
|
||||
onError: () => {
|
||||
setLiked(!next)
|
||||
setLikeCount((n) => n + (next ? -1 : 1))
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const toggleSave = () => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const next = !saved
|
||||
setSaved(next)
|
||||
;(next ? save : unsave).mutate(
|
||||
{ path: { post_id: post.post_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (res.saved != null) setSaved(res.saved)
|
||||
},
|
||||
onError: () => setSaved(!next),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const onTap = (e: MouseEvent<HTMLDivElement>) => {
|
||||
if ((e.target as HTMLElement).closest('button')) return
|
||||
const now = Date.now()
|
||||
if (now - lastTap.current < 320) {
|
||||
setLike(true)
|
||||
if (loggedIn) setPop((p) => p + 1)
|
||||
}
|
||||
lastTap.current = now
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="mt-3.5 border-y border-(--line) bg-white" aria-label={post.title}>
|
||||
<div className="flex items-center gap-2.5 px-3 py-2.5">
|
||||
<span className="b-ring size-[34px] shrink-0 rounded-full p-0.5">
|
||||
<i className="grid size-full place-items-center rounded-full bg-white">
|
||||
<Ic name={avatar} className="w-[22px]" />
|
||||
</i>
|
||||
</span>
|
||||
<span>
|
||||
<b className="block text-sm leading-tight font-extrabold">날씨각</b>
|
||||
<small className="text-xs font-semibold text-(--ink2)">{accountName}</small>
|
||||
</span>
|
||||
<button type="button" onClick={share} aria-label="더 보기" className="ml-auto grid size-7 cursor-pointer place-items-center text-(--ink)">
|
||||
<MoreIcon />
|
||||
</button>
|
||||
</div>
|
||||
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
|
||||
{n > 1 && (
|
||||
<span className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true">
|
||||
{index + 1}/{n}
|
||||
</span>
|
||||
)}
|
||||
<div
|
||||
className="b-noscroll flex h-full snap-x snap-mandatory overflow-x-auto"
|
||||
onScroll={(e) => setIndex(Math.round(e.currentTarget.scrollLeft / e.currentTarget.clientWidth))}
|
||||
tabIndex={n > 1 ? 0 : undefined}
|
||||
aria-label={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}
|
||||
role={n > 1 ? 'region' : undefined}
|
||||
>
|
||||
{post.slides.map((s, i) => (
|
||||
<SlideView key={i} slide={s} bg={bgs[i]} />
|
||||
))}
|
||||
</div>
|
||||
{pop > 0 && (
|
||||
<svg key={pop} className="b-heart-pop pointer-events-none absolute top-1/2 left-1/2 z-[4] -mt-12 -ml-12 w-24 opacity-0" viewBox="0 0 24 24" fill="#fff" aria-hidden="true">
|
||||
<path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
|
||||
<button type="button" onClick={() => setLike(!liked)} aria-pressed={liked} aria-label="좋아요" className="grid size-7 cursor-pointer place-items-center">
|
||||
<HeartIcon className={liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
|
||||
</button>
|
||||
<button type="button" onClick={comments} aria-label="댓글 보기" className="grid size-7 cursor-pointer place-items-center">
|
||||
<CommentIcon className="fill-none stroke-(--ink) [stroke-linejoin:round]" />
|
||||
</button>
|
||||
<button type="button" onClick={share} aria-label="보내기" className="grid size-7 cursor-pointer place-items-center">
|
||||
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
|
||||
</button>
|
||||
{n > 1 && (
|
||||
<span className="absolute left-1/2 flex -translate-x-1/2 gap-1" aria-hidden="true">
|
||||
{post.slides.map((_, k) => (
|
||||
<i key={k} className={cx('size-1.5 rounded-full', k === index ? 'bg-(--rain)' : 'bg-[#cfd8e6]')} />
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
<button type="button" onClick={toggleSave} aria-pressed={saved} aria-label="저장" className="ml-auto grid size-7 cursor-pointer place-items-center">
|
||||
<SaveIcon className={cx('stroke-(--ink) [stroke-linejoin:round]', saved ? 'fill-(--ink)' : 'fill-none')} />
|
||||
</button>
|
||||
</div>
|
||||
<p className="px-3 py-0.5 text-sm font-extrabold">좋아요 {likeCount.toLocaleString()}개</p>
|
||||
<p className="px-3 py-0.5 text-sm">
|
||||
<b className="mr-[5px] font-extrabold">날씨각</b>
|
||||
{post.caption}
|
||||
</p>
|
||||
<button type="button" onClick={comments} className="block cursor-pointer px-3 pt-[3px] text-sm font-semibold text-(--ink3)">
|
||||
{post.comment_count ? `댓글 ${post.comment_count}개 모두 보기` : '첫 댓글 남기기'}
|
||||
</button>
|
||||
<p className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-(--ink3)">{ago(post.published_at)}</p>
|
||||
</article>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getSeasonWeekOptions, listArticlesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { ArticleCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { ARTICLE_CAT, cardBg, fall, shortDay } from './lib'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, StateBox } from './ui'
|
||||
|
||||
const CATS = [
|
||||
['all', '전체'],
|
||||
['season', '계절 소식'],
|
||||
['tip', '날씨 상식'],
|
||||
['gak', '각 원리'],
|
||||
] as const
|
||||
|
||||
const CAT_PARAM = { season: ArticleCategory.SEASON, tip: ArticleCategory.TIP, gak: ArticleCategory.GAK } as const
|
||||
|
||||
export function SeasonPage() {
|
||||
const { open } = useSheet()
|
||||
const [cat, setCat] = useState<(typeof CATS)[number][0]>('all')
|
||||
const week = useQuery(getSeasonWeekOptions())
|
||||
const arts = useQuery(listArticlesOptions(cat === 'all' ? undefined : { query: { category: CAT_PARAM[cat] } }))
|
||||
const w = week.data
|
||||
const list = arts.data?.articles ?? []
|
||||
const progress = Math.round((w?.progress ?? 0) * 100)
|
||||
|
||||
return (
|
||||
<section aria-label="계절·상식">
|
||||
{w?.headline ? (
|
||||
<button type="button" onClick={() => open({ type: 'seasonWeek' })} className="relative mx-3 mt-3 flex min-h-[250px] w-[calc(100%-24px)] cursor-pointer flex-col overflow-hidden rounded-[28px] bg-[linear-gradient(180deg,#ffd2bb,#fff2ea)] p-5 text-left">
|
||||
<p className="m-0 text-[13px] font-extrabold opacity-75">이번 주 특집 · {w.week}번째 주</p>
|
||||
<p className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight">{w.headline}</p>
|
||||
<span className="b-fall pointer-events-none absolute top-[18%] right-3.5 w-[38%]" style={fall('.1s')}>
|
||||
<Ic name="maple" className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||
</span>
|
||||
{(w.poem_lines ?? []).length > 0 && (
|
||||
<p className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[1.7]">
|
||||
{w.poem_lines?.map((l, i) => (
|
||||
<span key={l}>
|
||||
{i > 0 && <br />}
|
||||
{l}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
{w.term_now && w.term_next && (
|
||||
<div className={cx('max-w-[70%]', (w.poem_lines ?? []).length ? 'mt-2.5' : 'mt-auto')}>
|
||||
<div className="flex justify-between text-xs font-extrabold text-(--ink2)">
|
||||
<span>
|
||||
{w.term_now.name} {shortDay(w.term_now.day)}
|
||||
</span>
|
||||
<span>
|
||||
{w.term_next.name} {shortDay(w.term_next.day)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 h-[7px] overflow-hidden rounded-full bg-[rgb(40_48_74/0.1)]" role="img" aria-label={`다음 절기까지 ${progress}% 지났어요`}>
|
||||
<s className="block h-full bg-(--orange)" style={{ width: `${progress}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<StateBox loading={week.isPending} error={week.error} onRetry={() => week.refetch()} empty="이번 주 특집이 아직 없어요." />
|
||||
)}
|
||||
<Chips items={CATS} value={cat} onChange={setCat} label="분류" />
|
||||
<div className="mt-1.5">
|
||||
<StateBox loading={arts.isPending} error={arts.error} onRetry={() => arts.refetch()} empty={arts.isSuccess && !list.length ? '읽을거리가 아직 없어요.' : undefined} />
|
||||
{list.map((a) => (
|
||||
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="grid w-full cursor-pointer grid-cols-[1fr_84px] items-center gap-3 border-b-[1.5px] border-(--line) px-4 py-3.5 text-left">
|
||||
<span>
|
||||
<span className={cx('text-xs font-extrabold', ARTICLE_CAT[a.category]?.[1])}>{ARTICLE_CAT[a.category]?.[0]}</span>
|
||||
<b className="mt-0.5 block font-jua text-[17.5px] leading-snug font-normal">{a.title}</b>
|
||||
<small className="mt-1 block text-xs font-semibold text-(--ink3)">{a.read_minutes}분 읽기</small>
|
||||
</span>
|
||||
<span className={cx('grid h-[84px] place-items-center rounded-[18px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-[54px]" />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { setTokens, subscribeAuth } from '../api/auth'
|
||||
import {
|
||||
addCommentMutation,
|
||||
deleteCommentMutation,
|
||||
getArticleOptions,
|
||||
getFeedQueryKey,
|
||||
getIndexOptions,
|
||||
getSeasonWeekOptions,
|
||||
likeCommentMutation,
|
||||
listCommentsQueryKey,
|
||||
listCommentsOptions,
|
||||
listRegionsOptions,
|
||||
loginMutation,
|
||||
signupMutation,
|
||||
unlikeCommentMutation,
|
||||
} from '../api/client/@tanstack/react-query.gen'
|
||||
import type { CommentData, Factor, ResAuth, ResIndexDetail } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, ARTICLE_CAT, articleMeta, cardBg, dayLabel, shortDay } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { Ic, StateBox } from './ui'
|
||||
|
||||
export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<SheetState>(null)
|
||||
const open = useCallback((s: Exclude<SheetState, null>) => setState(s), [])
|
||||
const close = useCallback(() => setState(null), [])
|
||||
const api = useMemo(() => ({ open, close }), [open, close])
|
||||
|
||||
// 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'required' && setState({ type: 'login' })), [])
|
||||
|
||||
return (
|
||||
<SheetContext value={api}>
|
||||
{children}
|
||||
<SheetHost state={state} onClose={close} />
|
||||
</SheetContext>
|
||||
)
|
||||
}
|
||||
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', region: '지역 바꾸기' } as const
|
||||
|
||||
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const [gakTitle, setGakTitle] = useState('')
|
||||
const [articleTitle, setArticleTitle] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current
|
||||
if (!el) return
|
||||
if (state && !el.open) el.showModal()
|
||||
if (!state && el.open) el.close()
|
||||
}, [state])
|
||||
|
||||
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
aria-label={title}
|
||||
onClose={onClose}
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose()
|
||||
}}
|
||||
className="b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)"
|
||||
>
|
||||
{state && (
|
||||
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white">
|
||||
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
|
||||
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-[#d5dce7]" aria-hidden="true" />
|
||||
<h3 className="m-0 text-[15px] font-extrabold">{title}</h3>
|
||||
<button type="button" onClick={onClose} aria-label="닫기" className="absolute right-3 bottom-2 grid size-[30px] cursor-pointer place-items-center text-xl text-(--ink2)">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
|
||||
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
|
||||
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
|
||||
{state.type === 'share' && <ShareSheet share={state.share} />}
|
||||
{state.type === 'comments' && <CommentsSheet postId={state.postId} />}
|
||||
{state.type === 'login' && <LoginSheet onDone={onClose} />}
|
||||
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||
</div>
|
||||
)}
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function Body({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cx('flex-1 overflow-auto px-4 pt-3.5 pb-[18px]', className)}>{children}</div>
|
||||
}
|
||||
|
||||
/* ---------- 각 계산 근거 ---------- */
|
||||
function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[]; size?: number }) {
|
||||
const c = size / 2
|
||||
const r = size / 2 - 34
|
||||
const n = factors.length
|
||||
const pt = (i: number, v: number) => {
|
||||
const a = -Math.PI / 2 + (i * 2 * Math.PI) / n
|
||||
return [c + Math.cos(a) * r * v, c + Math.sin(a) * r * v] as const
|
||||
}
|
||||
const ring = (v: number) => factors.map((_, i) => pt(i, v).join(',')).join(' ')
|
||||
return (
|
||||
<svg className="mx-auto mt-2 block w-full max-w-[250px]" viewBox={`0 0 ${size} ${size}`} role="img" aria-label={`${name} 요소별 점수`}>
|
||||
{[0.25, 0.5, 0.75, 1].map((v) => (
|
||||
<polygon key={v} points={ring(v)} fill={v === 1 ? '#f7f9fc' : 'none'} stroke="#d9e2ef" strokeWidth="1.5" />
|
||||
))}
|
||||
{factors.map((f, i) => (
|
||||
<line key={f.axis} x1={c} y1={c} x2={pt(i, 1)[0]} y2={pt(i, 1)[1]} stroke="#e3e9f2" strokeWidth="1.5" />
|
||||
))}
|
||||
<polygon points={factors.map((f, i) => pt(i, f.value / 100).join(',')).join(' ')} fill="rgb(255 122 69 / .38)" stroke="#ff7a45" strokeWidth="3" strokeLinejoin="round" />
|
||||
{factors.map((f, i) => (
|
||||
<circle key={f.axis} cx={pt(i, f.value / 100)[0]} cy={pt(i, f.value / 100)[1]} r="4.5" fill="#fff" stroke="#ff7a45" strokeWidth="2.5" />
|
||||
))}
|
||||
{factors.map((f, i) => (
|
||||
<text key={f.axis} x={pt(i, 1.2)[0]} y={pt(i, 1.2)[1]} textAnchor="middle" dominantBaseline="middle" fontFamily="Jua,sans-serif" fontSize="14" fill="#28304a">
|
||||
{f.label}
|
||||
</text>
|
||||
))}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) => void }) {
|
||||
const { region } = useRegion()
|
||||
const q = useQuery(getIndexOptions({ path: { index_id: indexId }, query: { region: region.code } }))
|
||||
const d: ResIndexDetail | undefined = q.data
|
||||
const g = d?.index
|
||||
|
||||
useEffect(() => {
|
||||
onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거')
|
||||
}, [g, onTitle])
|
||||
|
||||
if (!g) return <Body>{<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." className="mx-0" />}</Body>
|
||||
const factors = d.factors ?? []
|
||||
return (
|
||||
<Body>
|
||||
<div className="flex items-center gap-3">
|
||||
<Ic name={g.icon} className="w-[58px]" />
|
||||
<div>
|
||||
<h4 className="m-0 font-jua text-[22px] font-normal">{g.name}</h4>
|
||||
{d.description && <p className="mt-0.5 text-[13.5px] font-semibold text-(--ink2)">{d.description}</p>}
|
||||
</div>
|
||||
<b className="ml-auto font-bagel text-[42px] font-normal text-(--orange)">{g.score}</b>
|
||||
</div>
|
||||
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
|
||||
{g.trend && g.trend.length > 0 && (
|
||||
<div className="mt-2.5 grid grid-cols-3 gap-2">
|
||||
{g.trend.map((t, j) => (
|
||||
<div key={t.day} className="rounded-2xl bg-[#f3f6fb] p-2.5 text-center">
|
||||
<small className="text-xs font-extrabold text-(--ink2)">{dayLabel(t.day, j)}</small>
|
||||
<b className="block font-bagel text-2xl font-normal text-(--orange)">{t.score}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-3.5 flex flex-col gap-2.5">
|
||||
{factors.map((f) => (
|
||||
<div key={f.axis} className="grid grid-cols-[50px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
||||
<span>{f.label}</span>
|
||||
<i className="block h-[9px] overflow-hidden rounded-full bg-[#e3eaf4]">
|
||||
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${f.value}%` }} />
|
||||
</i>
|
||||
<em className="text-right text-xs text-(--ink2) not-italic">비중 {f.weight}%</em>
|
||||
<p className="col-start-2 col-end-4 -mt-0.5 text-[12.5px] font-semibold text-(--ink2)">{f.note}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3.5 flex flex-col gap-1.5 text-[13px] font-semibold text-(--ink2)">
|
||||
{d.zero_reason && (
|
||||
<span>
|
||||
<b className="text-(--heart)">오늘 0점인 이유:</b> {d.zero_reason}
|
||||
</span>
|
||||
)}
|
||||
{d.zero_rules && (
|
||||
<span>
|
||||
<b className="text-(--ink)">바로 0점:</b> {d.zero_rules}
|
||||
</span>
|
||||
)}
|
||||
{d.limit && (
|
||||
<span>
|
||||
<b className="text-(--ink)">반영 못 한 것:</b> {d.limit}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 읽을거리 ---------- */
|
||||
function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t: string) => void }) {
|
||||
const q = useQuery(getArticleOptions({ path: { article_id: articleId } }))
|
||||
const a = q.data?.article
|
||||
|
||||
useEffect(() => {
|
||||
onTitle(a ? (ARTICLE_CAT[a.category]?.[0] ?? '') : '')
|
||||
}, [a, onTitle])
|
||||
|
||||
if (!a) return <Body>{<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." className="mx-0" />}</Body>
|
||||
return (
|
||||
<Body>
|
||||
<div className={cx('mb-3.5 grid h-[150px] place-items-center rounded-[20px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-24" />
|
||||
</div>
|
||||
<p className="text-[13px] font-extrabold text-(--ink2)">{articleMeta(a)}</p>
|
||||
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">{a.title}</h4>
|
||||
{(q.data?.body ?? []).map((t) => (
|
||||
<p key={t} className="mb-2.5 text-[15px] leading-[1.7]">
|
||||
{t}
|
||||
</p>
|
||||
))}
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 이번 주 특집 ---------- */
|
||||
function SeasonWeekSheet() {
|
||||
const { open } = useSheet()
|
||||
const q = useQuery(getSeasonWeekOptions())
|
||||
const w = q.data
|
||||
if (!w?.headline) return <Body>{<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty="이번 주 특집이 아직 없어요." className="mx-0" />}</Body>
|
||||
return (
|
||||
<Body>
|
||||
<div className="mb-3.5 grid h-[150px] place-items-center rounded-[20px] b-bg-peach">
|
||||
<Ic name="maple" className="w-24" />
|
||||
</div>
|
||||
<p className="text-[13px] font-extrabold text-(--ink2)">이번 주 특집 · {w.week}번째 주</p>
|
||||
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">{w.headline}</h4>
|
||||
{(w.poem_lines ?? []).length > 0 && (
|
||||
<p className="mb-2.5 font-batang text-[17px] leading-[1.7]">
|
||||
{w.poem_lines?.join(' ')}
|
||||
{w.author && <small className="block font-sans text-xs font-semibold text-(--ink3)">{w.author}</small>}
|
||||
</p>
|
||||
)}
|
||||
{w.term_now && w.term_next && (
|
||||
<p className="mb-2.5 text-[15px] leading-[1.7]">
|
||||
지금 절기는 {w.term_now.name}({shortDay(w.term_now.day)}), 다음 절기는 {w.term_next.name}({shortDay(w.term_next.day)})예요.
|
||||
</p>
|
||||
)}
|
||||
{(w.news ?? []).map((n) => (
|
||||
<button key={n.code} type="button" onClick={() => open({ type: 'article', articleId: n.article_id })} className="flex w-full cursor-pointer items-center gap-2.5 border-b-[1.5px] border-(--line) py-2.5 text-left font-jua text-base">
|
||||
<Ic name={n.icon} className="w-8" />
|
||||
{n.title}
|
||||
</button>
|
||||
))}
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 보내기 ---------- */
|
||||
function ShareSheet({ share }: { share: SharePayload }) {
|
||||
const { region } = useRegion()
|
||||
const opts = [...share.messages, '직접 쓰기']
|
||||
const [pick, setPick] = useState(0)
|
||||
const [mine, setMine] = useState('')
|
||||
const [toast, setToast] = useState('')
|
||||
const isMine = pick === opts.length - 1
|
||||
const msg = isMine ? mine : opts[pick]
|
||||
|
||||
const url = window.location.origin
|
||||
const text = `${msg} — ${share.title} · 날씨각`
|
||||
|
||||
// 휴대폰 기본 공유창. 없거나 실패하면 링크 복사로 대신한다.
|
||||
const shareNative = () => {
|
||||
if (!navigator.share) {
|
||||
copy()
|
||||
return
|
||||
}
|
||||
navigator.share({ title: share.title, text, url }).then(
|
||||
() => setToast('보냈어요'),
|
||||
(e: unknown) => {
|
||||
if (e instanceof DOMException && e.name === 'AbortError') return
|
||||
copy()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const copy = () => {
|
||||
if (!navigator.clipboard) {
|
||||
setToast('복사가 막혀 있어요')
|
||||
return
|
||||
}
|
||||
navigator.clipboard.writeText(`${text} ${url}`).then(
|
||||
() => setToast('보낼 말과 링크를 복사했어요'),
|
||||
() => setToast('복사가 막혀 있어요. 길게 눌러 복사해 주세요'),
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Body>
|
||||
<div className={cx('flex items-center gap-3 rounded-[20px] p-3.5', `b-bg-${share.bg}`)}>
|
||||
<Ic name={share.icon} className="w-[58px]" />
|
||||
<div>
|
||||
<b className="block font-jua text-[19px] font-normal">{share.title}</b>
|
||||
<small className="font-bold opacity-80">날씨각 · {region.name}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-col gap-1.5" role="radiogroup" aria-label="함께 보낼 말">
|
||||
{opts.map((o, k) => (
|
||||
<label key={o} className="flex cursor-pointer items-center gap-2.5 rounded-[14px] bg-[#f3f6fb] px-3 py-2.5 font-semibold">
|
||||
<input type="radio" name="share-msg" checked={pick === k} onChange={() => setPick(k)} className="accent-(--orange)" />
|
||||
{o}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{isMine && (
|
||||
<textarea
|
||||
value={mine}
|
||||
onChange={(e) => setMine(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={80}
|
||||
placeholder="예: 오늘 한강 갈래? 🌇"
|
||||
aria-label="보낼 말 직접 쓰기"
|
||||
className="mt-1.5 w-full resize-none rounded-[14px] border border-[#dfe5ee] px-3 py-2.5"
|
||||
/>
|
||||
)}
|
||||
<div className="mt-3.5 grid grid-cols-2 gap-2">
|
||||
<button type="button" onClick={shareNative} className="cursor-pointer rounded-[16px] bg-(--orange-deep) py-3 font-jua text-base text-white">
|
||||
공유하기
|
||||
</button>
|
||||
<button type="button" onClick={copy} className="cursor-pointer rounded-[16px] bg-(--ink) py-3 font-jua text-base text-white">
|
||||
링크 복사
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-3 min-h-5 text-center text-[13px] font-bold text-[#1f9d62]" aria-live="polite">
|
||||
{toast}
|
||||
</p>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 댓글 ---------- */
|
||||
const AV_COLORS = ['#ff8e4e', '#4f97e3', '#1f9d62', '#7a5cd6', '#d6457a', '#c2471b']
|
||||
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
|
||||
|
||||
function CommentRow({ c, index, postId }: { c: CommentData; index: number; postId: number }) {
|
||||
const { region } = useRegion()
|
||||
const { loggedIn } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const queryClient = useQueryClient()
|
||||
const [liked, setLiked] = useState(c.liked)
|
||||
const [count, setCount] = useState(c.like_count)
|
||||
const like = useMutation(likeCommentMutation())
|
||||
const unlike = useMutation(unlikeCommentMutation())
|
||||
const remove = useMutation(deleteCommentMutation())
|
||||
|
||||
const toggle = () => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const next = !liked
|
||||
setLiked(next)
|
||||
setCount((n) => n + (next ? 1 : -1))
|
||||
;(next ? like : unlike).mutate(
|
||||
{ path: { comment_id: c.comment_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
setLiked(!!res.liked)
|
||||
if (res.like_count != null) setCount(res.like_count)
|
||||
},
|
||||
onError: () => {
|
||||
setLiked(!next)
|
||||
setCount(c.like_count)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const del = () =>
|
||||
remove.mutate(
|
||||
{ path: { comment_id: c.comment_id } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: listCommentsQueryKey({ path: { post_id: postId } }) })
|
||||
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 py-2">
|
||||
<span className="grid size-[34px] place-items-center rounded-full text-[13px] font-extrabold text-white" style={{ background: AV_COLORS[(c.nickname.charCodeAt(0) + index) % AV_COLORS.length] }} aria-hidden="true">
|
||||
{c.nickname[0]}
|
||||
</span>
|
||||
<div>
|
||||
<p className="m-0 text-sm">
|
||||
<b className="mr-1.5 font-extrabold">{c.nickname}</b>
|
||||
{c.body}
|
||||
</p>
|
||||
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
|
||||
{ago(c.created_at)} · 좋아요 {count}개
|
||||
{c.mine && (
|
||||
<>
|
||||
{' · '}
|
||||
<button type="button" onClick={del} disabled={remove.isPending} className="cursor-pointer font-bold text-(--ink3) underline-offset-2 hover:underline">
|
||||
지우기
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</small>
|
||||
{remove.isError && <small className="block text-xs font-bold text-(--heart)">지우지 못했어요. 다시 해 주세요.</small>}
|
||||
</div>
|
||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className="cursor-pointer pt-1">
|
||||
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommentsSheet({ postId }: { postId: number }) {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const { loggedIn, me } = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const list = useQuery(listCommentsOptions({ path: { post_id: postId } }))
|
||||
const add = useMutation(addCommentMutation())
|
||||
const [text, setText] = useState('')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const comments = list.data?.comments ?? []
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const body = text.trim()
|
||||
if (!body) return
|
||||
add.mutate(
|
||||
{ path: { post_id: postId }, body: { body } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setText('')
|
||||
queryClient.invalidateQueries({ queryKey: listCommentsQueryKey({ path: { post_id: postId } }) })
|
||||
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Body>
|
||||
{comments.length ? (
|
||||
comments.map((c, k) => <CommentRow key={c.comment_id} c={c} index={k} postId={postId} />)
|
||||
) : list.isSuccess ? (
|
||||
<p className="my-6 text-center font-semibold text-(--ink3)">
|
||||
아직 댓글이 없어요.
|
||||
<br />첫 댓글을 남겨 보세요.
|
||||
</p>
|
||||
) : (
|
||||
<StateBox loading={list.isPending} error={list.error} onRetry={() => list.refetch()} className="mx-0" />
|
||||
)}
|
||||
</Body>
|
||||
<div className="flex justify-around pt-1 pb-2 text-[22px]" role="group" aria-label="빠른 이모지">
|
||||
{EMOJIS.map((e) => (
|
||||
<button
|
||||
key={e}
|
||||
type="button"
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
setText((t) => (t + e).slice(0, 60))
|
||||
inputRef.current?.focus()
|
||||
}}
|
||||
>
|
||||
{e}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{add.isError && (
|
||||
<p className="px-4 pb-1 text-center text-xs font-bold text-(--heart)" role="alert">
|
||||
댓글을 올리지 못했어요. 다시 해 주세요.
|
||||
</p>
|
||||
)}
|
||||
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))]">
|
||||
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<button type="submit" disabled={add.isPending || (loggedIn && !text.trim())} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
|
||||
게시
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 로그인 ---------- */
|
||||
const AUTH_ERRORS: Record<string, string> = {
|
||||
AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.',
|
||||
AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.',
|
||||
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8자 이상, 닉네임은 2~12자로 써 주세요.',
|
||||
}
|
||||
|
||||
function LoginSheet({ onDone }: { onDone: () => void }) {
|
||||
const { me, logout } = useAuth()
|
||||
const [mode, setMode] = useState<'login' | 'signup'>('login')
|
||||
const [loginId, setLoginId] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [nickname, setNickname] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const login = useMutation(loginMutation())
|
||||
const signup = useMutation(signupMutation())
|
||||
const pending = login.isPending || signup.isPending
|
||||
|
||||
const done = (res: ResAuth) => {
|
||||
if (!res.result?.success || !res.access_token) {
|
||||
setError(AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.')
|
||||
return
|
||||
}
|
||||
setTokens(res.access_token, res.refresh_token ?? null)
|
||||
onDone()
|
||||
}
|
||||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: done, onError: fail })
|
||||
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: done, onError: fail })
|
||||
}
|
||||
|
||||
if (me)
|
||||
return (
|
||||
<Body className="flex flex-col gap-2.5 text-center">
|
||||
<p className="text-sm font-semibold text-(--ink2)">{me.nickname}(으)로 로그인했어요.</p>
|
||||
<button type="button" onClick={logout} className="cursor-pointer rounded-[14px] bg-[#f3f6fb] p-[13px] text-[15px] font-extrabold text-(--ink)">
|
||||
로그아웃
|
||||
</button>
|
||||
</Body>
|
||||
)
|
||||
|
||||
const field = 'w-full rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3'
|
||||
return (
|
||||
<Body>
|
||||
<form onSubmit={submit} className="flex flex-col gap-2.5">
|
||||
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·저장·댓글은 로그인한 뒤에 할 수 있어요.</p>
|
||||
<div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입">
|
||||
{(
|
||||
[
|
||||
['login', '로그인'],
|
||||
['signup', '처음이에요'],
|
||||
] as const
|
||||
).map(([m, l]) => (
|
||||
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full py-2 text-sm font-extrabold', mode === m ? 'bg-(--ink) text-white' : 'text-(--ink2)')}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<input value={loginId} onChange={(e) => setLoginId(e.target.value)} autoComplete="username" required minLength={4} maxLength={20} placeholder="아이디" aria-label="아이디" className={field} />
|
||||
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'} required minLength={8} placeholder="비밀번호 (8자 이상)" aria-label="비밀번호" className={field} />
|
||||
{mode === 'signup' && <input value={nickname} onChange={(e) => setNickname(e.target.value)} required minLength={2} maxLength={12} placeholder="닉네임 (2~12자)" aria-label="닉네임" className={field} />}
|
||||
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
|
||||
{error}
|
||||
</p>
|
||||
<button type="submit" disabled={pending} className="cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
{mode === 'login' ? '로그인' : '가입하고 시작하기'}
|
||||
</button>
|
||||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
|
||||
나중에 할게요
|
||||
</button>
|
||||
</form>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 지역 ---------- */
|
||||
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const
|
||||
|
||||
function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
const { region, setRegion, locate, locateStatus } = useRegion()
|
||||
const { me, logout } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const [q, setQ] = useState('')
|
||||
const deferred = useDeferredValue(q.trim())
|
||||
const list = useQuery(listRegionsOptions(deferred ? { query: { q: deferred } } : undefined))
|
||||
const regions = list.data?.regions ?? []
|
||||
|
||||
return (
|
||||
<Body>
|
||||
<button type="button" onClick={locate} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
지금 위치로 찾기
|
||||
</button>
|
||||
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
||||
{LOCATE_TEXT[locateStatus]}
|
||||
</p>
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="구 이름으로 찾기 (예: 마포)" aria-label="구 이름으로 찾기" className="mt-1 w-full rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<StateBox loading={list.isPending} error={list.error} onRetry={() => list.refetch()} empty={list.isSuccess && !regions.length ? '찾는 구가 없어요.' : undefined} className="mx-0" />
|
||||
<ul className="mt-2 flex flex-col">
|
||||
{regions.map((r) => (
|
||||
<li key={r.code}>
|
||||
<button
|
||||
type="button"
|
||||
aria-current={r.code === region.code ? 'true' : undefined}
|
||||
onClick={() => {
|
||||
setRegion(r)
|
||||
onDone()
|
||||
}}
|
||||
className={cx('flex w-full cursor-pointer items-center justify-between border-b-[1.5px] border-(--line) px-1 py-3 text-left font-jua text-[17px]', r.code === region.code && 'text-(--orange)')}
|
||||
>
|
||||
{r.name}
|
||||
{r.code === region.code && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
|
||||
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·저장·댓글을 쓸 수 있어요'}
|
||||
<button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)">
|
||||
{me ? '로그아웃' : '로그인'}
|
||||
</button>
|
||||
</p>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { RegionData, SpotData } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { clockShort, dayLabel, timeWords } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { Rail, Sec, StateBox } from './ui'
|
||||
|
||||
const W = 400
|
||||
const H = 260
|
||||
const BLOCKS = [
|
||||
[20, 20, 90, 60],
|
||||
[130, 18, 100, 52],
|
||||
[262, 22, 110, 48],
|
||||
[24, 190, 110, 54],
|
||||
[170, 196, 90, 50],
|
||||
[290, 180, 92, 62],
|
||||
]
|
||||
|
||||
/** 내 구 중심을 기준으로 명소를 km 단위로 놓고, 해 지는 방향을 그린다 */
|
||||
function SpotMap({ region, spots, azimuth }: { region: RegionData; spots: SpotData[]; azimuth: number | null | undefined }) {
|
||||
const kx = 111 * Math.cos((region.lat * Math.PI) / 180)
|
||||
const pts = spots.map((s) => ({ no: s.no, x: (s.lon - region.lon) * kx, y: (s.lat - region.lat) * 111 }))
|
||||
const maxX = Math.max(0.5, ...pts.map((p) => Math.abs(p.x)))
|
||||
const maxY = Math.max(0.5, ...pts.map((p) => Math.abs(p.y)))
|
||||
const scale = Math.min(160 / maxX, 95 / maxY)
|
||||
const cx0 = W / 2
|
||||
const cy0 = H / 2
|
||||
const az = ((azimuth ?? 270) * Math.PI) / 180
|
||||
const dir = (len: number, turn = 0) => [cx0 + Math.sin(az + turn) * len, cy0 - Math.cos(az + turn) * len] as const
|
||||
const tip = dir(190)
|
||||
const label = dir(120)
|
||||
|
||||
return (
|
||||
<div className="mx-3 mt-3 overflow-hidden rounded-[26px] bg-[#eef2e8] shadow-[inset_0_0_0_2px_#e1e7da]">
|
||||
<svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={`${region.name} 주변 노을 명소 지도`} className="block h-auto w-full">
|
||||
<rect width={W} height={H} fill="#eef2e8" />
|
||||
{BLOCKS.map(([x, y, w, h]) => (
|
||||
<rect key={`${x}-${y}`} x={x} y={y} width={w} height={h} rx="10" fill="#e1e7da" />
|
||||
))}
|
||||
<path d={`M${W / 2 - 10} 0 L${W / 2 + 4} ${H}`} stroke="#fff" strokeWidth="9" />
|
||||
<path d={`M0 ${H / 2 - 30} H${W}`} stroke="#fff" strokeWidth="10" />
|
||||
{azimuth != null && (
|
||||
<>
|
||||
<path d={`M${cx0} ${cy0} L${dir(260, -0.3).join(' ')} L${dir(260, 0.3).join(' ')} Z`} fill="#ff8e4e" opacity=".18" />
|
||||
<path d={`M${cx0} ${cy0} L${tip.join(' ')}`} stroke="#ff7a45" strokeWidth="3" strokeDasharray="7 6" />
|
||||
<text x={Math.min(W - 110, Math.max(8, label[0] - 50))} y={label[1] + 26} fontFamily="Jua,sans-serif" fontSize="14" fill="#d4552a">
|
||||
해 지는 쪽 {azimuth}°
|
||||
</text>
|
||||
</>
|
||||
)}
|
||||
<circle cx={cx0} cy={cy0} r="13" fill="#4f97e3" opacity=".25" />
|
||||
<circle cx={cx0} cy={cy0} r="6" fill="#4f97e3" stroke="#fff" strokeWidth="2" />
|
||||
<text x={cx0 + 14} y={cy0 + 18} fontFamily="Pretendard Variable,sans-serif" fontWeight="800" fontSize="11" fill="#2f6fb7">
|
||||
지금 여기
|
||||
</text>
|
||||
{pts.map((p) => (
|
||||
<g key={p.no}>
|
||||
<circle cx={cx0 + p.x * scale} cy={cy0 - p.y * scale} r="13" fill="#ff7a45" stroke="#fff" strokeWidth="3" />
|
||||
<text x={cx0 + p.x * scale} y={cy0 - p.y * scale + 5} textAnchor="middle" fontFamily="Bagel Fat One,sans-serif" fontSize="14" fill="#fff">
|
||||
{p.no}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Li({ no, title, sub, right, meter, mine = false }: { no: number; title: string; sub?: string | null; right: string; meter?: number; mine?: boolean }) {
|
||||
return (
|
||||
<li className={cx('grid grid-cols-[34px_1fr_auto] items-center gap-2.5 border-b-[1.5px] border-(--line) px-1 py-3 last:border-b-0', mine && 'rounded-2xl bg-white')}>
|
||||
<span className="text-center font-bagel text-xl text-(--orange)">{no}</span>
|
||||
<span>
|
||||
<b className="block font-jua text-[17px] font-normal">
|
||||
{title}
|
||||
{mine && <small className="ml-1.5 font-sans text-xs font-extrabold text-(--rain)">내 지역</small>}
|
||||
</b>
|
||||
{sub && <small className="text-[12.5px] font-semibold text-(--ink2)">{sub}</small>}
|
||||
{meter != null && (
|
||||
<span className="mt-[5px] block h-1.5 overflow-hidden rounded-full bg-[#eef1f6]">
|
||||
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,#ff6f8e)]" style={{ width: `${meter}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<em className="font-jua text-base not-italic">{right}</em>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
export function SkyPage() {
|
||||
const { region } = useRegion()
|
||||
const sky = useQuery(getSkyOptions({ query: { region: region.code } }))
|
||||
const ranking = useQuery(getSkyRankingOptions())
|
||||
const s = sky.data?.sunset
|
||||
const times = s?.best_times ?? []
|
||||
const peak = times.find((t) => t.kind === 'peak')
|
||||
const spots = sky.data?.spots ?? []
|
||||
const days = sky.data?.days ?? []
|
||||
const items = (ranking.data?.items ?? []).slice(0, 8)
|
||||
|
||||
return (
|
||||
<section aria-label="노을">
|
||||
{s ? (
|
||||
<div className="relative mx-3 mt-1 min-h-[300px] overflow-hidden rounded-[32px] bg-[linear-gradient(180deg,#7e6fe6,#f08aa2_58%,#ffc28a)] px-5 pt-5 pb-16 text-white">
|
||||
<div className="b-skyline pointer-events-none absolute inset-0 [--sky-h:22%]" aria-hidden="true" />
|
||||
<p className="relative m-0 text-[13px] font-extrabold opacity-90">오늘 노을 · {region.name}</p>
|
||||
<b className="relative mt-1.5 block font-bagel text-[96px] leading-[0.9] font-normal">{s.score}</b>
|
||||
<p className="relative m-0 font-jua text-[29px] leading-tight">
|
||||
{s.grade_label}
|
||||
{peak && ` · ${timeWords(peak.at)}이 절정`}
|
||||
</p>
|
||||
{times.length > 0 && (
|
||||
<div className="relative z-[1] mt-[18px]">
|
||||
<div className="h-2.5 rounded-full bg-[linear-gradient(90deg,#ffd27a,#ff7a6e_50%,#6a5bd6)]" />
|
||||
<div className="mt-1.5 flex justify-between text-[12.5px] font-extrabold">
|
||||
{times.map((t, i) => (
|
||||
<span key={t.kind} className={cx(i === 1 && 'text-center', i === times.length - 1 && i > 0 && 'text-right')}>
|
||||
<b className="block font-bagel text-lg font-normal">{clockShort(t.at)}</b>
|
||||
{t.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<StateBox loading={sky.isPending} error={sky.error} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." />
|
||||
)}
|
||||
{times.length > 0 && (
|
||||
<>
|
||||
<Sec title="오늘의 노을 3컷" sub="옆으로 넘겨 보세요" />
|
||||
<Rail label="오늘의 노을 3컷">
|
||||
{times.map((t, i) => (
|
||||
<div key={t.kind} className={cx('b-skyline relative h-[150px] w-[230px] overflow-hidden rounded-[22px] px-3.5 py-2.5 font-bagel text-2xl text-white [--sky-h:30%]', `b-cut-${Math.min(i + 1, 3)}`)}>
|
||||
<span className="relative z-[1]">
|
||||
{clockShort(t.at)}
|
||||
<small className="block font-jua text-sm">{t.label}</small>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</Rail>
|
||||
</>
|
||||
)}
|
||||
<Sec title="가까운 노을 명소" sub={sky.data?.sunset_azimuth != null ? `해 지는 쪽 ${sky.data.sunset_azimuth}° · 서쪽이 트인 곳` : '서쪽이 트인 곳'} />
|
||||
{spots.length ? (
|
||||
<>
|
||||
<SpotMap region={region} spots={spots} azimuth={sky.data?.sunset_azimuth} />
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{spots.map((p) => (
|
||||
<Li key={p.no} no={p.no} title={p.name} sub={p.description} right={`${p.distance_km}km`} />
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<StateBox loading={sky.isPending} error={sky.error} empty="이 지역은 아직 등록된 노을 명소가 없어요." />
|
||||
)}
|
||||
<Sec title="전국 노을 순위" sub={items[0] ? `오늘 기준 · 1위 ${items[0].name} ${items[0].score}점` : '오늘 기준'} />
|
||||
{items.length ? (
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{items.map((r) => (
|
||||
<Li key={r.region_code} no={r.rank} title={r.name} sub={r.note} right={String(r.score)} meter={r.score} mine={r.region_code === region.code} />
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<StateBox loading={ranking.isPending} error={ranking.error} onRetry={() => ranking.refetch()} empty="순위가 아직 없어요." />
|
||||
)}
|
||||
{days.length > 0 && (
|
||||
<>
|
||||
<Sec title="앞으로 3일" />
|
||||
<div className="grid grid-cols-3 gap-2 p-3">
|
||||
{days.map((d, i) => (
|
||||
<div key={d.day} className="rounded-[20px] bg-white p-3 text-center shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<small className="text-[12.5px] font-extrabold text-(--ink2)">{dayLabel(d.day, i)}</small>
|
||||
<b className={cx('block font-bagel text-[30px] font-normal', d.score < 50 ? 'text-(--ink3)' : 'text-[#d6457a]')}>{d.score}</b>
|
||||
<span className="text-xs font-bold text-(--ink2)">{d.grade_label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { Fragment, useEffect, useState, type ReactNode } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { BandArticle, BandEvent, Hero as HeroData, ResWeatherToday, TopIndex } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, fall, kindOfHour, kst, MEDALS, sidoOf, WEEKDAYS, type TimeKind } from './lib'
|
||||
import { PostCard } from './Post'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Ic, Rail, Sec, StateBox } from './ui'
|
||||
import { deg, skyText, slotAt } from './weatherText'
|
||||
|
||||
type Mode = 'now' | TimeKind
|
||||
|
||||
const MODES: [Mode, string][] = [
|
||||
['now', '지금 시간'],
|
||||
['morning', '아침'],
|
||||
['day', '낮'],
|
||||
['sunset', '노을'],
|
||||
['night', '밤'],
|
||||
]
|
||||
|
||||
// 미리보기 시간대마다 보여 줄 시계와 그 시각의 예보 칸
|
||||
const PREVIEW: Record<TimeKind, { label: string; clock: string; hour: number }> = {
|
||||
morning: { label: '아침', clock: '07:40', hour: 7 },
|
||||
day: { label: '낮', clock: '13:20', hour: 13 },
|
||||
sunset: { label: '노을', clock: '18:25', hour: 18 },
|
||||
night: { label: '밤', clock: '22:10', hour: 22 },
|
||||
}
|
||||
|
||||
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
|
||||
const ORB_POS = [
|
||||
{ left: '66%', top: '6px', d: '.5s', f: '4.4s' },
|
||||
{ left: '0%', top: '34px', d: '.7s', f: '5.1s' },
|
||||
{ left: '4%', top: '184px', d: '.9s', f: '4.7s' },
|
||||
]
|
||||
|
||||
function useNow(ms = 20000) {
|
||||
const [now, setNow] = useState(() => new Date())
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setNow(new Date()), ms)
|
||||
return () => clearInterval(id)
|
||||
}, [ms])
|
||||
return now
|
||||
}
|
||||
|
||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday }
|
||||
|
||||
function Hero({ hero, today }: HeroProps) {
|
||||
const { open } = useSheet()
|
||||
const [mode, setMode] = useState<Mode>('now')
|
||||
const clock = useNow()
|
||||
const t = kst(clock)
|
||||
const kind = mode === 'now' ? (hero?.sky_mode ?? kindOfHour(t.h)) : mode
|
||||
const slots = today?.slots ?? []
|
||||
const slot = slots.length ? slotAt(slots, mode === 'now' ? t.h : PREVIEW[mode].hour) : undefined
|
||||
// 지금은 /v1/feed hero 값을, 미리보기는 그 시각의 예보 칸을 쓴다
|
||||
const temp = mode === 'now' && hero ? hero.temp_c : slot?.temp_c
|
||||
const feels = mode === 'now' && hero ? hero.feels_c : slot?.feels_c
|
||||
const top3 = hero?.top3 ?? []
|
||||
const who = kind === 'night' ? 'bear' : 'rabbit'
|
||||
|
||||
return (
|
||||
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[32px] px-[18px] pt-4 pb-[18px]" data-t={kind}>
|
||||
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
|
||||
{STARS.map((s, i) => (
|
||||
<i key={i} className="absolute size-[3px] rounded-full bg-white shadow-[0_0_6px_#fff]" style={s} />
|
||||
))}
|
||||
</div>
|
||||
<div className="relative z-[3] flex flex-wrap gap-1.5" role="group" aria-label="시간대 배경 미리보기">
|
||||
{MODES.map(([m, l]) => (
|
||||
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full px-2.5 py-[5px] text-xs font-bold', mode === m ? 'bg-(--ink) text-white' : 'bg-white/55 text-(--ink)')}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="relative z-[3] mt-3 flex items-end justify-between">
|
||||
<div>
|
||||
<p className="mb-1 text-[13.5px] font-bold opacity-85">
|
||||
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 · {mode === 'now' ? '지금' : `${PREVIEW[mode].label} 미리보기`}
|
||||
</p>
|
||||
<div className="font-bagel text-[60px] leading-none">{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<b className="font-bagel text-[42px] leading-none font-normal">{temp != null ? deg(temp) : '--°'}</b>
|
||||
<span className="block text-[12.5px] font-bold opacity-85">{temp != null ? `체감 ${deg(feels)}${slot ? ` · ${skyText(slot)}` : ''}` : '날씨를 불러오는 중'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative z-[3] mt-3 grid grid-cols-2 gap-2.5">
|
||||
<div className="b-stat flex items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
|
||||
<Ic name="thermo" className="w-9" />
|
||||
<div>
|
||||
<small className="block text-xs font-bold opacity-80">불쾌지수</small>
|
||||
<b className="font-jua text-lg font-normal">{hero?.discomfort != null ? `${hero.discomfort} · ${hero.discomfort_label ?? ''}` : '-'}</b>
|
||||
</div>
|
||||
</div>
|
||||
<div className="b-stat flex items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
|
||||
<Ic name="umbrella" className="w-9" />
|
||||
<div>
|
||||
<small className="block text-xs font-bold opacity-80">지금 비</small>
|
||||
<b className="font-jua text-lg font-normal">{hero?.will_rain_2h == null ? '-' : hero.will_rain_2h ? '2시간 안에 비' : '2시간 없음'}</b>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-5 h-[286px]">
|
||||
<span className="b-cloud b-fall top-6 left-[6%] h-[30px] w-[84px]" style={fall('.1s', '6s')} aria-hidden="true" />
|
||||
<div className="b-sun b-fall absolute top-10 left-1/2 -ml-[82px] grid aspect-square w-[164px] place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
|
||||
<span>
|
||||
<b className="block font-bagel text-[56px] leading-[0.9] font-normal">{hero?.weather_score ?? '-'}</b>
|
||||
<small className="mt-0.5 block font-jua text-[14.5px]">오늘 날씨 점수</small>
|
||||
</span>
|
||||
</div>
|
||||
<span className="b-cloud b-fall top-[188px] left-[54%] h-10 w-[118px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
|
||||
{top3.map((g, i) => (
|
||||
<button
|
||||
key={g.index_id}
|
||||
type="button"
|
||||
onClick={() => open({ type: 'gak', indexId: g.index_id })}
|
||||
aria-label={`${i + 1}위 ${g.name} ${g.score}점, 계산 근거 보기`}
|
||||
className="b-fall absolute z-[2] flex w-24 cursor-pointer flex-col items-center"
|
||||
style={{ left: ORB_POS[i].left, top: ORB_POS[i].top, ...fall(ORB_POS[i].d, ORB_POS[i].f) }}
|
||||
>
|
||||
<span className={cx('relative', i === 0 ? 'w-[78px]' : 'w-[60px]')}>
|
||||
<Ic name={g.icon} className="w-full drop-shadow-[0_10px_12px_rgb(40_48_74/0.16)]" />
|
||||
<Ic name={MEDALS[i]} className="absolute -top-2 -left-3.5 w-[30px]" />
|
||||
</span>
|
||||
<span className="b-orb-label font-jua text-sm whitespace-nowrap">
|
||||
{i + 1}위 {g.name} <em className="font-bagel text-(--orange) not-italic">{g.score}</em>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{hero?.bubble && (
|
||||
<div className="relative z-[3] flex items-end gap-2">
|
||||
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[50px] drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
|
||||
<span className="mb-3 rounded-[20px_20px_20px_6px] bg-white px-3.5 py-[9px] font-jua text-base text-(--ink) shadow-[0_8px_16px_rgb(40_48_74/0.1)]">{hero.bubble}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Stories({ items }: { items: TopIndex[] }) {
|
||||
const { open } = useSheet()
|
||||
return (
|
||||
<Rail label="오늘의 각 순위">
|
||||
{items.map((g, i) => (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={`${g.rank}위 ${g.name} ${g.score}점`} className="flex w-[72px] cursor-pointer flex-col items-center gap-1">
|
||||
<span className={cx('relative size-[68px] rounded-full p-[3px]', g.score < 50 ? 'bg-[#d6deea]' : 'b-ring')}>
|
||||
<i className="grid size-full place-items-center rounded-full border-[3px] border-(--page) bg-(--page)">
|
||||
<Ic name={g.icon} className="w-[42px]" />
|
||||
</i>
|
||||
{i < 3 && <Ic name={MEDALS[i]} className="absolute -right-1 -bottom-1 w-[25px]" />}
|
||||
</span>
|
||||
<b className="font-jua text-[13px] font-normal whitespace-nowrap">{g.name}</b>
|
||||
<em className="font-bagel text-[12.5px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||
</button>
|
||||
))}
|
||||
</Rail>
|
||||
)
|
||||
}
|
||||
|
||||
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
|
||||
return (
|
||||
<section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
|
||||
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
|
||||
{children}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function EventsBand({ events }: { events: BandEvent[] }) {
|
||||
const { region } = useRegion()
|
||||
return (
|
||||
<Band tone={1} title={`이번 주 ${sidoOf(region.name)} 행사`} sub="날씨까지 같이 보고 골라요" to="/week">
|
||||
<Rail>
|
||||
{events.map((e, i) => (
|
||||
<Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<span className={cx('relative grid h-[116px] place-items-center', `b-bg-${cardBg(e.icon, i)}`)}>
|
||||
<span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', e.status_label === '진행 중' ? 'bg-[#1f9d62]' : 'bg-(--orange)')}>{e.status_label}</span>
|
||||
<Ic name={e.icon} className="w-[76px]" />
|
||||
</span>
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<b className="block font-jua text-[16.5px] leading-snug font-normal">{e.name}</b>
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</Rail>
|
||||
</Band>
|
||||
)
|
||||
}
|
||||
|
||||
function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) {
|
||||
const { open } = useSheet()
|
||||
return (
|
||||
<Band tone={2} title="지금 뜨는 각 TOP 5" sub={sub} to="/gak">
|
||||
<Rail>
|
||||
{items.slice(0, 5).map((g, i) => (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="relative flex w-[138px] cursor-pointer flex-col items-start gap-1 rounded-[22px] bg-white p-3 text-left shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="absolute top-2 left-2 w-[26px]" /> : <span className="absolute top-2.5 left-3 font-jua text-(--ink3)">{i + 1}위</span>}
|
||||
<Ic name={g.icon} className="w-[58px] self-center" />
|
||||
<b className="font-jua text-base font-normal">{g.name}</b>
|
||||
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||
{g.summary && <small className="text-xs font-semibold text-(--ink2)">{g.summary}</small>}
|
||||
</button>
|
||||
))}
|
||||
</Rail>
|
||||
</Band>
|
||||
)
|
||||
}
|
||||
|
||||
function SeasonBand({ news }: { news: BandArticle[] }) {
|
||||
const { open } = useSheet()
|
||||
return (
|
||||
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season">
|
||||
<Rail>
|
||||
{news.map((a) => (
|
||||
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<span className={cx('grid h-[116px] place-items-center', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-[76px]" />
|
||||
</span>
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<b className="block font-jua text-[16.5px] leading-snug font-normal">{a.title}</b>
|
||||
<small className="text-[12.5px] font-semibold text-(--ink2)">{a.meta}</small>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</Rail>
|
||||
</Band>
|
||||
)
|
||||
}
|
||||
|
||||
export function TodayPage() {
|
||||
const { region } = useRegion()
|
||||
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
|
||||
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
|
||||
const f = feed.data
|
||||
const posts = f?.posts ?? []
|
||||
const stories = f?.stories ?? []
|
||||
const bands = f?.bands
|
||||
const nowAt = f?.hero?.now_at
|
||||
|
||||
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
||||
const bandAt: [number, ReactNode][] = [
|
||||
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
|
||||
[6, bands?.top5?.length ? <TopBand key="top5" items={bands.top5} sub={nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
|
||||
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
|
||||
]
|
||||
|
||||
return (
|
||||
<section aria-label="오늘">
|
||||
<Hero hero={f?.hero} today={today.data} />
|
||||
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
|
||||
{stories.length ? <Stories items={stories} /> : <StateBox loading={feed.isPending} error={feed.error} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." />}
|
||||
<StateBox loading={feed.isPending} error={feed.error} onRetry={() => feed.refetch()} empty={feed.isSuccess && !posts.length ? '오늘 올라온 글이 아직 없어요.' : undefined} />
|
||||
<div>
|
||||
{posts.map((p, i) => (
|
||||
<Fragment key={p.post_id}>
|
||||
<PostCard key={`${p.post_id}-${p.liked}-${p.saved}-${p.like_count}`} post={p} />
|
||||
{bandAt.find(([at]) => at === i + 1)?.[1]}
|
||||
</Fragment>
|
||||
))}
|
||||
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getWeekOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, dateRange, sidoOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Ic, Rail, Sec, StateBox } from './ui'
|
||||
|
||||
const PLACE_BG: Record<string, string> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', bulb: 'lilac' }
|
||||
|
||||
export function WeekPage() {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const week = useQuery(getWeekOptions({ query: { region: region.code } }))
|
||||
const days = week.data?.days ?? []
|
||||
const [picked, setPicked] = useState<string | null>(null)
|
||||
// 지역을 바꾸면 동네 고르기는 전체로 돌아간다
|
||||
const [areaPick, setAreaPick] = useState({ region: region.code, area: '전체' })
|
||||
const area = areaPick.region === region.code ? areaPick.area : '전체'
|
||||
// 처음에는 이번 토요일을 고른다
|
||||
const sel = days.find((d) => d.day === picked) ?? days.find((d) => d.weekday === '토') ?? days[0]
|
||||
const places = useQuery({ ...listPlacesOptions({ query: { region: region.code, day: sel?.day, area: area === '전체' ? undefined : area } }), enabled: !!sel })
|
||||
const events = useQuery(listEventsOptions({ query: { region: region.code } }))
|
||||
const sido = sidoOf(region.name)
|
||||
const areas = places.data?.areas ?? []
|
||||
const rainy = places.data?.rainy ?? sel?.is_rainy
|
||||
const placeList = places.data?.places ?? []
|
||||
const eventList = events.data?.events ?? []
|
||||
|
||||
const sendPlan = () => {
|
||||
if (!sel) return
|
||||
open({ type: 'share', share: { title: `${sel.weekday}요일 일정`, icon: 'calendar', bg: 'mint', messages: [`${sel.weekday}요일 이렇게 놀자! ${sel.pick} 😆`, '이번 주말 같이 놀자 🙌'] } })
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-label="주말·행사">
|
||||
<Sec title="이번 주 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
|
||||
{days.length ? (
|
||||
<div className="grid grid-cols-7 gap-1 px-3 pt-3" role="group" aria-label="날짜 고르기">
|
||||
{days.map((d) => {
|
||||
const on = d.day === sel?.day
|
||||
const weekend = d.weekday === '토' || d.weekday === '일' || !!d.holiday
|
||||
return (
|
||||
<button
|
||||
key={d.day}
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
onClick={() => setPicked(d.day)}
|
||||
className={cx('flex cursor-pointer flex-col items-center gap-0.5 rounded-[18px] pt-[9px] pb-2 text-xs font-extrabold', on ? 'bg-(--ink) text-white' : cx('bg-white shadow-[inset_0_-4px_0_var(--shade)]', weekend ? 'text-[#d6457a]' : 'text-(--ink2)'))}
|
||||
>
|
||||
<span>{d.weekday}</span>
|
||||
<Ic name={d.icon} className="w-7" />
|
||||
<b className={cx('font-jua text-sm font-normal', on ? 'text-white' : 'text-(--ink)')}>{d.temp_max_c != null ? `${Math.round(d.temp_max_c)}°` : '-'}</b>
|
||||
<span className={cx('max-w-full truncate px-0.5 text-[9.5px]', on ? 'text-[#ffb3c4]' : 'text-[#d6457a]')}>{d.holiday ? d.holiday.replace(/\(.*\)/, '') : `${Number(d.day.slice(8))}일`}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<StateBox loading={week.isPending} error={week.error} onRetry={() => week.refetch()} empty="이번 주 날씨가 아직 없어요." />
|
||||
)}
|
||||
{sel && (
|
||||
<div className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-[linear-gradient(180deg,#e9fbf2,#fff)] p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-live="polite">
|
||||
<Ic name={sel.icon} className="w-16" />
|
||||
<div>
|
||||
<b className="block font-jua text-[19px] font-normal">{sel.headline}</b>
|
||||
<p className="mt-0.5 text-[13.5px] font-semibold text-(--ink2)">{sel.summary}</p>
|
||||
<p className="mt-2 font-jua text-base text-(--ink)">추천: {sel.pick}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{areas.length > 0 && (
|
||||
<div className="mx-3 mt-3.5 flex items-center justify-between">
|
||||
<label htmlFor="b-area" className="text-[13.5px] font-bold text-(--ink2)">
|
||||
{sido} · 데이트 명소
|
||||
</label>
|
||||
<select id="b-area" value={area} onChange={(e) => setAreaPick({ region: region.code, area: e.target.value })} className="rounded-full bg-white px-3 py-[7px] font-bold text-(--ink) shadow-[inset_0_-3px_0_var(--shade)]">
|
||||
{['전체', ...areas].map((a) => (
|
||||
<option key={a}>{a}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
<Sec title="날씨 맞춤 데이트 명소" sub={sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : '맑아서 야외 명소를 먼저'} 보여 줘요` : undefined} className="pt-3" />
|
||||
{placeList.length ? (
|
||||
<Rail>
|
||||
{placeList.map((p, i) => (
|
||||
<div key={p.place_id} className="w-[178px] overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<span className={cx('relative grid h-[104px] place-items-center', `b-bg-${PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, i))}`)}>
|
||||
{p.is_good && <span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', p.is_outdoor ? 'bg-[#1f9d62]' : 'bg-(--rain)')}>{p.is_outdoor ? '오늘 딱' : '비 와도 OK'}</span>}
|
||||
<Ic name={p.icon} className="w-[62px]" />
|
||||
</span>
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<span className="text-[11.5px] font-extrabold text-(--ink3)">
|
||||
{p.area} · {p.is_outdoor ? '야외' : '실내'}
|
||||
</span>
|
||||
<b className="block font-jua text-[16.5px] font-normal">{p.name}</b>
|
||||
<small className="block text-[12.5px] leading-snug font-semibold text-(--ink2)">
|
||||
{p.reason}
|
||||
<br />
|
||||
추천 {p.best_time}
|
||||
</small>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</Rail>
|
||||
) : (
|
||||
<StateBox loading={places.isPending && !!sel} error={places.error} onRetry={() => places.refetch()} empty={`${sido} 데이트 명소는 아직 준비 중이에요.`} />
|
||||
)}
|
||||
<Sec title={`${sido} 축제·행사`} sub="앞으로 30일 · 그날 날씨까지 같이 봐요" className="pt-[18px]" />
|
||||
{eventList.length ? (
|
||||
eventList.map((e, i) => (
|
||||
<div key={e.event_id} className="mx-3 mt-2.5 grid grid-cols-[84px_1fr] items-center gap-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<span className={cx('grid h-[84px] place-items-center rounded-2xl', `b-bg-${cardBg(e.icon, i)}`)}>
|
||||
<Ic name={e.icon} className="w-14" />
|
||||
</span>
|
||||
<span>
|
||||
<span className={cx('mr-1.5 inline-block rounded-full px-[7px] py-0.5 align-[2px] text-[11px] font-extrabold', e.status === 'live' ? 'bg-[#dff5ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}>{e.status_label}</span>
|
||||
<b className="inline font-jua text-[17px] leading-snug font-normal">{e.name}</b>
|
||||
<small className="block text-[12.5px] font-semibold text-(--ink2)">
|
||||
{dateRange(e.start_date, e.end_date)} · {e.place_name}
|
||||
{!e.is_confirmed && ' · 일정 확인 필요'}
|
||||
</small>
|
||||
{e.fit && <span className={cx('mt-[5px] inline-block text-xs font-extrabold', e.fit.includes('비') ? 'text-[#d6457a]' : 'text-[#1f9d62]')}>{e.fit}</span>}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<StateBox loading={events.isPending} error={events.error} onRetry={() => events.refetch()} empty="이 지역 행사는 아직 없어요. 다른 지역을 골라 보세요." />
|
||||
)}
|
||||
<button type="button" onClick={sendPlan} disabled={!sel} className="mx-3 mt-4 block w-[calc(100%-24px)] cursor-pointer rounded-full bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
이번 주말 일정 보내기
|
||||
</button>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
|
||||
import { clearTokens, getAccessToken, subscribeAuth } from '../api/auth'
|
||||
import { meOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { AuthContext } from './authContext'
|
||||
|
||||
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const token = useSyncExternalStore(subscribe, getAccessToken)
|
||||
const queryClient = useQueryClient()
|
||||
const me = useQuery({ ...meOptions(), enabled: !!token })
|
||||
|
||||
// 로그인·로그아웃하면 좋아요·저장 여부가 달라지니 받아 둔 데이터를 다시 받는다
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'change' && queryClient.invalidateQueries()), [queryClient])
|
||||
|
||||
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, logout: clearTokens }), [token, me.data])
|
||||
return <AuthContext value={api}>{children}</AuthContext>
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { createContext, use } from 'react'
|
||||
import type { Me } from '../api/client/types.gen'
|
||||
|
||||
export type AuthApi = { loggedIn: boolean; me: Me | null; logout: () => void }
|
||||
|
||||
export const AuthContext = createContext<AuthApi | null>(null)
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = use(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth must be used inside AuthProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
/* 시안 B 피드: 말랑한 3D 토큰과 Tailwind로 쓰기 어려운 그라데이션·애니메이션 */
|
||||
.b-app {
|
||||
--ink: #28304a;
|
||||
--ink2: #5a6380;
|
||||
--ink3: #8a92aa;
|
||||
--line: #e6ecf4;
|
||||
--page: #f7fbff;
|
||||
--outer: #dfeaf6;
|
||||
--shade: #d9e5f4;
|
||||
--orange: #ff7a45;
|
||||
--orange-deep: #d4552a;
|
||||
--rain: #4f97e3;
|
||||
--heart: #ff3b5c;
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.b-app :focus-visible {
|
||||
outline: 3px solid var(--rain);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.b-noscroll {
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.b-noscroll::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* 하늘에서 떨어진 뒤 둥둥 */
|
||||
.b-fall {
|
||||
animation:
|
||||
b-drop 1.05s cubic-bezier(0.22, 0.9, 0.3, 1) var(--d, 0s) both,
|
||||
b-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
|
||||
}
|
||||
@keyframes b-drop {
|
||||
0% {
|
||||
transform: translateY(-60vh) rotate(-10deg);
|
||||
opacity: 0;
|
||||
}
|
||||
55% {
|
||||
opacity: 1;
|
||||
}
|
||||
72% {
|
||||
transform: translateY(0) rotate(2deg) scale(1.04, 0.96);
|
||||
}
|
||||
86% {
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
100% {
|
||||
transform: none;
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes b-float {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(calc(var(--amp, 9px) * -1)) rotate(var(--tilt, 1.2deg));
|
||||
}
|
||||
}
|
||||
|
||||
.b-heart-pop {
|
||||
animation: b-hpop 0.8s ease-out;
|
||||
}
|
||||
@keyframes b-hpop {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: scale(0.3);
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
transform: scale(1.1);
|
||||
}
|
||||
60% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.b-sheet {
|
||||
animation: b-up 0.26s cubic-bezier(0.2, 0.9, 0.3, 1);
|
||||
}
|
||||
@keyframes b-up {
|
||||
from {
|
||||
transform: translateY(40px);
|
||||
opacity: 0.4;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.b-fall,
|
||||
.b-heart-pop,
|
||||
.b-sheet {
|
||||
animation: none !important;
|
||||
}
|
||||
.b-heart-pop {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* 히어로 시간대 배경 */
|
||||
.b-hero {
|
||||
transition: background 0.6s;
|
||||
}
|
||||
.b-hero[data-t='morning'] {
|
||||
background: linear-gradient(180deg, #ffd9b8, #ffe9d4 40%, #dff0ff);
|
||||
}
|
||||
.b-hero[data-t='day'] {
|
||||
background: linear-gradient(180deg, #9fd3ff, #cfe9ff 55%, #f1f8ff);
|
||||
}
|
||||
.b-hero[data-t='sunset'] {
|
||||
background: linear-gradient(180deg, #8e7cf0, #f28aa0 48%, #ffc38a);
|
||||
color: #fff;
|
||||
}
|
||||
.b-hero[data-t='night'] {
|
||||
background: linear-gradient(180deg, #141b3d, #27306a 60%, #3d3f86);
|
||||
color: #fff;
|
||||
}
|
||||
.b-hero .b-stars {
|
||||
opacity: 0;
|
||||
transition: opacity 0.6s;
|
||||
}
|
||||
.b-hero[data-t='night'] .b-stars {
|
||||
opacity: 1;
|
||||
}
|
||||
.b-stat {
|
||||
background: rgb(255 255 255 / 0.72);
|
||||
color: var(--ink);
|
||||
box-shadow: inset 0 -5px 0 rgb(217 229 244 / 0.9);
|
||||
}
|
||||
.b-hero[data-t='night'] .b-stat,
|
||||
.b-hero[data-t='sunset'] .b-stat {
|
||||
background: rgb(255 255 255 / 0.18);
|
||||
color: #fff;
|
||||
box-shadow: inset 0 -5px 0 rgb(255 255 255 / 0.12);
|
||||
}
|
||||
.b-orb-label {
|
||||
text-shadow: 0 2px 0 rgb(255 255 255 / 0.7);
|
||||
}
|
||||
.b-hero[data-t='night'] .b-orb-label,
|
||||
.b-hero[data-t='sunset'] .b-orb-label {
|
||||
text-shadow: 0 2px 0 rgb(0 0 0 / 0.2);
|
||||
}
|
||||
|
||||
.b-sun {
|
||||
background: radial-gradient(circle at 34% 30%, #fff5cf, #ffc86e 30%, #ff8e4e 68%, #ee6436);
|
||||
box-shadow:
|
||||
inset -18px -24px 40px rgb(170 50 20 / 0.34),
|
||||
inset 16px 18px 28px rgb(255 255 255 / 0.55),
|
||||
0 30px 56px rgb(240 106 58 / 0.32);
|
||||
color: #fff;
|
||||
}
|
||||
.b-hero[data-t='night'] .b-sun {
|
||||
background: radial-gradient(circle at 34% 30%, #fff, #e7e3ff 35%, #b9b0f2 72%, #8f86d9);
|
||||
color: #2b2a5c;
|
||||
box-shadow:
|
||||
inset -18px -24px 40px rgb(60 50 140 / 0.3),
|
||||
inset 16px 18px 28px rgb(255 255 255 / 0.6),
|
||||
0 0 60px rgb(190 180 255 / 0.45);
|
||||
}
|
||||
|
||||
.b-cloud {
|
||||
position: absolute;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
box-shadow:
|
||||
inset 0 -12px 18px rgb(160 190 230 / 0.45),
|
||||
0 16px 28px rgb(40 70 120 / 0.13);
|
||||
}
|
||||
.b-cloud::before,
|
||||
.b-cloud::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
box-shadow: inset 0 -10px 16px rgb(160 190 230 / 0.35);
|
||||
}
|
||||
.b-cloud::before {
|
||||
left: 16%;
|
||||
top: -58%;
|
||||
width: 46%;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
.b-cloud::after {
|
||||
left: 50%;
|
||||
top: -36%;
|
||||
width: 36%;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
.b-hero[data-t='night'] .b-cloud,
|
||||
.b-hero[data-t='night'] .b-cloud::before,
|
||||
.b-hero[data-t='night'] .b-cloud::after {
|
||||
background: #c9cdf0;
|
||||
}
|
||||
|
||||
/* 이야기 고리 */
|
||||
.b-ring {
|
||||
background: conic-gradient(var(--orange), #ffc86e, #8fcaff, var(--orange));
|
||||
}
|
||||
|
||||
/* 슬라이드·카드 배경 */
|
||||
.b-bg-sky {
|
||||
background: linear-gradient(180deg, #bfe3ff, #eef7ff);
|
||||
}
|
||||
.b-bg-butter {
|
||||
background: linear-gradient(180deg, #ffe7a0, #fff6d8);
|
||||
}
|
||||
.b-bg-peach {
|
||||
background: linear-gradient(180deg, #ffd2bb, #fff2ea);
|
||||
}
|
||||
.b-bg-mint {
|
||||
background: linear-gradient(180deg, #bfecd6, #effaf4);
|
||||
}
|
||||
.b-bg-lilac {
|
||||
background: linear-gradient(180deg, #d8cffc, #f4f1ff);
|
||||
}
|
||||
.b-bg-dusk {
|
||||
background: linear-gradient(180deg, #7e6fe6, #f08aa2 60%, #ffc28a);
|
||||
color: #fff;
|
||||
}
|
||||
.b-bg-night {
|
||||
background: linear-gradient(180deg, #1f2658, #3d3f86);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* 건물 실루엣 */
|
||||
.b-skyline::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: auto 0 0 0;
|
||||
height: var(--sky-h, 32%);
|
||||
background: #2d2440;
|
||||
clip-path: polygon(0 55%, 8% 55%, 8% 30%, 15% 30%, 15% 50%, 22% 50%, 22% 10%, 28% 10%, 28% 45%, 36% 45%, 36% 25%, 44% 25%, 44% 55%, 52% 55%, 52% 35%, 60% 35%, 60% 5%, 66% 5%, 66% 40%, 74% 40%, 74% 20%, 82% 20%, 82% 50%, 90% 50%, 90% 30%, 100% 30%, 100% 100%, 0 100%);
|
||||
}
|
||||
.b-cut-1 {
|
||||
background: linear-gradient(#9fd0ff, #ffd79a 60%, #ff9a5c);
|
||||
}
|
||||
.b-cut-2 {
|
||||
background: linear-gradient(#8f7cf0, #ff6f8e 55%, #ff8a4c);
|
||||
}
|
||||
.b-cut-3 {
|
||||
background: linear-gradient(#34306e, #7a5cc8);
|
||||
}
|
||||
|
||||
/* 각 줄 사이 가로 띠 */
|
||||
.b-band-1 {
|
||||
background: linear-gradient(180deg, #fff4ec, #f7fbff);
|
||||
}
|
||||
.b-band-2 {
|
||||
background: linear-gradient(180deg, #fff6d8, #f7fbff);
|
||||
}
|
||||
.b-band-3 {
|
||||
background: linear-gradient(180deg, #e9fbf2, #f7fbff);
|
||||
}
|
||||
|
||||
.b-sheet-dialog::backdrop {
|
||||
background: rgb(20 26 45 / 0.45);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons) */
|
||||
export function iconSrc(name: string) {
|
||||
if (OWN.has(name)) return `/b/icons/${name}.png`
|
||||
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
|
||||
}
|
||||
|
||||
export const MEDALS = ['gold', 'silver', 'bronze'] as const
|
||||
|
||||
export const fall = (d: string, f = '4.8s', amp?: string) => ({ '--d': d, '--f': f, ...(amp ? { '--amp': amp } : {}) }) as CSSProperties
|
||||
|
||||
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
|
||||
|
||||
const KST = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Seoul', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23', weekday: 'short' })
|
||||
const WD_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||
|
||||
/** 한국 시각으로 쪼개기 (브라우저 시간대와 상관없이) */
|
||||
export function kst(input: string | Date) {
|
||||
const parts = Object.fromEntries(KST.formatToParts(typeof input === 'string' ? new Date(input) : input).map((p) => [p.type, p.value]))
|
||||
return { y: +parts.year, mo: +parts.month, d: +parts.day, h: +parts.hour, mi: +parts.minute, wd: WD_EN.indexOf(parts.weekday) }
|
||||
}
|
||||
|
||||
const h12 = (h: number) => h % 12 || 12
|
||||
|
||||
/** 18:25 → "6:25" */
|
||||
export function clockShort(iso: string) {
|
||||
const t = kst(iso)
|
||||
return `${h12(t.h)}:${String(t.mi).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
|
||||
export function timeWords(iso: string) {
|
||||
const t = kst(iso)
|
||||
return `${h12(t.h)}시${t.mi === 0 ? '' : t.mi === 30 ? ' 반' : ` ${t.mi}분`}`
|
||||
}
|
||||
|
||||
/** 발표 시각 → "방금" · "12분 전" · "3시간 전" */
|
||||
export function ago(iso: string | null | undefined, now = Date.now()) {
|
||||
if (!iso) return '오늘'
|
||||
const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
|
||||
if (min < 5) return '방금'
|
||||
if (min < 60) return `${min}분 전`
|
||||
return `${Math.floor(min / 60)}시간 전`
|
||||
}
|
||||
|
||||
/** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */
|
||||
export function dayLabel(date: string, index: number) {
|
||||
if (index === 0) return '오늘'
|
||||
if (index === 1) return '내일'
|
||||
const [, m, d] = date.split('-').map(Number)
|
||||
const wd = new Date(`${date}T12:00:00+09:00`).getUTCDay()
|
||||
return `${WEEKDAYS[wd]} ${m}.${d}`
|
||||
}
|
||||
|
||||
export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
|
||||
|
||||
export function kindOfHour(h: number): TimeKind {
|
||||
if (h >= 5 && h < 9) return 'morning'
|
||||
if (h >= 9 && h < 16) return 'day'
|
||||
if (h >= 16 && h < 19) return 'sunset'
|
||||
return 'night'
|
||||
}
|
||||
|
||||
/** "서울 마포구" → "서울" */
|
||||
export const sidoOf = (regionName: string) => regionName.split(' ')[0]
|
||||
|
||||
/** 2026-10-02 ~ 2026-10-11 → "10.2 ~ 10.11", 하루짜리는 "10.3" */
|
||||
export function dateRange(start: string, end: string) {
|
||||
return start === end ? shortDay(start) : `${shortDay(start)} ~ ${shortDay(end)}`
|
||||
}
|
||||
|
||||
const CARD_BG = ['night', 'butter', 'lilac', 'mint', 'peach', 'sky'] as const
|
||||
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
|
||||
|
||||
/** API에 배경색이 없어 아이콘·순서로 카드 배경을 고른다 */
|
||||
export function cardBg(icon: string, index: number) {
|
||||
return ICON_BG[icon] && icon !== 'calendar' ? ICON_BG[icon] : CARD_BG[index % CARD_BG.length]
|
||||
}
|
||||
|
||||
/** "2026-09-23" → "9.23" */
|
||||
export const shortDay = (day: string) => day.split('-').slice(1).map(Number).join('.')
|
||||
|
||||
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: ['계절 소식', 'text-[#1f9d62]'], 2: ['날씨 상식', 'text-[#7a5cd6]'], 3: ['각 원리', 'text-(--orange)'] }
|
||||
|
||||
/** 읽을거리 한 줄 정보: "계절 소식 · 3분" */
|
||||
export const articleMeta = (a: { category: number; read_minutes: number }) => `${ARTICLE_CAT[a.category]?.[0] ?? '읽을거리'} · ${a.read_minutes}분`
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { nearestRegion } from '../api/client/sdk.gen'
|
||||
import type { RegionData } from '../api/client/types.gen'
|
||||
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
|
||||
function readStored(): RegionData | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY)
|
||||
return raw ? (JSON.parse(raw) as RegionData) : null
|
||||
} catch {
|
||||
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 기본 구로 시작
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeStored(r: RegionData) {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(r))
|
||||
} catch {
|
||||
// 저장이 막혀도 이번 방문 동안은 메모리 값으로 계속 쓴다
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
const [stored] = useState(readStored)
|
||||
const [region, setRegionState] = useState<RegionData>(stored ?? DEFAULT_REGION)
|
||||
const canLocate = typeof navigator !== 'undefined' && 'geolocation' in navigator
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!stored && canLocate ? 'locating' : 'idle')
|
||||
|
||||
const setRegion = useCallback((r: RegionData) => {
|
||||
setRegionState(r)
|
||||
writeStored(r)
|
||||
}, [])
|
||||
|
||||
const findNearest = useCallback(() => {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
||||
.then(({ data: res }) => {
|
||||
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||
setRegion(res.region)
|
||||
setLocateStatus('idle')
|
||||
})
|
||||
.catch(() => setLocateStatus('error'))
|
||||
},
|
||||
(err) => setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
{ timeout: 10000, maximumAge: 600000 },
|
||||
)
|
||||
}, [setRegion])
|
||||
|
||||
const locate = useCallback(() => {
|
||||
if (!canLocate) {
|
||||
setLocateStatus('error')
|
||||
return
|
||||
}
|
||||
setLocateStatus('locating')
|
||||
findNearest()
|
||||
}, [canLocate, findNearest])
|
||||
|
||||
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
||||
useEffect(() => {
|
||||
if (!stored && canLocate) findNearest()
|
||||
}, [stored, canLocate, findNearest])
|
||||
|
||||
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
||||
return <RegionContext value={api}>{children}</RegionContext>
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { createContext, use } from 'react'
|
||||
import type { RegionData } from '../api/client/types.gen'
|
||||
|
||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
||||
|
||||
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: () => void; locateStatus: LocateStatus }
|
||||
|
||||
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
|
||||
|
||||
export const RegionContext = createContext<RegionApi | null>(null)
|
||||
|
||||
export function useRegion() {
|
||||
const ctx = use(RegionContext)
|
||||
if (!ctx) throw new Error('useRegion must be used inside RegionProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createContext, use } from 'react'
|
||||
import type { SlideBg } from './types'
|
||||
|
||||
export type SharePayload = { title: string; icon: string; bg: SlideBg; messages: string[] }
|
||||
|
||||
export type SheetState =
|
||||
| { type: 'gak'; indexId: number }
|
||||
| { type: 'article'; articleId: number }
|
||||
| { type: 'share'; share: SharePayload }
|
||||
| { type: 'comments'; postId: number }
|
||||
| { type: 'seasonWeek' }
|
||||
| { type: 'login' }
|
||||
| { type: 'region' }
|
||||
| null
|
||||
|
||||
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
|
||||
|
||||
export const SheetContext = createContext<SheetApi | null>(null)
|
||||
|
||||
export function useSheet() {
|
||||
const ctx = use(SheetContext)
|
||||
if (!ctx) throw new Error('useSheet must be used inside SheetProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
type P = { className?: string }
|
||||
|
||||
const line = { fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', strokeLinejoin: 'round' } as const
|
||||
|
||||
export function HeartIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
|
||||
<path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function CommentIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
|
||||
<path d="M20.5 12a8.5 8.5 0 0 1-12.6 7.4L3.5 20.5l1.2-4.2A8.5 8.5 0 1 1 20.5 12z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function SendIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
|
||||
<path d="M21 3 10 14M21 3l-6.5 18-4-7.5L3 9.5z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function SaveIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
|
||||
<path d="M19 21l-7-5-7 5V4.5A1.5 1.5 0 0 1 6.5 3h11A1.5 1.5 0 0 1 19 4.5z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function MoreIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor" className={className} aria-hidden="true">
|
||||
<circle cx="5" cy="12" r="1.8" />
|
||||
<circle cx="12" cy="12" r="1.8" />
|
||||
<circle cx="19" cy="12" r="1.8" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function PinIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" {...line} strokeWidth="2.2" className={className} aria-hidden="true">
|
||||
<path d="M12 21s7-6.2 7-11.5A7 7 0 0 0 5 9.5C5 14.8 12 21 12 21z" />
|
||||
<circle cx="12" cy="9.5" r="2.5" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" {...line} className={className} aria-hidden="true">
|
||||
{name === 'today' && <path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />}
|
||||
{name === 'gak' && (
|
||||
<>
|
||||
<rect x="3.5" y="3.5" width="7" height="7" rx="2" />
|
||||
<rect x="13.5" y="3.5" width="7" height="7" rx="2" />
|
||||
<rect x="3.5" y="13.5" width="7" height="7" rx="2" />
|
||||
<rect x="13.5" y="13.5" width="7" height="7" rx="2" />
|
||||
</>
|
||||
)}
|
||||
{name === 'sky' && <path d="M3 18h18M6 14a6 6 0 0 1 12 0M12 4v3M4.9 7.9l2 2M19.1 7.9l-2 2M8 21h8" />}
|
||||
{name === 'week' && (
|
||||
<>
|
||||
<rect x="3.5" y="5" width="17" height="15.5" rx="2.5" />
|
||||
<path d="M3.5 10h17M8 3v4M16 3v4" />
|
||||
<circle cx="12" cy="15" r="1.6" />
|
||||
</>
|
||||
)}
|
||||
{name === 'season' && <path d="M12 6.5C10 5 7 4.5 3.5 5v14c3.5-.5 6.5 0 8.5 1.5 2-1.5 5-2 8.5-1.5V5C17 4.5 14 5 12 6.5zM12 6.5v14" />}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export type SlideBg = 'sky' | 'butter' | 'peach' | 'mint' | 'lilac' | 'dusk' | 'night'
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { CSSProperties, ReactNode } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import { iconSrc } from './lib'
|
||||
|
||||
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
|
||||
|
||||
export function Ic({ name, className, alt = '', style }: IcProps) {
|
||||
return <img src={iconSrc(name)} alt={alt} className={cx('block', className)} style={style} decoding="async" />
|
||||
}
|
||||
|
||||
type SecProps = { title: string; sub?: ReactNode; more?: { to: string; label?: string }; className?: string }
|
||||
|
||||
export function Sec({ title, sub, more, className }: SecProps) {
|
||||
return (
|
||||
<div className={cx('flex items-end justify-between px-4 pt-[22px] pb-1.5', className)}>
|
||||
<div>
|
||||
<h2 className="m-0 font-jua text-[21px] font-normal">{title}</h2>
|
||||
{sub && <p className="mt-0.5 text-[13px] font-semibold text-(--ink2)">{sub}</p>}
|
||||
</div>
|
||||
{more && (
|
||||
<Link to={more.to} className="text-[13px] font-bold text-(--ink2)">
|
||||
{more.label ?? '전체 보기'}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Rail({ children, className, label }: { children: ReactNode; className?: string; label?: string }) {
|
||||
return (
|
||||
<div className={cx('b-noscroll flex snap-x snap-proximity gap-2.5 overflow-x-auto px-4 pt-3 pb-1 *:shrink-0 *:snap-start', className)} role={label ? 'group' : undefined} aria-label={label}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type ChipsProps<K extends string> = { items: readonly (readonly [K, string])[]; value: K; onChange: (k: K) => void; label: string }
|
||||
|
||||
export function Chips<K extends string>({ items, value, onChange, label }: ChipsProps<K>) {
|
||||
return (
|
||||
<div className="b-noscroll flex gap-2 overflow-x-auto px-4 pt-3 pb-0.5" role="group" aria-label={label}>
|
||||
{items.map(([k, l]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
aria-pressed={value === k}
|
||||
onClick={() => onChange(k)}
|
||||
className={cx('shrink-0 cursor-pointer rounded-full px-3.5 py-[7px] text-[13.5px] font-bold', value === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2) shadow-[inset_0_-3px_0_var(--shade)]')}
|
||||
>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type StateProps = { loading?: boolean; error?: unknown; onRetry?: () => void; empty?: string; className?: string }
|
||||
|
||||
/** 불러오는 중·실패·빈 목록 안내 */
|
||||
export function StateBox({ loading, error, onRetry, empty, className }: StateProps) {
|
||||
const text = loading ? '불러오는 중이에요…' : error ? '정보를 불러오지 못했어요.' : empty
|
||||
if (!text) return null
|
||||
return (
|
||||
<div className={cx('mx-3 mt-3 flex flex-col items-center gap-2 rounded-[22px] bg-white px-4 py-6 text-center text-[13.5px] font-semibold text-(--ink2) shadow-[inset_0_-5px_0_var(--shade)]', className)} role={error ? 'alert' : 'status'}>
|
||||
<span>{text}</span>
|
||||
{error != null && onRetry && (
|
||||
<button type="button" onClick={onRetry} className="cursor-pointer rounded-full bg-(--ink) px-4 py-1.5 text-[13px] font-bold text-white">
|
||||
다시 시도
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 줄 목록 (라벨 · 값) */
|
||||
export function Rows({ rows, dark = false }: { rows: { label: string; value: string }[]; dark?: boolean }) {
|
||||
return (
|
||||
<div className="mt-auto flex flex-col">
|
||||
{rows.map((r) => (
|
||||
<div key={r.label} className={cx('flex justify-between gap-2.5 border-b-2 py-2.5 font-bold last:border-b-0', dark ? 'border-white/18' : 'border-[rgb(40_48_74/0.08)]')}>
|
||||
<span>{r.label}</span>
|
||||
<b className="text-right font-jua text-[17px] font-normal">{r.value}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { RainType, Sky, type WeatherSlot } from '../api/client/types.gen'
|
||||
import { kst } from './lib'
|
||||
|
||||
const RAIN_TEXT: Partial<Record<RainType, string>> = { [RainType.RAIN]: '비', [RainType.SLEET]: '진눈깨비', [RainType.SNOW]: '눈', [RainType.SHOWER]: '소나기' }
|
||||
const SKY_TEXT: Record<Sky, string> = { [Sky.CLEAR]: '맑음', [Sky.PARTLY]: '구름 많음', [Sky.CLOUDY]: '흐림' }
|
||||
|
||||
/** 칸 하나의 하늘 상태 한 마디: 비·눈이 오면 그걸, 아니면 하늘 */
|
||||
export function skyText(slot: WeatherSlot) {
|
||||
return (slot.rain_type != null && RAIN_TEXT[slot.rain_type]) || (slot.sky != null ? SKY_TEXT[slot.sky] : slot.note)
|
||||
}
|
||||
|
||||
/** 주어진 시(0~23)를 넘지 않는 마지막 칸 */
|
||||
export function slotAt(slots: WeatherSlot[], hour: number) {
|
||||
let pick: WeatherSlot | undefined
|
||||
for (const s of slots) if (kst(s.at).h <= hour) pick = s
|
||||
return pick ?? slots[0]
|
||||
}
|
||||
|
||||
export const deg = (v: number | null | undefined) => (v == null ? '-' : `${Math.round(v)}°`)
|
||||
Reference in new issue
Block a user