Files
o2o-weather/frontend/src/b/talk.tsx
T
minaChoi 4fec164364 feat: 기념일 꾸밈 — 할로윈·빼빼로데이·크리스마스·추석 기간에만 이야기 주제와 구름 합치기 그림이 바뀜
frontend/src/b/holiday.ts 한 곳에 기간·주제·배경·게임 그림. ?holiday=<key> 로 미리 보기.
GA: game_start theme 추가, talk_post topic 6~9.
2026-10-30 09:15:53 +09:00

453 lines
20 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 { useMutation, useQueryClient } from '@tanstack/react-query'
import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'
import {
addTalkMutation,
blockTalkAuthorMutation,
deleteTalkMutation,
likeTalkMutation,
reportTalkMutation,
unlikeTalkMutation,
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { uploadTalkImage } from '@nalssigak/shared/api/client/sdk.gen'
import { TalkReport, TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen'
import { API_BASE_URL } from '../api/setup'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { kst } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext'
import { holidayByTopic } from './holiday'
import { openTopics, topicName, useMyTalks } from './talkState'
import { useSheet } from './sheetContext'
import { CameraIcon, CommentIcon, HeartIcon, SendIcon } from './svg'
import { Avatar, TAP44 } from './ui'
import { track } from '../lib/analytics'
const BODY_MAX = 100
const PHOTO_MAX = 10 * 1024 * 1024
// 서버 ErrorType 이름 → 안내
const WRITE_ERRORS: Record<string, string> = {
LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.',
DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.',
INVALID_INPUT: '100자 안으로 써 주세요.',
}
const REASONS = [
[TalkReport.ABUSE, '욕설·비하'],
[TalkReport.SPAM, '광고·도배'],
[TalkReport.PRIVACY, '개인정보 노출'],
[TalkReport.ETC, '기타'],
] as const
/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */
function slotWord(iso: string) {
const h = kst(iso).h
return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤'
}
function useRefreshTalks() {
const queryClient = useQueryClient()
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') })
}
function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
const { region } = useRegion()
const { loggedIn, me } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
const add = useMutation(addTalkMutation())
const [text, setText] = useState('')
const [topic, setTopic] = useState<TalkTopic>(TalkTopic.LOCAL)
const [error, setError] = useState<string | null>(null)
const [photo, setPhoto] = useState<{ file: File; src: string } | null>(null)
const [uploading, setUploading] = useState(false)
const fileRef = useRef<HTMLInputElement>(null)
const busy = add.isPending || uploading
useEffect(() => {
if (!photo) return
return () => URL.revokeObjectURL(photo.src)
}, [photo])
const pick = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
e.target.value = ''
if (!file) return
if (file.size > PHOTO_MAX) return setError('사진은 10MB까지 올릴 수 있어요.')
setError(null)
setPhoto({ file, src: URL.createObjectURL(file) })
}
// 사진이 있으면 먼저 올려 주소를 받고, 그 주소를 글에 붙인다
const upload = async (): Promise<string | undefined> => {
if (!photo) return undefined
setUploading(true)
try {
const { data } = await uploadTalkImage({ body: { file: photo.file } })
if (!data.result?.success || !data.image) throw new Error(data.result?.desc ?? 'upload')
return data.image
} finally {
setUploading(false)
}
}
const submit = (e: FormEvent) => {
e.preventDefault()
if (!loggedIn) return open({ type: 'login' })
const body = text.trim()
if (!body || busy) return
setError(null)
upload().then(
(image) =>
add.mutate(
{ body: { region_code: region.code, body, image, topic } },
{
onSuccess: (res) => {
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
track('talk_post', { topic, with_image: !!image })
setText('')
setPhoto(null)
setTopic(TalkTopic.LOCAL)
refresh()
if (res.talk) onDone?.(res.talk)
},
onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
},
),
(e: unknown) => {
console.error('[talk] photo upload', e)
setError('사진을 올리지 못했어요. 사진 파일인지 확인해 주세요.')
},
)
}
return (
<form onSubmit={submit} className="mx-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
// 로그인 전엔 읽기 전용이라 눌러도 키보드가 안 올라온다 (키보드가 떴다 내려가며 로그인 창이 버벅이던 것). 누르거나 Enter 면 로그인 창
onClick={(e) => {
if (loggedIn) return
// 창이 닫힐 때 포커스가 이 칸으로 돌아와 테두리가 번쩍이지 않게
e.currentTarget.blur()
open({ type: 'login' })
}}
onKeyDown={(e) => {
if (loggedIn || (e.key !== 'Enter' && e.key !== ' ')) return
e.preventDefault()
open({ type: 'login' })
}}
readOnly={busy || !loggedIn}
maxLength={BODY_MAX}
rows={2}
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
aria-label="동네 이야기 쓰기"
className="w-full resize-none rounded-2xl bg-[#f3f6fb] px-3 py-2.5 text-[14.5px]"
/>
{photo && (
<div className="relative mt-2 w-[96px]">
<img src={photo.src} alt="올릴 사진" className="aspect-[4/5] w-full rounded-xl object-cover" />
<button type="button" onClick={() => setPhoto(null)} aria-label="사진 빼기" className="absolute -top-1.5 -right-1.5 grid size-6 cursor-pointer place-items-center rounded-full bg-(--ink) text-[13px] font-extrabold text-white">
×
</button>
</div>
)}
<div className="mt-2 flex flex-wrap gap-1.5" role="radiogroup" aria-label="글 주제">
{openTopics().map(([k, label]) => (
<button
key={k}
type="button"
role="radio"
aria-checked={topic === k}
onClick={() => setTopic(k)}
className={cx('cursor-pointer rounded-full px-2.5 py-1 text-[12.5px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-[#f3f6fb] text-(--ink2)')}
>
{label}
</button>
))}
</div>
<input ref={fileRef} type="file" accept="image/*" onChange={pick} hidden />
<div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)">
{/* 주제 칩과 헷갈리지 않게 글자 대신 카메라 아이콘 */}
<button type="button" onClick={() => (loggedIn ? fileRef.current?.click() : open({ type: 'login' }))} disabled={busy} aria-label="사진 붙이기" className={cx('relative grid size-8 shrink-0 cursor-pointer place-items-center rounded-full bg-[#eef4fc] text-(--ink2) disabled:opacity-40', TAP44)}>
<CameraIcon className="size-[18px]" />
</button>
<span className="min-w-0 truncate">{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span>
<span className="ml-auto tabular-nums">
{text.length}/{BODY_MAX}
</span>
<button type="submit" disabled={busy || (loggedIn && !text.trim())} className="shrink-0 cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white disabled:opacity-40">
{busy ? '올리는 중…' : '올리기'}
</button>
</div>
{error && (
<p className="mt-1 mb-0 text-xs font-bold text-(--heart)" role="alert">
{error}
</p>
)}
</form>
)
}
type Menu = 'closed' | 'open' | 'confirm' | 'report' | 'done'
const talkMeta = (t: TalkData) => [t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ')
const talkImage = (t: TalkData) => (t.image?.startsWith('/v1/') ? API_BASE_URL + t.image : (t.image ?? undefined))
/** 좋아요: 화면을 먼저 바꾸고, 실패하면 되돌린다 */
function useTalkLike(t: TalkData) {
const [liked, setLiked] = useState(t.liked)
const [count, setCount] = useState(t.like_count)
const like = useMutation(likeTalkMutation())
const unlike = useMutation(unlikeTalkMutation())
const toggle = () => {
if (like.isPending || unlike.isPending) return
const next = !liked
setLiked(next)
setCount((n) => n + (next ? 1 : -1))
;(next ? like : unlike).mutate(
{ path: { talk_id: t.talk_id } },
{
onSuccess: (res) => {
if (res.result?.success && res.like_count != null) {
if (next) track('like', { content_type: 'talk', item_id: t.talk_id })
return setCount(res.like_count)
}
setLiked(!next)
setCount(t.like_count)
},
onError: () => {
setLiked(!next)
setCount(t.like_count)
},
},
)
}
return { liked, count, toggle }
}
/** 글 메뉴(⋯)를 눌렀을 때 나오는 버튼 줄: 내 글은 지우기, 남의 글은 안 보기·신고 */
function TalkMenu({ t, menu, setMenu, onGone, className }: { t: TalkData; menu: Menu; setMenu: (m: Menu) => void; onGone?: () => void; className?: string }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
const remove = useMutation(deleteTalkMutation())
const report = useMutation(reportTalkMutation())
const block = useMutation(blockTalkAuthorMutation())
const [failed, setFailed] = useState(false)
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
const after = (done?: () => void) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true)
done?.()
setMenu('done')
refresh()
},
onError: () => setFailed(true),
})
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }))
return (
<div className={cx('flex flex-wrap gap-1.5 text-[12.5px] font-extrabold', className)} role="group" aria-label="글 메뉴">
{menu === 'done' ? (
<span className="text-[#1f9d62]">처리했어요</span>
) : t.mine && menu === 'confirm' ? (
<>
<span className="self-center text-(--ink2)">지울까요?</span>
<button type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, after(() => onGone?.()))} disabled={remove.isPending} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
지우기
</button>
<button type="button" onClick={() => setMenu('closed')} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
취소
</button>
</>
) : t.mine ? (
<button type="button" onClick={() => setMenu('confirm')} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
지우기
</button>
) : menu === 'report' ? (
REASONS.map(([reason, label]) => (
<button key={reason} type="button" onClick={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after(() => track('report', { content_type: 'talk', reason })))} disabled={report.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
{label}
</button>
))
) : (
<>
<button type="button" onClick={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after(() => track('block', { content_type: 'talk' }))))} disabled={block.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
이 사람 글 안 보기
</button>
<button type="button" onClick={() => guard(() => setMenu('report'))} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
신고하기
</button>
</>
)}
{failed && (
<span className="text-(--heart)" role="alert">
못 했어요. 다시 해 주세요
</span>
)}
</div>
)
}
function MenuButton({ menu, setMenu, className }: { menu: Menu; setMenu: (m: Menu) => void; className?: string }) {
return (
<button
type="button"
onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')}
aria-expanded={menu !== 'closed'}
aria-label="글 메뉴"
className={cx('relative cursor-pointer text-[15px] leading-none font-extrabold tracking-[1px] text-(--ink3)', TAP44, className)}
>
⋯
</button>
)
}
const MINE_BADGE = 'rounded-full bg-[#ffe8dc] px-1.5 py-px text-[11px] font-extrabold text-[#c2471b]'
/** onGone: 내 글을 지웠을 때. 목록을 다시 받아도 빠지지 않는 곳(방금 쓴 글)에서 직접 뺀다 */
function TalkRow({ t, onGone }: { t: TalkData; onGone?: () => void }) {
const { liked, count, toggle } = useTalkLike(t)
const [menu, setMenu] = useState<Menu>('closed')
const src = talkImage(t)
return (
<div className="grid grid-cols-[34px_1fr_auto] items-start gap-2.5 border-b border-(--line) py-2.5 last:border-b-0">
<span className="self-start">
<Avatar character={t.character} color={t.color} mood={t.mood} />
</span>
<div className="min-w-0">
<small className="block text-xs font-bold text-(--ink3)">
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
{t.mine && <span className={cx('mr-1', MINE_BADGE)}>내 글</span>}
{talkMeta(t)}
</small>
<p className="m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
{src && <img src={src} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
{t.ago} · 좋아요 {count}개
</small>
{menu !== 'closed' && <TalkMenu t={t} menu={menu} setMenu={setMenu} onGone={onGone} className="mt-1.5" />}
</div>
{/* 글 메뉴(⋯)는 하트 옆 오른쪽 위에: 아래 줄 끝에 두면 말줄임표처럼 읽힌다 */}
<span className="flex items-start gap-4 self-start">
<MenuButton menu={menu} setMenu={setMenu} className="pt-0.5" />
<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>
</span>
</div>
)
}
// 사진 없는 글을 크게 띄울 때 주제별 바탕
const TOPIC_BG: Partial<Record<TalkTopic, string>> = { [TalkTopic.SKY]: 'peach', [TalkTopic.RAIN]: 'sky', [TalkTopic.FOLIAGE]: 'butter', [TalkTopic.OUTFIT]: 'lilac' }
/** 오늘 피드에 끼우는 사람 글: 운영 포스트와 같은 틀(머리줄·4:5 본문·버튼줄·댓글). 사진이 없으면 글을 4:5 칸에 크게. 두 번 누르면 좋아요 */
export function TalkPost({ t }: { t: TalkData }) {
const { open } = useSheet()
const { liked, count, toggle } = useTalkLike(t)
const [menu, setMenu] = useState<Menu>('closed')
const bodyRef = useRef<HTMLDivElement>(null)
const lastTap = useRef(0)
const src = talkImage(t)
const share = () => {
if (bodyRef.current) open({ type: 'share', share: { title: `${t.nickname}의 글`, slides: [bodyRef.current] } })
}
const comments = () => open({ type: 'comments', talkId: t.talk_id })
const onTap = () => {
const now = Date.now()
if (now - lastTap.current < 320 && !liked) toggle()
lastTap.current = now
}
return (
<article className="mt-3.5 border-y border-(--line) bg-white" aria-label={`${t.nickname}의 글`}>
<div className="flex items-center gap-2.5 px-3 py-2.5">
<Avatar character={t.character} color={t.color} mood={t.mood} />
<span className="min-w-0">
<b className="block text-sm leading-tight font-extrabold">
{t.nickname}
{t.mine && <span className={cx('ml-1 align-middle', MINE_BADGE)}>내 글</span>}
</b>
<small className="block truncate text-xs font-semibold text-(--ink2)">{talkMeta(t)}</small>
</span>
<MenuButton menu={menu} setMenu={setMenu} className="ml-auto" />
</div>
{menu !== 'closed' && <TalkMenu t={t} menu={menu} setMenu={setMenu} className="px-3 pb-2.5" />}
<div ref={bodyRef} onClick={onTap} className={cx('b-day aspect-[4/5] overflow-hidden', !src && `b-bg-${(t.topic && (TOPIC_BG[t.topic] ?? holidayByTopic(t.topic)?.bg)) || 'mint'} grid place-items-center px-7`)}>
{src ? (
<img src={src} alt="" loading="lazy" className="size-full bg-[#eef4fc] object-cover" />
) : (
<p className="m-0 w-full text-center font-jua text-[26px] leading-snug whitespace-pre-wrap [overflow-wrap:anywhere]">{t.body}</p>
)}
</div>
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<HeartIcon className={liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
</button>
<button type="button" onClick={comments} aria-label="댓글 보기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<CommentIcon className="fill-none stroke-(--ink) [stroke-linejoin:round]" />
</button>
<button type="button" onClick={share} aria-label="보내기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
</button>
</div>
<p className="px-3 py-0.5 text-sm font-extrabold">좋아요 {count.toLocaleString()}개</p>
{src && (
<p className="px-3 py-0.5 text-sm break-words whitespace-pre-wrap">
<b className="mr-[5px] font-extrabold">{t.nickname}</b>
{t.body}
</p>
)}
<button type="button" onClick={comments} className="block cursor-pointer px-3 pt-[3px] text-sm font-semibold text-(--ink3)">
{t.comment_count ? `댓글 ${t.comment_count}개 모두 보기` : '첫 댓글 남기기'}
</button>
<p className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-(--ink3)">{t.ago}</p>
</article>
)
}
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 쓴 글은 아래 피드에 다른 사람 글과 같이 섞여 보인다 */
export function FeedComposer() {
return (
<div className="mt-3.5">
<Composer />
</div>
)
}
/** 피드에 끼우는 글 한 장 */
export function TalkCard({ t, onGone }: { t: TalkData; onGone?: () => void }) {
return (
<article className="mx-3 mt-3 rounded-[20px] bg-white px-3 shadow-[inset_0_-4px_0_var(--shade)]" aria-label={`${t.nickname}의 글`}>
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} onGone={onGone} />
</article>
)
}
/** 내 정보 창의 내가 쓴 글 */
export function MyTalks() {
const { talks, loaded, more, loadMore } = useMyTalks()
if (!loaded) return null
return (
<section aria-label="내 글">
<h4 className="m-0 mb-1 text-sm font-extrabold">내 글</h4>
{talks.length ? (
talks.map((t) => <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />)
) : (
<p className="m-0 text-[13px] font-semibold text-(--ink3)">아직 쓴 글이 없어요</p>
)}
{more && (
<button type="button" onClick={() => loadMore()} className="mt-1 w-full cursor-pointer rounded-[14px] bg-[#f3f6fb] py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
더 보기
</button>
)}
</section>
)
}