1476 lines
65 KiB
TypeScript
1476 lines
65 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 { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
|
||
import { SITE_URL } from '../api/setup'
|
||
import {
|
||
addCommentMutation,
|
||
addTalkCommentMutation,
|
||
agreeTermsMutation,
|
||
blockAuthorMutation,
|
||
deleteCommentMutation,
|
||
getArticleOptions,
|
||
getFeedQueryKey,
|
||
getIndexOptions,
|
||
getSeasonWeekOptions,
|
||
likeCommentMutation,
|
||
listCommentsInfiniteOptions,
|
||
listTalkCommentsInfiniteOptions,
|
||
listTalkCommentsInfiniteQueryKey,
|
||
listBlockedOptions,
|
||
listBlockedQueryKey,
|
||
listCommentsInfiniteQueryKey,
|
||
listRegionsOptions,
|
||
meQueryKey,
|
||
reportCommentMutation,
|
||
tossMutation,
|
||
unblockMutation,
|
||
unlikeCommentMutation,
|
||
updateMeMutation,
|
||
withdrawMutation,
|
||
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||
import { AuthProvider, ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
|
||
import { track } from '../lib/analytics'
|
||
import { IS_TOSS, tossLogin, tossShare } from '../lib/platform'
|
||
import { cx } from '../lib/utils'
|
||
import { useAuth } from './authContext'
|
||
import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
|
||
import { GoogleButton } from './googleLogin'
|
||
import { useInstall, useInstallable } from './install'
|
||
import { InstallSheet } from './installBanner'
|
||
import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib'
|
||
import { MixSheet, MyGakSheet } from './myGak'
|
||
import { TarotSheet } from './fortune'
|
||
import { LevelCard, LevelSheet, LevelUpSheet, useShareReward } from './level'
|
||
import { ownPage, useRegion } from './regionContext'
|
||
import { WeatherWhySheet } from './weatherWhy'
|
||
import { useSky } from './skyContext'
|
||
import { LEVELS } from './cloudMerge'
|
||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||
import { SheetContext, useSheet, type CommentTarget, type SharePayload, type SheetState } from './sheetContext'
|
||
import { HeartIcon } from './svg'
|
||
import { MyTalks } from './talk'
|
||
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
|
||
}
|
||
track('sheet_open', { sheet: s.type })
|
||
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: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기', tarot: '오늘 타로', level: '내 레벨', levelUp: '레벨이 올랐어요', gameHelp: '구름 합치기 하는 법', contact: '날씨각 문의' } 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('')
|
||
|
||
// 닫히는 동안에도 내려가는 창에 내용이 남아 있게, 마지막으로 연 창을 들고 있는다
|
||
const [shown, setShown] = useState<SheetState>(state)
|
||
if (state && state !== shown) setShown(state)
|
||
const closing = !state && shown != null
|
||
|
||
useEffect(() => {
|
||
const el = ref.current
|
||
if (!el) return
|
||
if (state) {
|
||
if (!el.open) el.showModal()
|
||
return
|
||
}
|
||
if (!el.open) return
|
||
// 내려가는 애니메이션이 끝난 뒤에 실제로 닫는다
|
||
const t = setTimeout(() => {
|
||
el.close()
|
||
setShown(null)
|
||
}, SHEET_CLOSE_MS)
|
||
return () => clearTimeout(t)
|
||
}, [state])
|
||
|
||
// 창이 열려 있는 동안 뒤 페이지는 스크롤되지 않게 잠근다
|
||
const isOpen = state != null
|
||
useEffect(() => {
|
||
if (!isOpen) return
|
||
const root = document.documentElement
|
||
const before = root.style.overflow
|
||
root.style.overflow = 'hidden'
|
||
// 뒤 화면 움직임 멈추기는 페이지 전체 스타일을 다시 계산하게 해서, 창이 다 올라온 뒤에 한다
|
||
const pause = setTimeout(() => root.classList.add('b-sheet-open'), SHEET_OPEN_MS)
|
||
return () => {
|
||
clearTimeout(pause)
|
||
root.style.overflow = before
|
||
root.classList.remove('b-sheet-open')
|
||
}
|
||
}, [isOpen])
|
||
|
||
const then = shown?.type === 'login' ? shown.then : undefined
|
||
const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : shown.type === 'myGak' ? '내 각' : TITLES[shown.type]
|
||
|
||
return (
|
||
<dialog
|
||
ref={ref}
|
||
aria-label={title}
|
||
data-t={kind}
|
||
onClose={onClose}
|
||
// ESC 도 바로 닫지 않고 내려가며 닫히게
|
||
onCancel={(e) => {
|
||
e.preventDefault()
|
||
onClose()
|
||
}}
|
||
onClick={(e) => {
|
||
if (e.target === e.currentTarget) onClose()
|
||
}}
|
||
className={cx('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)', closing && 'b-sheet-closing')}
|
||
>
|
||
{shown && (
|
||
<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>
|
||
{shown.type === 'gak' && <GakSheet indexId={shown.indexId} onTitle={setGakTitle} />}
|
||
{shown.type === 'article' && <ArticleSheet articleId={shown.articleId} onTitle={setArticleTitle} />}
|
||
{shown.type === 'seasonWeek' && <SeasonWeekSheet />}
|
||
{shown.type === 'share' && <ShareSheet share={shown.share} />}
|
||
{shown.type === 'comments' && <CommentsSheet to={shown} draft={shown.draft} />}
|
||
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={shown.why} />}
|
||
{shown.type === 'me' && <MeSheet onDone={onClose} />}
|
||
{shown.type === 'region' && <RegionSheet onDone={onClose} />}
|
||
{shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
|
||
{shown.type === 'myGak' && <MyGakSheet gak={shown.gak} shot={shown.shot} onDone={onClose} />}
|
||
{shown.type === 'install' && <InstallSheet />}
|
||
{shown.type === 'weatherWhy' && <WeatherWhySheet d={shown.why} />}
|
||
{shown.type === 'tarot' && <TarotSheet />}
|
||
{shown.type === 'level' && <LevelSheet />}
|
||
{shown.type === 'levelUp' && <LevelUpSheet level={shown.level} />}
|
||
{shown.type === 'gameHelp' && <GameHelpSheet />}
|
||
{shown.type === 'contact' && <ContactSheet 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="b-keep-bg 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>
|
||
)
|
||
}
|
||
|
||
/* ---------- 이번 주 특집 ---------- */
|
||
const GAME_STEPS = [
|
||
'목표 점수를 채우면 다음 라운드로 넘어가요. 라운드가 오를수록 목표가 높아져요.',
|
||
'손가락을 좌우로 움직여 떨어뜨릴 자리를 고르고, 손을 떼면 떨어져요.',
|
||
'떨어지는 동안 오늘 우리 동네 바람만큼 옆으로 밀려요. 바람 방향을 보고 조금 비켜 떨어뜨리세요.',
|
||
'같은 그림끼리 닿으면 한 단계 큰 그림으로 합쳐지고 점수가 올라요.',
|
||
'해 둘이 만나면 사라지면서 보너스 점수!',
|
||
'쌓인 그림이 위쪽 점선을 넘은 채로 잠깐 있으면 끝나요. 판은 다음 라운드로 그대로 이어져요.',
|
||
'로그인하면 라운드를 깰 때마다 2각을 받아요. 하루 20각까지예요.',
|
||
]
|
||
|
||
function GameHelpSheet() {
|
||
return (
|
||
<Body>
|
||
<ol className="m-0 flex list-decimal flex-col gap-2 pl-5 text-[15px] leading-[1.6]">
|
||
{GAME_STEPS.map((t) => (
|
||
<li key={t}>{t}</li>
|
||
))}
|
||
</ol>
|
||
<p className="mt-4 mb-2 text-[13px] font-extrabold text-(--ink2)">합쳐지는 순서</p>
|
||
<div className="grid grid-cols-4 gap-2 rounded-[16px] bg-[#f3f6fb] p-3">
|
||
{LEVELS.map((l, i) => (
|
||
<span key={l.icon} className="flex flex-col items-center gap-0.5 text-[12px] font-bold">
|
||
<Ic name={l.icon} className="size-8" />
|
||
{i + 1}. {l.name}
|
||
</span>
|
||
))}
|
||
</div>
|
||
</Body>
|
||
)
|
||
}
|
||
|
||
const CONTACTS = [
|
||
{ method: 'phone', label: '전화 문의', value: '010-2755-6463', href: 'tel:010-2755-6463', icon: 'M6.6 3h3l1.5 4.2-2 1.5a12 12 0 0 0 6.2 6.2l1.5-2L21 14.4v3A2.6 2.6 0 0 1 18.4 20 15.4 15.4 0 0 1 4 5.6 2.6 2.6 0 0 1 6.6 3Z' },
|
||
{ method: 'email', label: '이메일 문의', value: 'sales@o2o.kr', href: 'mailto:sales@o2o.kr', icon: 'M3.5 6.5h17v11h-17zM4 7l8 6.5L20 7' },
|
||
] as const
|
||
|
||
/** 오른쪽 아래 문의 버튼으로 여는 창: 운영사 소개와 전화·이메일 */
|
||
function ContactSheet({ onDone }: { onDone: () => void }) {
|
||
return (
|
||
<Body className="flex flex-col items-center text-center">
|
||
<img src="/b/aio2o.png" alt="AIO2O" width={162} height={27} className="mt-1 block h-[27px] w-auto" />
|
||
<h4 className="mt-3 mb-0 font-jua text-[22px] font-normal">날씨각과 함께할까요?</h4>
|
||
<p className="mt-1.5 mb-0 text-[13.5px] leading-[1.6] font-semibold text-(--ink2)">
|
||
날씨에 맞춘 광고, 지역 축제·행사 소개,
|
||
<br />
|
||
콘텐츠 협업 같은 제휴 문의를 받아요.
|
||
<br />
|
||
전화나 이메일로 편하게 알려 주세요.
|
||
</p>
|
||
<div className="mt-4 flex w-full flex-col gap-2">
|
||
{CONTACTS.map((c) => (
|
||
<a key={c.method} href={c.href} onClick={() => track('contact_click', { method: c.method })} className="flex items-center gap-3 rounded-[16px] bg-[#f3f6fb] p-3 text-left text-(--ink)">
|
||
<span className="b-keep-bg grid size-11 shrink-0 place-items-center rounded-full bg-white text-(--orange)">
|
||
<svg viewBox="0 0 24 24" className="size-[22px]" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||
<path d={c.icon} />
|
||
</svg>
|
||
</span>
|
||
<span className="flex min-w-0 flex-1 flex-col">
|
||
<span className="text-[12px] font-bold text-(--ink2)">{c.label}</span>
|
||
<span className="truncate text-[17px] font-extrabold">{c.value}</span>
|
||
</span>
|
||
<span className="text-xl text-(--orange)" aria-hidden="true">
|
||
›
|
||
</span>
|
||
</a>
|
||
))}
|
||
</div>
|
||
<p className="mt-3.5 mb-0 text-[12px] font-semibold text-(--ink3)">날씨각은 주식회사 에이아이오투오가 만들어요</p>
|
||
<button type="button" onClick={onDone} className="mt-3 w-full cursor-pointer rounded-[14px] bg-(--orange) p-3 text-[15px] font-extrabold text-white">
|
||
확인
|
||
</button>
|
||
</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 reward = useShareReward()
|
||
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} · 날씨각`
|
||
const url = share.url ?? 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(size === 'square' && share.square ? share.square : 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, share.square, 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 (IS_TOSS) {
|
||
tossShare(image.blob, file.name, share.title).then(
|
||
(r) => {
|
||
setToast(r === 'saved' ? '이미지를 저장하고 링크를 보냈어요' : '링크를 보냈어요')
|
||
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
|
||
reward()
|
||
},
|
||
(e: unknown) => {
|
||
console.error('[share] toss', e)
|
||
setToast('보내지 못했어요. 한 번 더 눌러 주세요')
|
||
},
|
||
)
|
||
return
|
||
}
|
||
if (navigator.canShare?.({ files: [file], text, url })) {
|
||
const copied = navigator.clipboard?.writeText(url).then(
|
||
() => true,
|
||
(e: unknown) => {
|
||
console.error('[share] copy link', e)
|
||
return false
|
||
},
|
||
)
|
||
navigator.share({ files: [file], title: share.title, text, url }).then(
|
||
async () => {
|
||
setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요')
|
||
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
|
||
reward()
|
||
},
|
||
(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} ${url}`).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 = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
|
||
const REPORT_REASONS = [
|
||
[ReportReason.ABUSE, '욕설·비하'],
|
||
[ReportReason.AD, '광고'],
|
||
[ReportReason.PRIVACY, '개인정보 노출'],
|
||
[ReportReason.OTHER, '기타'],
|
||
] as const
|
||
const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments'
|
||
|
||
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
|
||
function CommentMenu({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
|
||
const { loggedIn } = useAuth()
|
||
const { open } = useSheet()
|
||
const queryClient = useQueryClient()
|
||
const [step, setStep] = useState<'closed' | 'menu' | 'report' | 'block'>('closed')
|
||
const [failed, setFailed] = useState(false)
|
||
const report = useMutation(reportCommentMutation())
|
||
const block = useMutation(blockAuthorMutation())
|
||
const pending = report.isPending || block.isPending
|
||
|
||
const finish = (notice: string, done: () => void) => ({
|
||
onSuccess: (res: { result?: { success?: boolean } }) => {
|
||
if (!res.result?.success) return setFailed(true)
|
||
done()
|
||
setStep('closed')
|
||
onNotice(notice)
|
||
queryClient.invalidateQueries({ predicate: isCommentList })
|
||
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() })
|
||
},
|
||
onError: () => setFailed(true),
|
||
})
|
||
const go = (next: typeof step) => {
|
||
setFailed(false)
|
||
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', ...to } })
|
||
setStep(next)
|
||
}
|
||
const btn = 'cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50'
|
||
|
||
return (
|
||
<>
|
||
<button type="button" onClick={() => go(step === 'closed' ? 'menu' : 'closed')} aria-expanded={step !== 'closed'} aria-label="댓글 메뉴" className="ml-1.5 cursor-pointer px-1 font-extrabold text-(--ink3)">
|
||
⋯
|
||
</button>
|
||
{step !== 'closed' && (
|
||
<span className="mt-2 flex flex-wrap items-center gap-1.5" role="group" aria-label="댓글 메뉴">
|
||
{step === 'menu' && (
|
||
<>
|
||
<button type="button" className={btn} onClick={() => go('report')}>
|
||
신고하기
|
||
</button>
|
||
<button type="button" className={btn} onClick={() => go('block')}>
|
||
이 사람 차단하기
|
||
</button>
|
||
</>
|
||
)}
|
||
{step === 'report' &&
|
||
REPORT_REASONS.map(([reason, label]) => (
|
||
<button key={reason} type="button" disabled={pending} className={btn} onClick={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.', () => track('report', { content_type: 'comment', reason })))}>
|
||
{label}
|
||
</button>
|
||
))}
|
||
{step === 'block' && (
|
||
<>
|
||
<span className="w-full text-[13px] font-bold text-(--ink)">{c.nickname}님 댓글을 더는 안 볼까요?</span>
|
||
<button type="button" disabled={pending} className={cx(btn, 'bg-(--heart) text-white')} onClick={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.', () => track('block', { content_type: 'comment' })))}>
|
||
차단하기
|
||
</button>
|
||
<button type="button" disabled={pending} className={btn} onClick={() => go('closed')}>
|
||
취소
|
||
</button>
|
||
</>
|
||
)}
|
||
{failed && (
|
||
<span className="w-full text-[13px] font-bold text-(--heart)" role="alert">
|
||
잠시 뒤에 다시 해 주세요.
|
||
</span>
|
||
)}
|
||
</span>
|
||
)}
|
||
</>
|
||
)
|
||
}
|
||
|
||
function CommentRow({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
|
||
const { region } = useRegion()
|
||
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 (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)
|
||
if (next) track('like', { content_type: 'comment', item_id: c.comment_id })
|
||
return
|
||
}
|
||
revert()
|
||
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
|
||
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: commentListKey(to) })
|
||
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 = commentListKey(to)
|
||
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.official && <span className="mr-1.5 inline-block -translate-y-px rounded-md bg-(--orange) px-1.5 py-px align-middle text-[10.5px] font-extrabold text-white">날씨각</span>}
|
||
{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>
|
||
</>
|
||
)}
|
||
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
|
||
{!c.mine && !c.official && <CommentMenu c={c} to={to} onNotice={onNotice} />}
|
||
</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 commentListKey(to: CommentTarget) {
|
||
return 'talkId' in to ? listTalkCommentsInfiniteQueryKey({ path: { talk_id: to.talkId } }) : listCommentsInfiniteQueryKey({ path: { post_id: to.postId } })
|
||
}
|
||
|
||
/** 포스트 댓글, 또는 사람 글 댓글(로그인한 사람만 쓴다) */
|
||
function CommentsSheet({ to, draft }: { to: CommentTarget; draft?: string }) {
|
||
const { region } = useRegion()
|
||
const { me } = useAuth()
|
||
const { open } = useSheet()
|
||
const queryClient = useQueryClient()
|
||
const talkId = 'talkId' in to ? to.talkId : undefined
|
||
const postId = 'postId' in to ? to.postId : undefined
|
||
// 둘 중 하나만 받는다
|
||
const postList = useInfiniteQuery({
|
||
...listCommentsInfiniteOptions({ path: { post_id: postId ?? 0 } }),
|
||
initialPageParam: { path: { post_id: postId ?? 0 } },
|
||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||
enabled: postId != null,
|
||
})
|
||
const talkList = useInfiniteQuery({
|
||
...listTalkCommentsInfiniteOptions({ path: { talk_id: talkId ?? 0 } }),
|
||
initialPageParam: { path: { talk_id: talkId ?? 0 } },
|
||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||
enabled: talkId != null,
|
||
})
|
||
const list = talkId != null ? talkList : postList
|
||
const addPost = useMutation(addCommentMutation())
|
||
const addTalk = useMutation(addTalkCommentMutation())
|
||
const add = { isPending: addPost.isPending || addTalk.isPending }
|
||
const agree = useMutation(agreeTermsMutation())
|
||
const [addFailed, setAddFailed] = useState(false)
|
||
const [askTerms, setAskTerms] = useState(false)
|
||
const [notice, setNotice] = useState('')
|
||
const [text, setText] = useState(draft ?? '')
|
||
const inputRef = useRef<HTMLInputElement>(null)
|
||
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
||
|
||
useEffect(() => {
|
||
if (!notice) return
|
||
const t = setTimeout(() => setNotice(''), 3000)
|
||
return () => clearTimeout(t)
|
||
}, [notice])
|
||
|
||
const send = () => {
|
||
const body = text.trim()
|
||
if (!body || add.isPending) return
|
||
setAddFailed(false)
|
||
const handlers = {
|
||
onSuccess: (res: { result?: { success?: boolean; desc?: string } }) => {
|
||
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true)
|
||
setAddFailed(!res.result?.success)
|
||
if (!res.result?.success) return
|
||
setText('')
|
||
queryClient.invalidateQueries({ queryKey: commentListKey(to) })
|
||
if (talkId != null) {
|
||
track('talk_comment', { talk_id: talkId })
|
||
queryClient.invalidateQueries({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listTalks' })
|
||
} else if (postId != null) {
|
||
track('comment', { post_id: postId })
|
||
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||
}
|
||
},
|
||
onError: () => setAddFailed(true),
|
||
}
|
||
if (talkId != null) addTalk.mutate({ path: { talk_id: talkId }, body: { body } }, handlers)
|
||
else if (postId != null) addPost.mutate({ path: { post_id: postId }, body: { body, region: region.code } }, handlers)
|
||
}
|
||
|
||
// 로그인했으면 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
|
||
const submit = (e: FormEvent) => {
|
||
e.preventDefault()
|
||
if (talkId != null && !me) return open({ type: 'login', then: { type: 'comments', ...to, draft: text } })
|
||
if (me && !me.terms_agreed) return setAskTerms(true)
|
||
send()
|
||
}
|
||
const agreeAndSend = () => {
|
||
setAddFailed(false)
|
||
agree.mutate(
|
||
{},
|
||
{
|
||
onSuccess: (res) => {
|
||
if (!res.result?.success) return setAddFailed(true)
|
||
track('terms_agree', {})
|
||
queryClient.setQueryData(meQueryKey(), res)
|
||
setAskTerms(false)
|
||
send()
|
||
},
|
||
onError: () => setAddFailed(true),
|
||
},
|
||
)
|
||
}
|
||
|
||
return (
|
||
<>
|
||
<Body>
|
||
{comments.length ? (
|
||
<>
|
||
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
|
||
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} to={to} onNotice={setNotice} />)}
|
||
{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>
|
||
{askTerms ? (
|
||
<div className="mx-3 flex flex-col gap-2 rounded-[16px] bg-[#f3f6fb] p-3" role="dialog" aria-label="이용약관 동의">
|
||
<p className="m-0 text-[13px] font-bold text-(--ink)">댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.</p>
|
||
<div className="flex gap-2">
|
||
<a href="/terms.html" target="_blank" rel="noopener" className="flex-1 rounded-[12px] bg-white p-2.5 text-center text-[13px] font-extrabold text-(--ink)">
|
||
이용약관 보기
|
||
</a>
|
||
<button type="button" onClick={agreeAndSend} disabled={agree.isPending || add.isPending} className="flex-1 cursor-pointer rounded-[12px] bg-(--orange) p-2.5 text-[13px] font-extrabold text-white disabled:opacity-60">
|
||
동의하고 쓰기
|
||
</button>
|
||
</div>
|
||
</div>
|
||
) : (
|
||
<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={cx('h-4 px-4 text-center text-xs leading-4 font-bold', addFailed ? 'text-(--heart)' : 'text-(--ink2)')} role="alert">
|
||
{addFailed ? '댓글을 올리지 못했어요. 다시 해 주세요.' : notice}
|
||
</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}(으)로 댓글 달기…` : talkId != null ? '로그인하고 댓글 달기…' : '댓글 달기…'} 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 || !text.trim()} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
|
||
<Swap labels={['게시', '올리는 중…']} at={add.isPending ? 1 : 0} />
|
||
</button>
|
||
</form>
|
||
</>
|
||
)
|
||
}
|
||
|
||
/* ---------- 로그인 ---------- */
|
||
function LoginSheet({ onDone, onLoggedIn, why }: { onDone: () => void; onLoggedIn: () => void; why?: 'level' }) {
|
||
const { me } = useAuth()
|
||
const [error, setError] = useState('')
|
||
|
||
const done = (res: ResAuth) => {
|
||
if (!res.result?.success || !res.access_token) {
|
||
setError('구글로 로그인하지 못했어요. 다시 해 주세요.')
|
||
return
|
||
}
|
||
setTokens(res.access_token, res.refresh_token ?? null)
|
||
if (res.is_new) track('sign_up', { method: 'google' })
|
||
else track('login', { method: 'google' })
|
||
onLoggedIn()
|
||
}
|
||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||
|
||
if (me) return <MeSheet onDone={onDone} />
|
||
if (IS_TOSS) return <TossLoginSheet onDone={onDone} onLoggedIn={onLoggedIn} />
|
||
|
||
return (
|
||
<Body>
|
||
<div className="flex flex-col gap-2.5">
|
||
<p className="text-center text-sm font-semibold text-(--ink2)">{why === 'level' ? '로그인하면 출석·사주·좋아요로 각이 쌓여 레벨이 올라요.' : '글쓰기는 로그인한 뒤에 할 수 있어요.'}</p>
|
||
<GoogleButton
|
||
onResult={(res) => {
|
||
setError('')
|
||
done(res)
|
||
}}
|
||
onFail={fail}
|
||
/>
|
||
<p className="m-0 text-center text-[13px] font-bold text-(--heart) empty:hidden" aria-live="polite">
|
||
{error}
|
||
</p>
|
||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
|
||
나중에 할게요
|
||
</button>
|
||
</div>
|
||
</Body>
|
||
)
|
||
}
|
||
|
||
/** 앱인토스는 토스 로그인만 쓸 수 있다 */
|
||
function TossLoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
|
||
const [error, setError] = useState('')
|
||
const [opening, setOpening] = useState(false)
|
||
const toss = useMutation(tossMutation())
|
||
const pending = opening || toss.isPending
|
||
|
||
const start = async () => {
|
||
setError('')
|
||
setOpening(true)
|
||
let code: Awaited<ReturnType<typeof tossLogin>>
|
||
try {
|
||
code = await tossLogin()
|
||
} catch (e) {
|
||
console.error('[login] toss', e)
|
||
setError('토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.')
|
||
return
|
||
} finally {
|
||
setOpening(false)
|
||
}
|
||
toss.mutate(
|
||
{ body: { authorization_code: code.authorizationCode, referrer: code.referrer } },
|
||
{
|
||
onSuccess: (res) => {
|
||
if (!res.result?.success || !res.access_token) return setError('토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.')
|
||
setTokens(res.access_token, res.refresh_token ?? null)
|
||
if (res.is_new) track('sign_up', { method: 'toss' })
|
||
else track('login', { method: 'toss' })
|
||
onLoggedIn()
|
||
},
|
||
onError: () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.'),
|
||
},
|
||
)
|
||
}
|
||
|
||
return (
|
||
<Body className="flex flex-col gap-2.5">
|
||
<h3 className="m-0 text-center font-jua text-xl font-normal">날씨각 로그인</h3>
|
||
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">로그인하면 동네 이야기를 쓰고 내 각을 저장할 수 있어요</p>
|
||
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
|
||
{error}
|
||
</p>
|
||
<button type="button" onClick={start} 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={['토스로 로그인', '로그인 중…']} at={pending ? 1 : 0} />
|
||
</button>
|
||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
|
||
나중에 할게요
|
||
</button>
|
||
</Body>
|
||
)
|
||
}
|
||
|
||
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃·탈퇴 ---------- */
|
||
/** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */
|
||
function Withdraw({ onDone }: { onDone: () => void }) {
|
||
const withdraw = useMutation(withdrawMutation())
|
||
const [asking, setAsking] = useState(false)
|
||
const [failed, setFailed] = useState(false)
|
||
if (!asking)
|
||
return (
|
||
<button type="button" onClick={() => setAsking(true)} className="cursor-pointer self-center p-1 text-[13px] font-semibold text-(--ink3)">
|
||
탈퇴하기
|
||
</button>
|
||
)
|
||
const run = () => {
|
||
setFailed(false)
|
||
withdraw.mutate(
|
||
{},
|
||
{
|
||
onSuccess: (res) => {
|
||
if (!res.result?.success) return setFailed(true)
|
||
clearTokens()
|
||
onDone()
|
||
},
|
||
onError: () => setFailed(true),
|
||
},
|
||
)
|
||
}
|
||
return (
|
||
<div className="flex flex-col gap-2.5 rounded-[18px] bg-[#fff1f3] p-3.5" role="alert">
|
||
<p className="m-0 text-center text-sm font-bold text-(--ink)">
|
||
탈퇴하면 계정과 남긴 댓글·좋아요가
|
||
<br />
|
||
모두 지워져요. 되돌릴 수 없어요.
|
||
</p>
|
||
<div className="flex gap-2">
|
||
<button type="button" onClick={() => setAsking(false)} disabled={withdraw.isPending} className="flex-1 cursor-pointer rounded-[14px] bg-white p-3 text-sm font-extrabold text-(--ink)">
|
||
그만둘게요
|
||
</button>
|
||
<button type="button" onClick={run} disabled={withdraw.isPending} className="flex-1 cursor-pointer rounded-[14px] bg-(--heart) p-3 text-sm font-extrabold text-white disabled:opacity-60">
|
||
탈퇴할게요
|
||
</button>
|
||
</div>
|
||
{failed && <p className="m-0 text-center text-[13px] font-bold text-(--heart)">탈퇴하지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/** 차단한 사람: 있을 때만 보이고, 풀면 그 사람 댓글이 다시 보인다 */
|
||
function Blocked() {
|
||
const queryClient = useQueryClient()
|
||
const list = useQuery(listBlockedOptions())
|
||
const unblock = useMutation(unblockMutation())
|
||
const [failed, setFailed] = useState(false)
|
||
const users = list.data?.users ?? []
|
||
if (!users.length) return null
|
||
const release = (user_id: string) => {
|
||
setFailed(false)
|
||
unblock.mutate(
|
||
{ path: { user_id } },
|
||
{
|
||
onSuccess: (res) => {
|
||
if (!res.result?.success) return setFailed(true)
|
||
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() })
|
||
queryClient.invalidateQueries({ predicate: isCommentList })
|
||
},
|
||
onError: () => setFailed(true),
|
||
},
|
||
)
|
||
}
|
||
return (
|
||
<section aria-label="차단한 사람">
|
||
<h4 className="m-0 mb-2 text-sm font-extrabold">차단한 사람</h4>
|
||
<ul className="m-0 flex list-none flex-col gap-2 p-0">
|
||
{users.map((u) => (
|
||
<li key={u.user_id} className="flex items-center gap-2.5">
|
||
<Avatar character={u.character} color={u.color} />
|
||
<span className="flex-1 text-sm font-bold">{u.nickname}</span>
|
||
<button type="button" onClick={() => release(u.user_id)} disabled={unblock.isPending} className="cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50">
|
||
풀기
|
||
</button>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
{failed && <p className="m-0 mt-1.5 text-[13px] font-bold text-(--heart)">잠시 뒤에 다시 해 주세요.</p>}
|
||
</section>
|
||
)
|
||
}
|
||
|
||
function MeSheet({ onDone }: { onDone: () => void }) {
|
||
const install = useInstall()
|
||
const installable = useInstallable()
|
||
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.provider === AuthProvider.TOSS ? '토스로 로그인했어요' : me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
|
||
</div>
|
||
<LevelCard />
|
||
{installable && (
|
||
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
|
||
📲 홈 화면에 추가
|
||
</button>
|
||
)}
|
||
<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>
|
||
<MyTalks />
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
logout()
|
||
onDone()
|
||
}}
|
||
className="cursor-pointer rounded-[14px] bg-[#f3f6fb] p-[13px] text-[15px] font-extrabold text-(--ink)"
|
||
>
|
||
로그아웃
|
||
</button>
|
||
<Blocked />
|
||
<Withdraw onDone={onDone} />
|
||
</Body>
|
||
)
|
||
}
|
||
|
||
/* ---------- 지역 ---------- */
|
||
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const
|
||
|
||
/** 구 코드 → 그 구의 지역 페이지 주소 */
|
||
const pageHref = (code: string) => {
|
||
const p = ownPage(code)
|
||
return p ? `/today/${p.path}` : '/'
|
||
}
|
||
|
||
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}>
|
||
<a
|
||
href={pageHref(r.code)}
|
||
aria-current={r.code === region.code ? 'true' : undefined}
|
||
onClick={(e) => {
|
||
e.preventDefault()
|
||
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>}
|
||
</a>
|
||
</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>
|
||
)
|
||
}
|