- 화면 전체 스켈레톤, 로딩·완료·실패 사이 레이아웃 고정, 값 없음은 '?' - 행사 사진·출처 표시, 문화정보 API 전시 연결, 행사 30km 거리 기준 - 각 상세 점수 칸 오늘/내일/토/일, 단기예보 밖 주말은 중기예보 예상 점수 - 6각 차트 축 이름을 좋은 방향으로, 계산 근거 문구 정리 - 아이콘 오용·뜻 모를 표시·빈 데이터·포스트 본문 반복 수정 - 미세먼지 별도 포스트, 노을 명소 전국 155곳 거리 기준, 노을 탭 결론 중심 재구성 - 밤 다크 테마·별똥별, 댓글·좋아요 대기·실패 표시 - 주말 전국 랭킹·당일치기 카드, 계절 이야기 사진 수집 - 문서: 포스트 타입별 내용, 각 데이터 정리, TODO 진행 순서
985 lines
43 KiB
TypeScript
985 lines
43 KiB
TypeScript
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } 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,
|
||
listCommentsInfiniteOptions,
|
||
listCommentsInfiniteQueryKey,
|
||
listRegionsOptions,
|
||
loginMutation,
|
||
meQueryKey,
|
||
signupMutation,
|
||
unlikeCommentMutation,
|
||
updateMeMutation,
|
||
} from '../api/client/@tanstack/react-query.gen'
|
||
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
|
||
import { cx } from '../lib/utils'
|
||
import { useAuth } from './authContext'
|
||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||
import { useRegion } from './regionContext'
|
||
import { useSky } from './skyContext'
|
||
import { storyImage } from './storyImage'
|
||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||
import { HeartIcon } from './svg'
|
||
import { Avatar, Ic, Skel, 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: '로그인', me: '내 정보', 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 isOpen = state != null
|
||
useEffect(() => {
|
||
if (!isOpen) return
|
||
const root = document.documentElement
|
||
const before = root.style.overflow
|
||
root.style.overflow = 'hidden'
|
||
return () => {
|
||
root.style.overflow = before
|
||
}
|
||
}, [isOpen])
|
||
|
||
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 === 'me' && <MeSheet 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 overscroll-contain px-4 pt-3.5 pb-[18px]', className)}>{children}</div>
|
||
}
|
||
|
||
/** 문구를 모두 같은 칸에 겹쳐 두고 하나만 보인다: 대기 문구로 바뀌어도 버튼 크기가 그대로다 */
|
||
function Swap({ labels, at }: { labels: readonly ReactNode[]; at: number }) {
|
||
return (
|
||
<span className="inline-grid [&>*]:col-start-1 [&>*]:row-start-1">
|
||
{labels.map((l, i) => (
|
||
<span key={i} className={cx(i !== at && 'invisible')}>
|
||
{l}
|
||
</span>
|
||
))}
|
||
</span>
|
||
)
|
||
}
|
||
|
||
/* ---------- 시트 스켈레톤: 완료 화면과 같은 틀·같은 줄 높이 ---------- */
|
||
const N3 = [0, 1, 2]
|
||
const N4 = [0, 1, 2, 3]
|
||
const N6 = [0, 1, 2, 3, 4, 5]
|
||
const N14 = Array.from({ length: 14 }, (_, i) => i)
|
||
|
||
function GakSkel() {
|
||
return (
|
||
<div aria-hidden="true">
|
||
<div className="flex items-center gap-3">
|
||
<Skel shape className="size-[58px] shrink-0 rounded-full" />
|
||
<div className="flex-1">
|
||
<h4 className="m-0 font-jua text-[22px] font-normal">
|
||
<Skel className="w-28" />
|
||
</h4>
|
||
<p className="mt-0.5 text-[13.5px] font-semibold">
|
||
<Skel className="w-4/5" />
|
||
</p>
|
||
</div>
|
||
<b className="ml-auto font-bagel text-[42px] font-normal">
|
||
<Skel className="w-14" />
|
||
</b>
|
||
</div>
|
||
<Skel shape className="mx-auto mt-2 aspect-square w-full max-w-[250px] rounded-full" />
|
||
<div className="mt-2.5 grid grid-cols-4 gap-1.5">
|
||
{N4.map((i) => (
|
||
<div key={i} className="rounded-2xl bg-[#f3f6fb] px-1 py-2.5 text-center">
|
||
<small className="block text-xs font-extrabold">
|
||
<Skel className="w-8" />
|
||
</small>
|
||
<b className="block font-bagel text-2xl font-normal">
|
||
<Skel className="w-9" />
|
||
</b>
|
||
<small className="block text-[11px] leading-4 font-extrabold">
|
||
<Skel className="w-6" />
|
||
</small>
|
||
</div>
|
||
))}
|
||
</div>
|
||
<div className="mt-3.5 flex flex-col gap-2.5">
|
||
{N6.map((i) => (
|
||
<div key={i} className="grid grid-cols-[84px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
||
<span>
|
||
<Skel className="w-12" />
|
||
</span>
|
||
<Skel shape className="h-[9px] rounded-full" />
|
||
<em className="text-right text-xs not-italic">
|
||
<Skel className="w-10" />
|
||
</em>
|
||
<p className="col-start-2 col-end-4 -mt-0.5 text-[12.5px] font-semibold">
|
||
<Skel className="w-3/4" />
|
||
</p>
|
||
</div>
|
||
))}
|
||
</div>
|
||
<div className="mt-3.5 flex flex-col gap-1.5 text-[13px] font-semibold">
|
||
<span>
|
||
<Skel className="w-full" />
|
||
<br />
|
||
<Skel className="w-1/2" />
|
||
</span>
|
||
<span>
|
||
<Skel className="w-4/5" />
|
||
</span>
|
||
</div>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/** 읽을거리·이번 주 특집: 그림 150px · 머리말 · 제목 · 본문 */
|
||
function ArticleSkel() {
|
||
return (
|
||
<div aria-hidden="true">
|
||
<Skel shape className="mb-3.5 h-[150px] rounded-[20px]" />
|
||
<p className="text-[13px] font-extrabold">
|
||
<Skel className="w-24" />
|
||
</p>
|
||
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">
|
||
<Skel className="w-4/5" />
|
||
</h4>
|
||
{N3.map((k) => (
|
||
<p key={k} className="mb-2.5 text-[15px] leading-[1.7]">
|
||
<Skel className="w-full" />
|
||
<br />
|
||
<Skel className="w-2/3" />
|
||
</p>
|
||
))}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
function CommentsSkel() {
|
||
return (
|
||
<div aria-hidden="true">
|
||
{N3.map((i) => (
|
||
<div key={i} className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 py-2">
|
||
<Skel shape className="size-[34px] rounded-full" />
|
||
<div>
|
||
<p className="m-0 text-sm">
|
||
<Skel className="w-3/4" />
|
||
</p>
|
||
<small className="mt-0.5 block text-xs font-bold">
|
||
<Skel className="w-24" />
|
||
</small>
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
function RegionsSkel() {
|
||
return (
|
||
<ul className="mt-2 flex flex-col" aria-hidden="true">
|
||
{N14.map((i) => (
|
||
<li key={i} className="border-b-[1.5px] border-(--line) px-1 py-3 font-jua text-[17px]">
|
||
<Skel className="w-28" />
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)
|
||
}
|
||
|
||
/* ---------- 각 계산 근거 ---------- */
|
||
const labelLines = (label: string) => {
|
||
const cut = label.indexOf(' ')
|
||
return cut < 0 ? [label] : [label.slice(0, cut), label.slice(cut + 1)]
|
||
}
|
||
|
||
function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[]; size?: number }) {
|
||
const c = size / 2
|
||
const r = size / 2 - 40
|
||
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.24)[0]} y={pt(i, 1.24)[1]} textAnchor="middle" dominantBaseline="middle" fontFamily="Jua,sans-serif" fontSize="13" fill="#28304a">
|
||
{labelLines(f.label).map((line, k, all) => (
|
||
<tspan key={k} x={pt(i, 1.24)[0]} dy={k === 0 ? `${-(all.length - 1) * 0.55}em` : '1.1em'}>
|
||
{line}
|
||
</tspan>
|
||
))}
|
||
</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])
|
||
|
||
const load = loadOf(q)
|
||
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} className="inset-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-4 gap-1.5">
|
||
{g.trend.map((t) => (
|
||
<div key={t.day} className="rounded-2xl bg-[#f3f6fb] px-1 py-2.5 text-center">
|
||
<small className="block text-xs font-extrabold whitespace-nowrap text-(--ink2)">{t.label}</small>
|
||
<b className="block font-bagel text-2xl font-normal text-(--orange)">{t.score}</b>
|
||
<small className={cx('block text-[11px] leading-4 font-extrabold text-(--ink2)', !t.estimated && 'invisible')}>예상</small>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
<div className="mt-3.5 flex flex-col gap-2.5">
|
||
{factors.map((f) => (
|
||
<div key={f.axis} className="grid grid-cols-[84px_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)">오늘 걸린 조건:</b> {d.zero_reason}
|
||
</span>
|
||
)}
|
||
{factors.length > 0 && (
|
||
<span>
|
||
<b className="text-(--ink)">계산 방법:</b> 요소 점수에 비중을 곱해 더하고, 가장 낮은 요소가 낮을수록 최대 25%까지 더 깎아요
|
||
</span>
|
||
)}
|
||
{d.zero_rules && (
|
||
<span>
|
||
<b className="text-(--ink)">점수 깎이는 조건:</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])
|
||
|
||
const load = loadOf(q)
|
||
if (!a) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." hold={<ArticleSkel />} className="inset-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
|
||
const load = loadOf(q)
|
||
if (!w?.headline) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이번 주 특집이 아직 없어요." hold={<ArticleSkel />} className="inset-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.start && w.end ? dateRange(w.start, w.end) : '이번 주'}</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.trim() ? `${msg} — ${share.title} · 날씨각` : `${share.title} · 날씨각`
|
||
const { kind } = useSky()
|
||
const [image, setImage] = useState<{ blob: Blob; src: string } | null>(null)
|
||
const [imageError, setImageError] = useState(false)
|
||
|
||
// 창이 열리면 카드를 스토리 크기 이미지로 미리 만들어 둔다
|
||
useEffect(() => {
|
||
if (!share.card) return
|
||
let src = ''
|
||
let alive = true
|
||
storyImage(share.card, { title: share.title, sub: `${region.name} · 날씨각`, sky: kind }).then(
|
||
(blob) => {
|
||
if (!alive) return
|
||
src = URL.createObjectURL(blob)
|
||
setImage({ blob, src })
|
||
},
|
||
(e: unknown) => {
|
||
console.error('[share] story image', e)
|
||
if (alive) setImageError(true)
|
||
},
|
||
)
|
||
return () => {
|
||
alive = false
|
||
if (src) URL.revokeObjectURL(src)
|
||
}
|
||
}, [share.card, share.title, region.name, kind])
|
||
|
||
// 휴대폰은 공유창에 이미지 파일을 넘기고(인스타 스토리·카톡 등), 안 되면 이미지를 내려받는다
|
||
const shareImage = () => {
|
||
if (!image) return
|
||
const file = new File([image.blob], 'nalssigak.png', { type: 'image/png' })
|
||
if (navigator.canShare?.({ files: [file] })) {
|
||
navigator.share({ files: [file], title: share.title, text }).then(
|
||
() => setToast('보냈어요'),
|
||
(e: unknown) => {
|
||
if (e instanceof DOMException && e.name === 'AbortError') return
|
||
setToast('공유하지 못했어요. 이미지를 내려받아 올려 주세요')
|
||
},
|
||
)
|
||
return
|
||
}
|
||
const a = document.createElement('a')
|
||
a.href = image.src
|
||
a.download = 'nalssigak.png'
|
||
a.click()
|
||
setToast('이미지를 내려받았어요. 인스타 스토리에 올려 보세요')
|
||
}
|
||
|
||
// 휴대폰 기본 공유창. 없거나 실패하면 링크 복사로 대신한다.
|
||
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"
|
||
/>
|
||
)}
|
||
{share.card && (
|
||
<div className="mt-3.5 flex items-center gap-3 rounded-[18px] bg-[#f3f6fb] p-2.5">
|
||
{image ? <img src={image.src} alt="공유할 이미지 미리보기" className="h-28 rounded-[10px] shadow-[0_4px_10px_rgb(40_48_74/0.15)]" /> : <span className="grid h-28 w-16 place-items-center rounded-[10px] bg-white text-xs font-bold text-(--ink3)">{imageError ? '실패' : '만드는 중'}</span>}
|
||
<div className="flex flex-1 flex-col gap-1.5">
|
||
<b className="text-sm font-extrabold">이미지로 보내기</b>
|
||
<small className="text-xs font-semibold text-(--ink2)">인스타 스토리 크기(9:16)로 만들어요</small>
|
||
<button type="button" onClick={shareImage} disabled={!image} className="cursor-pointer rounded-[14px] bg-(--orange) py-2.5 font-jua text-[15px] text-white shadow-[inset_0_-4px_0_var(--orange-deep)] disabled:opacity-50">
|
||
이미지 공유하기
|
||
</button>
|
||
</div>
|
||
</div>
|
||
)}
|
||
<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 EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
|
||
|
||
function CommentRow({ c, postId }: { c: CommentData; 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 [removeFailed, setRemoveFailed] = useState(false)
|
||
|
||
const toggle = () => {
|
||
if (!loggedIn) return open({ type: 'login' })
|
||
if (like.isPending || unlike.isPending) return
|
||
const next = !liked
|
||
setLiked(next)
|
||
setCount((n) => n + (next ? 1 : -1))
|
||
;(next ? like : unlike).mutate(
|
||
{ path: { comment_id: c.comment_id } },
|
||
{
|
||
onSuccess: (res) => {
|
||
if (!res.result?.success) {
|
||
setLiked(!next)
|
||
setCount(c.like_count)
|
||
return
|
||
}
|
||
setLiked(!!res.liked)
|
||
if (res.like_count != null) setCount(res.like_count)
|
||
},
|
||
onError: () => {
|
||
setLiked(!next)
|
||
setCount(c.like_count)
|
||
},
|
||
},
|
||
)
|
||
}
|
||
|
||
// 지우는 동안은 흐리게 두고, 성공하면 다시 받기 전에 목록 캐시에서 바로 뺀다
|
||
const del = () => {
|
||
setRemoveFailed(false)
|
||
remove.mutate(
|
||
{ path: { comment_id: c.comment_id } },
|
||
{
|
||
onSuccess: async (res) => {
|
||
if (!res.result?.success) return setRemoveFailed(true)
|
||
const key = listCommentsInfiniteQueryKey({ path: { post_id: postId } })
|
||
await queryClient.cancelQueries({ queryKey: key })
|
||
queryClient.setQueryData<InfiniteData<ResCommentList>>(key, (data) =>
|
||
data ? { ...data, pages: data.pages.map((p) => ({ ...p, comments: p.comments?.filter((x) => x.comment_id !== c.comment_id) })) } : data,
|
||
)
|
||
queryClient.invalidateQueries({ queryKey: key })
|
||
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||
},
|
||
onError: () => setRemoveFailed(true),
|
||
},
|
||
)
|
||
}
|
||
|
||
return (
|
||
<div className={cx('grid grid-cols-[34px_1fr_24px] items-start gap-2.5 py-2 transition-opacity', remove.isPending && 'opacity-50')} aria-busy={remove.isPending}>
|
||
<Avatar character={c.character} color={c.color} mood={c.mood} />
|
||
<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={cx('cursor-pointer text-left font-bold underline-offset-2 hover:underline', removeFailed && !remove.isPending ? 'text-(--heart)' : 'text-(--ink3)')}>
|
||
<Swap labels={['지우기', '지우는 중…', '못 지웠어요 · 다시']} at={remove.isPending ? 1 : removeFailed ? 2 : 0} />
|
||
</button>
|
||
</>
|
||
)}
|
||
</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 = useInfiniteQuery({
|
||
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
|
||
initialPageParam: { path: { post_id: postId } },
|
||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||
})
|
||
const add = useMutation(addCommentMutation())
|
||
const [addFailed, setAddFailed] = useState(false)
|
||
const [text, setText] = useState('')
|
||
const inputRef = useRef<HTMLInputElement>(null)
|
||
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
||
|
||
const submit = (e: FormEvent) => {
|
||
e.preventDefault()
|
||
if (!loggedIn) return open({ type: 'login' })
|
||
const body = text.trim()
|
||
if (!body || add.isPending) return
|
||
setAddFailed(false)
|
||
add.mutate(
|
||
{ path: { post_id: postId }, body: { body } },
|
||
{
|
||
onSuccess: (res) => {
|
||
setAddFailed(!res.result?.success)
|
||
if (!res.result?.success) return
|
||
setText('')
|
||
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
|
||
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||
},
|
||
onError: () => setAddFailed(true),
|
||
},
|
||
)
|
||
}
|
||
|
||
return (
|
||
<>
|
||
<Body>
|
||
{comments.length ? (
|
||
<>
|
||
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
|
||
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} />)}
|
||
{list.hasNextPage && (
|
||
<button type="button" onClick={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 w-full cursor-pointer text-center text-sm font-bold text-(--ink3) disabled:opacity-50">
|
||
{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}
|
||
</button>
|
||
)}
|
||
</>
|
||
) : loadOf(list) === 'loading' ? (
|
||
<CommentsSkel />
|
||
) : (
|
||
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} className="inset-0" />
|
||
)}
|
||
</Body>
|
||
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
|
||
{EMOJIS.map((e) => (
|
||
<button
|
||
key={e}
|
||
type="button"
|
||
disabled={add.isPending}
|
||
className="cursor-pointer disabled:opacity-40"
|
||
onClick={() => {
|
||
setText((t) => (t + e).slice(0, 60))
|
||
inputRef.current?.focus()
|
||
}}
|
||
>
|
||
{e}
|
||
</button>
|
||
))}
|
||
</div>
|
||
<p className="h-4 px-4 text-center text-xs leading-4 font-bold text-(--heart)" role="alert">
|
||
{addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'}
|
||
</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)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 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">
|
||
<Swap labels={['게시', '올리는 중…']} at={add.isPending ? 1 : 0} />
|
||
</button>
|
||
</form>
|
||
</>
|
||
)
|
||
}
|
||
|
||
/* ---------- 로그인 ---------- */
|
||
const AUTH_ERRORS: Record<string, string> = {
|
||
AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.',
|
||
AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.',
|
||
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.',
|
||
}
|
||
|
||
function LoginSheet({ onDone }: { onDone: () => void }) {
|
||
const { me } = 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 <MeSheet onDone={onDone} />
|
||
|
||
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={mode === 'signup' ? 8 : undefined} maxLength={64} placeholder={mode === 'signup' ? '비밀번호 (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">
|
||
<Swap labels={mode === 'login' ? ['로그인', '로그인 중…'] : ['가입하고 시작하기', '가입하는 중…']} at={pending ? 1 : 0} />
|
||
</button>
|
||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
|
||
나중에 할게요
|
||
</button>
|
||
</form>
|
||
</Body>
|
||
)
|
||
}
|
||
|
||
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
|
||
function MeSheet({ onDone }: { onDone: () => void }) {
|
||
const { me, logout } = useAuth()
|
||
const queryClient = useQueryClient()
|
||
const update = useMutation(updateMeMutation())
|
||
const [nickname, setNickname] = useState(me?.nickname ?? '')
|
||
const [error, setError] = useState('')
|
||
if (!me) return null
|
||
|
||
const save = (body: { nickname?: string; character?: string; color?: string; mood?: string }) => {
|
||
setError('')
|
||
update.mutate(
|
||
{ body },
|
||
{
|
||
onSuccess: (res) => {
|
||
if (!res.result?.success) return setError(res.result?.desc === 'INVALID_INPUT' ? '닉네임은 2~12자로 써 주세요.' : '잠시 뒤에 다시 해 주세요.')
|
||
queryClient.setQueryData(meQueryKey(), res)
|
||
// 댓글에 보이는 내 캐릭터·닉네임도 바뀐다
|
||
queryClient.invalidateQueries({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments' })
|
||
},
|
||
onError: () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.'),
|
||
},
|
||
)
|
||
}
|
||
|
||
// 저장하는 동안은 고른 값을 바로 선택으로 보여 준다. 실패하면 me 값으로 돌아간다
|
||
const saving = update.isPending ? update.variables?.body : undefined
|
||
const character = saving?.character ?? me.character
|
||
const color = saving?.color ?? me.color
|
||
const mood = saving?.mood ?? me.mood
|
||
|
||
return (
|
||
<Body className="flex flex-col gap-3">
|
||
<div className="flex flex-col items-center gap-1.5">
|
||
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
|
||
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.login_id}(으)로 로그인했어요</p>
|
||
</div>
|
||
<section aria-label="내 캐릭터">
|
||
<h4 className="m-0 mb-2 text-sm font-extrabold">내 캐릭터</h4>
|
||
<div className="grid grid-cols-3 gap-2" role="radiogroup" aria-label="캐릭터 고르기">
|
||
{CHARACTERS.map(([key, label]) => (
|
||
<button
|
||
key={key}
|
||
type="button"
|
||
role="radio"
|
||
aria-checked={character === key}
|
||
disabled={update.isPending}
|
||
onClick={() => save({ character: key })}
|
||
className={cx('flex cursor-pointer flex-col items-center gap-1 rounded-[18px] border-2 bg-[#f7f9fc] py-2.5 font-jua text-[15px]', character === key ? 'border-(--orange) text-(--orange)' : 'border-transparent text-(--ink)')}
|
||
>
|
||
<Ic name={key} className="w-12" />
|
||
{label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</section>
|
||
<section aria-label="배경색">
|
||
<h4 className="m-0 mb-2 text-sm font-extrabold">배경색</h4>
|
||
<div className="flex flex-wrap gap-2.5" role="radiogroup" aria-label="배경색 고르기">
|
||
{Object.entries(AVATAR_COLORS).map(([key, hex]) => (
|
||
<button
|
||
key={key}
|
||
type="button"
|
||
role="radio"
|
||
aria-checked={color === key}
|
||
aria-label={key}
|
||
disabled={update.isPending}
|
||
onClick={() => save({ color: key })}
|
||
className={cx('size-9 cursor-pointer rounded-full border-[3px]', color === key ? 'border-(--ink)' : 'border-white shadow-[0_0_0_1px_var(--line)]')}
|
||
style={{ background: hex }}
|
||
/>
|
||
))}
|
||
</div>
|
||
</section>
|
||
<section aria-label="오늘 기분">
|
||
<h4 className="m-0 mb-2 text-sm font-extrabold">오늘 기분</h4>
|
||
<div className="grid grid-cols-4 gap-2" role="radiogroup" aria-label="오늘 기분 고르기">
|
||
{MOODS.map(([key, emoji, label]) => (
|
||
<button
|
||
key={key}
|
||
type="button"
|
||
role="radio"
|
||
aria-checked={mood === key}
|
||
disabled={update.isPending}
|
||
onClick={() => save({ mood: mood === key ? '' : key })}
|
||
className={cx('flex cursor-pointer flex-col items-center gap-0.5 rounded-[14px] border-2 bg-[#f7f9fc] py-2 text-xs font-bold', mood === key ? 'border-(--orange) text-(--orange)' : 'border-transparent text-(--ink2)')}
|
||
>
|
||
<span className="text-[22px] leading-none">{emoji}</span>
|
||
{label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">한 번 더 누르면 지워져요</p>
|
||
</section>
|
||
<form
|
||
className="flex items-center gap-2"
|
||
onSubmit={(e) => {
|
||
e.preventDefault()
|
||
save({ nickname: nickname.trim() })
|
||
}}
|
||
>
|
||
<input value={nickname} onChange={(e) => setNickname(e.target.value)} required minLength={2} maxLength={12} aria-label="닉네임" placeholder="닉네임 (2~12자)" className="flex-1 rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3" />
|
||
<button type="submit" disabled={update.isPending || nickname.trim() === me.nickname} className="cursor-pointer rounded-[14px] bg-(--ink) px-4 py-3 text-sm font-extrabold text-white disabled:opacity-40">
|
||
<Swap labels={['바꾸기', '저장 중…']} at={saving?.nickname != null ? 1 : 0} />
|
||
</button>
|
||
</form>
|
||
<p className={cx('m-0 min-h-5 text-center text-[13px] font-bold', saving ? 'text-(--ink2)' : 'text-(--heart)')} aria-live="polite">
|
||
{saving ? (saving.nickname == null ? '저장 중…' : '') : error}
|
||
</p>
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
logout()
|
||
onDone()
|
||
}}
|
||
className="cursor-pointer rounded-[14px] bg-[#f3f6fb] p-[13px] text-[15px] font-extrabold text-(--ink)"
|
||
>
|
||
로그아웃
|
||
</button>
|
||
</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 ?? []
|
||
const listLoad = loadOf(list)
|
||
|
||
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" />
|
||
{listLoad === 'loading' && <RegionsSkel />}
|
||
{listLoad !== 'loading' && !regions.length && (listLoad === 'ready' ? <StateBox load={listLoad} empty="찾는 구가 없어요." className="mt-3" /> : <StateBox load={listLoad} onRetry={() => list.refetch()} hold={<RegionsSkel />} className="inset-x-0 top-2 bottom-0" />)}
|
||
<ul className={cx('mt-2 flex flex-col transition-opacity', list.isPlaceholderData && 'opacity-60')}>
|
||
{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>
|
||
)
|
||
}
|