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 = { 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.LOCAL) const [error, setError] = useState(null) const [photo, setPhoto] = useState<{ file: File; src: string } | null>(null) const [uploading, setUploading] = useState(false) const fileRef = useRef(null) const busy = add.isPending || uploading useEffect(() => { if (!photo) return return () => URL.revokeObjectURL(photo.src) }, [photo]) const pick = (e: ChangeEvent) => { 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 => { 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 (