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

1046 lines
46 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { 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 { SITE_URL } from '../api/setup'
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 { track } from '../lib/analytics'
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 { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
import { HeartIcon } from './svg'
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
export function SheetProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<SheetState>(null)
// 창이 열려 있는 동안 방문 기록을 하나 쌓아 두어 뒤로 가기가 창만 닫게 한다
const pushed = useRef(false)
const open = useCallback((s: Exclude<SheetState, null>) => {
if (!pushed.current) {
window.history.pushState({ ...window.history.state, sheet: true }, '')
pushed.current = true
}
setState(s)
}, [])
const close = useCallback(() => {
setState(null)
if (!pushed.current) return
pushed.current = false
window.history.back()
}, [])
const api = useMemo(() => ({ open, close }), [open, close])
useEffect(() => {
const onPop = () => {
if (!pushed.current) return
pushed.current = false
setState(null)
}
window.addEventListener('popstate', onPop)
return () => window.removeEventListener('popstate', onPop)
}, [])
// 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다
useEffect(() => subscribeAuth((reason) => reason === 'required' && open({ type: 'login' })), [open])
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 { kind } = useSky()
const { open } = useSheet()
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 then = state?.type === 'login' ? state.then : undefined
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
return (
<dialog
ref={ref}
aria-label={title}
data-t={kind}
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 pb-[env(safe-area-inset-bottom,0px)]">
<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-(--line)" aria-hidden="true" />
<h3 className="m-0 text-[15px] font-extrabold">{title}</h3>
<button type="button" onClick={onClose} aria-label="닫기" className={cx('absolute right-3 bottom-2 grid size-[30px] cursor-pointer place-items-center text-xl text-(--ink2)', TAP44)}>
×
</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} draft={state.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : 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 SLOT_KEYS = ['morning', 'day', 'evening', 'night'] as const
const SLOT_NAMES = { morning: '아침', day: '낮', evening: '저녁', night: '밤' } as const
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 tracked = useRef(0)
useEffect(() => {
if (!g || tracked.current === g.index_id) return
tracked.current = g.index_id
track('view_gak', { index_id: g.index_id, gak_name: g.name, score: g.score, rank: g.rank })
}, [g])
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 ?? []
const bands = d.bands ?? []
const now = bands.find((b) => b.current)
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={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
</div>
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{now && (
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
{now.text}
</p>
)}
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
{g.slots && g.slots.length > 0 && (
<div className="mt-2.5 grid grid-cols-4 gap-1.5" aria-label="오늘 시간대별 점수">
{SLOT_KEYS.map((k) => {
const s = g.slots?.find((x) => x.slot === k)
const cur = g.active && g.slot === k
return (
<div key={k} className={cx('rounded-2xl px-1 py-2 text-center', cur ? 'bg-[#fff4ec]' : 'bg-[#f3f6fb]')}>
<small className="block text-xs font-extrabold text-(--ink2)">
{SLOT_NAMES[k]}
{cur && ' · 지금'}
</small>
<b className={cx('block font-bagel text-xl font-normal', s ? 'text-(--orange)' : 'text-(--ink3)')}>{s ? s.score : '–'}</b>
</div>
)
})}
</div>
)}
{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>
)}
{bands.length > 0 && (
<ol className="mt-3.5 flex flex-col gap-1.5" aria-label="점수 구간별 설명">
{bands.map((b) => (
<li key={b.low} className={cx('grid grid-cols-[62px_1fr] items-start gap-2 text-[13px] font-semibold', !b.current && 'opacity-45')}>
<span className={cx('rounded-full py-px text-center font-jua text-xs text-white tabular-nums', b.current ? 'bg-(--orange)' : 'bg-(--ink3)')}>
{b.low}~{b.high}
</span>
<span>{b.text}</span>
</li>
))}
</ol>
)}
<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 tracked = useRef(0)
useEffect(() => {
if (!a || tracked.current === a.article_id) return
tracked.current = a.article_id
track('select_content', { content_type: 'article', item_id: a.article_id, category: ARTICLE_CAT[a.category]?.[0] ?? a.category })
}, [a])
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>
<Thumb image={a.image} icon={a.icon} credit={a.image_credit} className={cx('mb-3.5 h-[150px] rounded-[20px]', `b-bg-${cardBg(a.icon, a.article_id)}`)} iconClassName="w-24" />
<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>
)
}
/* ---------- 보내기 ---------- */
const SIZE_KEYS = Object.keys(SHARE_SIZES) as ShareSize[]
function ShareSheet({ share }: { share: SharePayload }) {
const { region } = useRegion()
const { kind } = useSky()
const [size, setSize] = useState<ShareSize>('story')
const [images, setImages] = useState<Partial<Record<ShareSize, { blob: Blob; src: string }>>>({})
const [failed, setFailed] = useState<Partial<Record<ShareSize, boolean>>>({})
const srcs = useRef<string[]>([])
const [toast, setToast] = useState('')
const image = images[size]
const text = `${share.title} · 날씨각 ${SITE_URL}`
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
useEffect(() => {
if (images[size] || failed[size]) return
let alive = true
const today = new Date().toLocaleDateString('ko-KR', { month: 'long', day: 'numeric', weekday: 'long' })
shareImage(share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
(blob) => {
if (!alive) return
const src = URL.createObjectURL(blob)
srcs.current.push(src)
setImages((m) => ({ ...m, [size]: { blob, src } }))
},
(e: unknown) => {
console.error('[share] image', e)
if (alive) setFailed((m) => ({ ...m, [size]: true }))
},
)
return () => {
alive = false
}
}, [size, images, failed, share.slides, kind, region.name])
useEffect(() => {
const list = srcs.current
return () => list.forEach((s) => URL.revokeObjectURL(s))
}, [])
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 공유창이 없으면 이미지를 내려받고 링크를 복사한다
const send = () => {
if (!image) return
const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' })
if (navigator.canShare?.({ files: [file], text })) {
navigator.share({ files: [file], title: share.title, text }).then(
() => {
setToast('보냈어요')
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
},
(e: unknown) => {
if (e instanceof DOMException && e.name === 'AbortError') return
console.error('[share] send', e)
setToast('보내지 못했어요. 한 번 더 눌러 주세요')
},
)
return
}
const a = document.createElement('a')
a.href = image.src
a.download = file.name
a.click()
track('share', { content_type: 'image', item_id: share.title, method: 'download', ratio: SHARE_SIZES[size].ratio })
if (!navigator.clipboard) {
setToast('이미지를 내려받았어요')
return
}
navigator.clipboard.writeText(text).then(
() => setToast('이미지를 내려받고 링크를 복사했어요'),
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
)
}
return (
<Body>
<div className="grid grid-cols-3 gap-1.5 rounded-[16px] bg-[#f3f6fb] p-1" role="radiogroup" aria-label="이미지 크기">
{SIZE_KEYS.map((k) => (
<button key={k} type="button" role="radio" aria-checked={size === k} aria-label={`${SHARE_SIZES[k].ratio} 비율`} onClick={() => setSize(k)} className={cx('flex cursor-pointer items-center justify-center gap-2 rounded-[12px] py-2 text-sm font-extrabold', size === k ? 'bg-white text-(--ink) shadow-[0_2px_6px_rgb(40_48_74/0.12)]' : 'text-(--ink3)')}>
<i className="h-4 rounded-[3px] border-2 border-current" style={{ aspectRatio: `${SHARE_SIZES[k].w} / ${SHARE_SIZES[k].hr}` }} aria-hidden="true" />
{SHARE_SIZES[k].ratio}
</button>
))}
</div>
<div className="mt-3 flex h-[300px] items-center justify-center rounded-[18px] bg-[#f3f6fb] p-3">
{image ? (
<img src={image.src} alt={`${SHARE_SIZES[size].ratio} 공유 이미지 미리보기`} className="max-h-full max-w-full rounded-[10px] shadow-[0_4px_12px_rgb(40_48_74/0.18)]" />
) : (
<span className="text-sm font-bold text-(--ink3)">{failed[size] ? '이미지를 만들지 못했어요' : '이미지 만드는 중'}</span>
)}
</div>
<button type="button" onClick={send} disabled={!image} className="mt-3.5 block w-full cursor-pointer rounded-[16px] bg-(--orange) py-3 font-jua text-base text-white shadow-[inset_0_-4px_0_var(--orange-deep)] disabled:opacity-50">
공유하기
</button>
<p className="mt-3 min-h-5 text-center text-[13px] font-bold text-[#1f9d62]" aria-live="polite">
{toast}
</p>
</Body>
)
}
/* ---------- 댓글 ---------- */
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
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 [likeFailed, setLikeFailed] = useState(false)
const toggle = () => {
if (!loggedIn) return open({ type: 'login' })
if (like.isPending || unlike.isPending) return
const next = !liked
setLikeFailed(false)
setLiked(next)
setCount((n) => n + (next ? 1 : -1))
const revert = () => {
setLiked(!next)
setCount(c.like_count)
}
;(next ? like : unlike).mutate(
{ path: { comment_id: c.comment_id } },
{
onSuccess: (res) => {
if (res.result?.success) {
setLiked(!!res.liked)
if (res.like_count != null) setCount(res.like_count)
return
}
revert()
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
else setLikeFailed(true)
},
onError: () => {
revert()
setLikeFailed(true)
},
},
)
}
// 지우는 동안은 흐리게 두고, 성공하면 다시 받기 전에 목록 캐시에서 바로 뺀다
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)} · {likeFailed ? <span className="text-(--heart)" role="alert">좋아요를 못 했어요. 잠시 뒤에 다시 눌러 주세요</span> : `좋아요 ${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={cx('relative cursor-pointer pt-1', TAP44)}>
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
</button>
</div>
)
}
function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
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(draft ?? '')
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', then: { type: 'comments', postId, draft: text } })
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-2.5">
<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, onLoggedIn }: { onDone: () => void; onLoggedIn: () => 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)
track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' })
onLoggedIn()
}
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 alive = useRef(true)
useEffect(() => {
alive.current = true
return () => {
alive.current = false
}
}, [])
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(() => alive.current && onDone())} 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)
track('region_change', { region_name: r.name, method: 'list' })
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>
)
}