# Conflicts: # backend/common/enums.py # backend/router/v1/auth/account.py # frontend/.dockerignore # frontend/package-lock.json # frontend/package.json # frontend/public/terms.html # frontend/src/api/client/index.ts # frontend/src/b/BLayout.tsx # frontend/src/b/Sheets.tsx # shared/api/client/@tanstack/react-query.gen.ts # shared/api/client/sdk.gen.ts # shared/api/client/types.gen.ts
401 lines
17 KiB
TypeScript
401 lines
17 KiB
TypeScript
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||
import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'
|
||
import { Link } from 'react-router'
|
||
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 { IS_TOSS } from '../lib/platform'
|
||
import { cx } from '../lib/utils'
|
||
import { useAuth } from './authContext'
|
||
import { ago, kst } from '@nalssigak/shared/lib'
|
||
import { useRegion } from './regionContext'
|
||
import { topicName, TOPICS, useMyTalks } from './talkState'
|
||
import { useSheet } from './sheetContext'
|
||
import { HeartIcon } from './svg'
|
||
import { Avatar, Rail, TAP44 } from './ui'
|
||
|
||
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 GROUP_MIN = 3
|
||
const COMPOSE_ID = 'talk-compose'
|
||
|
||
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', 'talkGroups'].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 ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
|
||
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
|
||
id={COMPOSE_ID}
|
||
value={text}
|
||
onChange={(e) => setText(e.target.value)}
|
||
onFocus={() => !loggedIn && open({ type: 'login' })}
|
||
readOnly={busy}
|
||
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="글 주제">
|
||
{TOPICS.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} className="shrink-0 cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2) disabled:opacity-40">
|
||
사진
|
||
</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>
|
||
)
|
||
}
|
||
|
||
/** onGone: 내 글을 지웠을 때. 목록을 다시 받아도 빠지지 않는 곳(방금 쓴 글)에서 직접 뺀다 */
|
||
function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; compact?: boolean }) {
|
||
const { loggedIn } = useAuth()
|
||
const { open } = useSheet()
|
||
const refresh = useRefreshTalks()
|
||
const [liked, setLiked] = useState(t.liked)
|
||
const [count, setCount] = useState(t.like_count)
|
||
const [menu, setMenu] = useState<'closed' | 'open' | 'report' | 'done'>('closed')
|
||
const like = useMutation(likeTalkMutation())
|
||
const unlike = useMutation(unlikeTalkMutation())
|
||
const remove = useMutation(deleteTalkMutation())
|
||
const report = useMutation(reportTalkMutation())
|
||
const block = useMutation(blockTalkAuthorMutation())
|
||
const [failed, setFailed] = useState(false)
|
||
|
||
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) return setCount(res.like_count)
|
||
setLiked(!next)
|
||
setCount(t.like_count)
|
||
},
|
||
onError: () => {
|
||
setLiked(!next)
|
||
setCount(t.like_count)
|
||
},
|
||
},
|
||
)
|
||
}
|
||
|
||
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
|
||
const after = {
|
||
onSuccess: (res: { result?: { success?: boolean } }) => {
|
||
if (!res.result?.success) return setFailed(true)
|
||
setMenu('done')
|
||
refresh()
|
||
},
|
||
onError: () => setFailed(true),
|
||
}
|
||
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }))
|
||
const src = t.image?.startsWith('/v1/') ? API_BASE_URL + t.image : (t.image ?? undefined)
|
||
|
||
return (
|
||
<div className={cx('grid grid-cols-[34px_1fr_24px] gap-2.5 border-b border-(--line) py-2.5 last:border-b-0', compact ? 'h-full w-full items-stretch' : 'items-start')}>
|
||
<span className="self-start">
|
||
<Avatar character={t.character} color={t.color} mood={t.mood} />
|
||
</span>
|
||
{/* 묶음 카드는 옆 카드 높이에 맞춰 늘어나니, 시간·좋아요 줄을 맨 아래에 붙여 빈 곳이 아래에 몰리지 않게 */}
|
||
<div className={cx('min-w-0', compact && 'flex flex-col')}>
|
||
<small className={cx('block text-xs font-bold text-(--ink3)', compact && 'truncate')}>
|
||
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
|
||
{[t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ')}
|
||
</small>
|
||
{/* 묶음 안 작은 카드는 글이 잘리니, 누르면 창에서 글 전체·큰 사진을 본다 */}
|
||
{compact ? (
|
||
<button type="button" onClick={() => open({ type: 'talk', talk: { ...t, liked, like_count: count } })} aria-label={`${t.nickname}의 글 전체 보기`} className="block w-full cursor-pointer text-left">
|
||
{t.image && <img src={src} alt="" loading="lazy" className="float-right mt-1 ml-2 size-12 rounded-xl bg-[#eef4fc] object-cover" />}
|
||
<p className="m-0 mt-0.5 line-clamp-2 min-h-[2lh] text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
|
||
</button>
|
||
) : (
|
||
<p className="m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
|
||
)}
|
||
{t.image && !compact && <img src={src} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
|
||
<small className={cx('block text-xs font-bold text-(--ink3)', compact ? 'mt-auto pt-1.5' : 'mt-0.5')}>
|
||
{ago(t.created_at)} · 좋아요 {count}개
|
||
{!IS_TOSS && (
|
||
<>
|
||
{' · '}
|
||
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
|
||
{t.mine ? '내 글' : '더보기'}
|
||
</button>
|
||
</>
|
||
)}
|
||
</small>
|
||
{menu !== 'closed' && (
|
||
<div className="mt-1.5 flex flex-wrap gap-1.5 text-[12.5px] font-extrabold" role="group" aria-label="글 메뉴">
|
||
{menu === 'done' ? (
|
||
<span className="text-[#1f9d62]">처리했어요</span>
|
||
) : t.mine ? (
|
||
<button type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, { ...after, onSuccess: (res) => (after.onSuccess(res), res.result?.success && onGone?.()) })} disabled={remove.isPending} 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)} 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))} 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>
|
||
)}
|
||
</div>
|
||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative cursor-pointer self-start pt-1', TAP44)}>
|
||
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||
</button>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
|
||
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 방금 올린 글은 바로 아래에 보인다 (피드 사이 글은 새로 받을 때 섞인다) */
|
||
export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) {
|
||
if (IS_TOSS) return null
|
||
return (
|
||
<div className="mt-3.5">
|
||
<Composer onDone={onPosted} />
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/** 묶음에서 누른 글 하나를 창으로: 글 전체·큰 사진·좋아요·더보기 */
|
||
export function TalkSheet({ talk }: { talk: TalkData }) {
|
||
return (
|
||
<div className="flex-1 overflow-auto overscroll-contain px-4 pb-[18px]">
|
||
<TalkRow t={talk} />
|
||
</div>
|
||
)
|
||
}
|
||
|
||
/** 피드에 끼우는 글 한 장 */
|
||
export function TalkCard({ t, onGone }: { t: TalkData; onGone?: () => void }) {
|
||
return (
|
||
<article className="mt-3.5 border-y border-(--line) bg-white px-3" aria-label={`${t.nickname}의 글`}>
|
||
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} onGone={onGone} />
|
||
</article>
|
||
)
|
||
}
|
||
|
||
/** 오늘 피드의 사람 글 묶음: 옆으로 넘기는 카드, 끝에 그 주제 전체 보기 */
|
||
export function TalkGroup({ title, topic, talks }: { title: string; topic?: number; talks: TalkData[] }) {
|
||
return (
|
||
<section aria-label={title} className="mt-3.5">
|
||
<div className="flex items-end justify-between px-4">
|
||
<h2 className="m-0 font-jua text-[19px] font-normal">{title}</h2>
|
||
<Link to={topic ? `/talk?topic=${topic}` : '/talk'} className="text-[13px] font-bold text-(--ink2)">
|
||
전체 보기
|
||
</Link>
|
||
</div>
|
||
<Rail label={title}>
|
||
{talks.map((t) => (
|
||
<article key={`${t.talk_id}:${t.liked}:${t.like_count}`} className="flex w-[78%] max-w-[320px] rounded-[20px] bg-white px-3 shadow-[inset_0_-4px_0_var(--shade)]" aria-label={`${t.nickname}의 글`}>
|
||
<TalkRow t={t} compact />
|
||
</article>
|
||
))}
|
||
</Rail>
|
||
</section>
|
||
)
|
||
}
|
||
|
||
/** '동네 사람들' 글이 적을 때 묶음 대신: 위 쓰기 칸으로 데려간다 */
|
||
export function FirstTalkCard() {
|
||
const { region } = useRegion()
|
||
const place = region.name.split(' ').at(-1)
|
||
const go = () => {
|
||
const el = document.getElementById(COMPOSE_ID)
|
||
el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||
el?.focus({ preventScroll: true })
|
||
}
|
||
return (
|
||
<button type="button" onClick={go} className="mx-3 mt-3.5 flex w-[calc(100%-1.5rem)] cursor-pointer items-center gap-3 rounded-[22px] bg-white p-3.5 text-left shadow-[inset_0_-5px_0_var(--shade)]">
|
||
<span className="font-jua text-[16.5px] leading-snug">
|
||
지금 {place} 하늘 어때요?
|
||
<small className="block font-sans text-[12.5px] font-semibold text-(--ink2)">첫 이야기를 남겨 주세요</small>
|
||
</span>
|
||
<span className="ml-auto shrink-0 rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">쓰기</span>
|
||
</button>
|
||
)
|
||
}
|
||
|
||
/** '동네 사람들' 자리: 글이 GROUP_MIN 개 이상이면 묶음, 아니면 첫 글 쓰기 */
|
||
export function NearTalks({ talks, loaded }: { talks: TalkData[]; loaded: boolean }) {
|
||
if (!loaded) return null
|
||
if (talks.length >= GROUP_MIN) return <TalkGroup title="동네 사람들" talks={talks} />
|
||
return IS_TOSS ? null : <FirstTalkCard />
|
||
}
|
||
|
||
/** 내 정보 창의 내가 쓴 글 */
|
||
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>
|
||
)
|
||
}
|