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:
minaChoiandClaude Opus 5.5 committed 2026-10-02 11:32:22 +09:00
1 parent e134295ce5
commit f8b47f064a
147 files changed
+12350

No files matched your search

+612
View File
@@ -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>
)
}