feat: 동네 이야기 — 로그인하면 100자 글 쓰기(쓸 때 동네 날씨가 붙음, 전국에 보임), 좋아요·신고 3건 자동 숨김·이 사람 글 안 보기·내 글 지우기, 링크·전화번호 막기와 하루 5개 제한
This commit is contained in:
1 parent
a8a126f6a5
commit
798286d975
18 files changed
+1356
-6
No files matched your search
@@ -0,0 +1,256 @@
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import {
|
||||
addTalkMutation,
|
||||
blockTalkAuthorMutation,
|
||||
deleteTalkMutation,
|
||||
likeTalkMutation,
|
||||
listTalksInfiniteOptions,
|
||||
listTalksOptions,
|
||||
reportTalkMutation,
|
||||
unlikeTalkMutation,
|
||||
} from '../api/client/@tanstack/react-query.gen'
|
||||
import { TalkReport, type TalkData } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, kst, loadOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { Avatar, Sec, StateBox, TAP44 } from './ui'
|
||||
|
||||
const BODY_MAX = 100
|
||||
const PREVIEW = 3
|
||||
|
||||
// 서버 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({ queryKey: [{ _id: 'listTalks' }] })
|
||||
}
|
||||
|
||||
function Composer() {
|
||||
const { region } = useRegion()
|
||||
const { loggedIn, me } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const refresh = useRefreshTalks()
|
||||
const add = useMutation(addTalkMutation())
|
||||
const [text, setText] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const body = text.trim()
|
||||
if (!body || add.isPending) return
|
||||
setError(null)
|
||||
add.mutate(
|
||||
{ body: { region_code: region.code, body } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
|
||||
setText('')
|
||||
refresh()
|
||||
},
|
||||
onError: () => 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)}
|
||||
onFocus={() => !loggedIn && open({ type: 'login' })}
|
||||
readOnly={add.isPending}
|
||||
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]"
|
||||
/>
|
||||
<div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)">
|
||||
<span>{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span>
|
||||
<span className="ml-auto tabular-nums">
|
||||
{text.length}/{BODY_MAX}
|
||||
</span>
|
||||
<button type="submit" disabled={add.isPending || (loggedIn && !text.trim())} className="cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white disabled:opacity-40">
|
||||
{add.isPending ? '올리는 중…' : '올리기'}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="mt-1 mb-0 text-xs font-bold text-(--heart)" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function TalkRow({ t }: { t: TalkData }) {
|
||||
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 (!loggedIn) return open({ type: 'login' })
|
||||
if (like.isPending || unlike.isPending) return
|
||||
const next = !liked
|
||||
setLiked(next)
|
||||
setCount((n) => n + (next ? 1 : -1))
|
||||
;(next ? like : unlike).mutate(
|
||||
{ path: { 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' }))
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 border-b border-(--line) py-2.5 last:border-b-0">
|
||||
<Avatar character={t.character} color={t.color} mood={t.mood} />
|
||||
<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.region_name, slotWord(t.created_at), t.weather].filter(Boolean).join(' · ')}
|
||||
</small>
|
||||
<p className="m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
|
||||
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
|
||||
{ago(t.created_at)} · 좋아요 {count}개 ·{' '}
|
||||
<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)} 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 pt-1', TAP44)}>
|
||||
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 오늘 탭의 동네 이야기: 쓰기 칸과 최근 글 몇 개 */
|
||||
export function TalkBand() {
|
||||
const { open } = useSheet()
|
||||
const q = useQuery(listTalksOptions())
|
||||
const talks = q.data?.talks ?? []
|
||||
const load = loadOf(q)
|
||||
return (
|
||||
<section aria-label="동네 이야기">
|
||||
<Sec title="동네 이야기" sub="전국 사람들이 쓰는 지금 날씨 이야기" />
|
||||
<Composer />
|
||||
<div className="relative mx-3 mt-2 min-h-[60px] rounded-[22px] bg-white px-3 py-1 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
{talks.length ? (
|
||||
talks.slice(0, PREVIEW).map((t) => <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />)
|
||||
) : (
|
||||
<StateBox load={load} onRetry={() => q.refetch()} empty="아직 글이 없어요. 첫 이야기를 남겨 보세요." className="inset-0" />
|
||||
)}
|
||||
{talks.length > PREVIEW && (
|
||||
<button type="button" onClick={() => open({ type: 'talks' })} className="w-full cursor-pointer border-t border-(--line) py-2.5 text-center text-sm font-bold text-(--ink2)">
|
||||
이야기 더 보기
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 동네 이야기 전체 (아래로 더 받기) */
|
||||
export function TalkSheet() {
|
||||
const list = useInfiniteQuery({
|
||||
...listTalksInfiniteOptions(),
|
||||
initialPageParam: {},
|
||||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||||
})
|
||||
const talks = list.data?.pages.flatMap((p) => p.talks ?? []) ?? []
|
||||
return (
|
||||
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-1.5 pb-[18px]">
|
||||
{talks.map((t) => (
|
||||
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
|
||||
))}
|
||||
{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>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user