363 lines
16 KiB
TypeScript
363 lines
16 KiB
TypeScript
import {
|
|
addCommentMutation,
|
|
agreeTermsMutation,
|
|
blockAuthorMutation,
|
|
deleteCommentMutation,
|
|
getFeedQueryKey,
|
|
likeCommentMutation,
|
|
listBlockedQueryKey,
|
|
listCommentsInfiniteOptions,
|
|
listCommentsInfiniteQueryKey,
|
|
meQueryKey,
|
|
reportCommentMutation,
|
|
unlikeCommentMutation,
|
|
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
import { ReportReason, type CommentData, type ResCommentList } from '@nalssigak/shared/api/client/types.gen';
|
|
import { ago, loadOf } from '@nalssigak/shared/lib';
|
|
import { useInfiniteQuery, useMutation, useQueryClient, type InfiniteData } from '@tanstack/react-query';
|
|
import { useEffect, useRef, useState } from 'react';
|
|
import { Linking, Pressable, TextInput, View } from 'react-native';
|
|
import { Text } from '@/components/text';
|
|
import { useCSSVariable } from 'uniwind';
|
|
|
|
import { Avatar, Skel, StateBox } from '@/components/ui';
|
|
import { useAuth } from '@/lib/auth';
|
|
import { useRegion } from '@/lib/region';
|
|
import { useSheet } from '@/lib/sheet';
|
|
import { SITE_URL } from '@/lib/site';
|
|
|
|
import { Body, ErrorLine, Field, HeartIcon, useSoft } from './parts';
|
|
|
|
const NOT_FOUND = 3001; // 서버 ErrorType.NOT_FOUND
|
|
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍'];
|
|
const N3 = [0, 1, 2];
|
|
const REPORT_REASONS = [
|
|
[ReportReason.ABUSE, '욕설·비하'],
|
|
[ReportReason.AD, '광고'],
|
|
[ReportReason.PRIVACY, '개인정보 노출'],
|
|
[ReportReason.OTHER, '기타'],
|
|
] as const;
|
|
export const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments';
|
|
|
|
function Chip({ label, onPress, disabled, danger }: { label: string; onPress: () => void; disabled?: boolean; danger?: boolean }) {
|
|
const s = useSoft();
|
|
return (
|
|
<Pressable onPress={onPress} disabled={disabled} className={`rounded-[12px] px-3 py-2 disabled:opacity-50 ${danger ? 'bg-heart' : ''}`} style={danger ? undefined : { backgroundColor: s.soft }}>
|
|
<Text className={`text-[13px] font-extrabold ${danger ? 'text-white' : 'text-ink'}`}>{label}</Text>
|
|
</Pressable>
|
|
);
|
|
}
|
|
|
|
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
|
|
function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number; 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) => ({
|
|
onSuccess: (res: { result?: { success?: boolean } }) => {
|
|
if (!res.result?.success) return setFailed(true);
|
|
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', postId } });
|
|
setStep(next);
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<Pressable onPress={() => go(step === 'closed' ? 'menu' : 'closed')} hitSlop={10} accessibilityRole="button" accessibilityState={{ expanded: step !== 'closed' }} accessibilityLabel="댓글 메뉴" className="px-1">
|
|
<Text className="text-sm font-extrabold text-ink3">⋯</Text>
|
|
</Pressable>
|
|
{step !== 'closed' && (
|
|
<View className="mt-2 w-full flex-row flex-wrap items-center gap-1.5" accessibilityLabel="댓글 메뉴">
|
|
{step === 'menu' && (
|
|
<>
|
|
<Chip label="신고하기" onPress={() => go('report')} />
|
|
<Chip label="이 사람 차단하기" onPress={() => go('block')} />
|
|
</>
|
|
)}
|
|
{step === 'report' &&
|
|
REPORT_REASONS.map(([reason, label]) => (
|
|
<Chip key={reason} label={label} disabled={pending} onPress={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.'))} />
|
|
))}
|
|
{step === 'block' && (
|
|
<>
|
|
<Text className="w-full text-[13px] font-bold text-ink">{c.nickname}님 댓글을 더는 안 볼까요?</Text>
|
|
<Chip label="차단하기" danger disabled={pending} onPress={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.'))} />
|
|
<Chip label="취소" disabled={pending} onPress={() => go('closed')} />
|
|
</>
|
|
)}
|
|
{failed && (
|
|
<Text className="w-full text-[13px] font-bold text-heart" accessibilityRole="alert">
|
|
잠시 뒤에 다시 해 주세요.
|
|
</Text>
|
|
)}
|
|
</View>
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
function CommentsSkel() {
|
|
return (
|
|
<View>
|
|
{N3.map((i) => (
|
|
<View key={i} className="flex-row items-start gap-2.5 py-2">
|
|
<View className="size-[34px] rounded-full bg-skel" />
|
|
<View className="flex-1 gap-1.5">
|
|
<Skel className="w-3/4" />
|
|
<Skel className="w-24" />
|
|
</View>
|
|
</View>
|
|
))}
|
|
</View>
|
|
);
|
|
}
|
|
|
|
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
|
|
const { region } = useRegion();
|
|
const { loggedIn } = useAuth();
|
|
const { open } = useSheet();
|
|
const queryClient = useQueryClient();
|
|
const [heart, ink3] = useCSSVariable(['--color-heart', '--color-ink3']).map(String);
|
|
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 (!loggedIn) return open({ type: 'login' });
|
|
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);
|
|
return;
|
|
}
|
|
revert();
|
|
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
|
|
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) });
|
|
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 = listCommentsInfiniteQueryKey({ path: { post_id: postId } });
|
|
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 (
|
|
<View className={`flex-row items-start gap-2.5 py-2 ${remove.isPending ? 'opacity-50' : ''}`}>
|
|
<Avatar character={c.character} color={c.color} mood={c.mood} />
|
|
<View className="flex-1">
|
|
<Text className="text-sm text-ink">
|
|
<Text className="font-extrabold">{c.nickname} </Text>
|
|
{c.official && (
|
|
<>
|
|
<Text className="bg-orange text-[10.5px] font-extrabold text-white">{' 날씨각 '}</Text>{' '}
|
|
</>
|
|
)}
|
|
{c.body}
|
|
</Text>
|
|
<View className="mt-0.5 flex-row flex-wrap items-center">
|
|
<Text className="text-xs font-bold text-ink3">
|
|
{ago(c.created_at)} · {likeFailed ? <Text className="text-heart">좋아요를 못 했어요. 잠시 뒤에 다시 눌러 주세요</Text> : `좋아요 ${count}개`}
|
|
{c.mine && (
|
|
<>
|
|
{' · '}
|
|
<Text onPress={remove.isPending ? undefined : del} className={removeFailed && !remove.isPending ? 'text-heart' : 'text-ink3'}>
|
|
{remove.isPending ? '지우는 중…' : removeFailed ? '못 지웠어요 · 다시' : '지우기'}
|
|
</Text>
|
|
</>
|
|
)}
|
|
</Text>
|
|
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
|
|
{!c.mine && !c.official && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
|
|
</View>
|
|
</View>
|
|
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="댓글 좋아요" className="pt-1">
|
|
<HeartIcon size={16} fill={liked ? heart : 'none'} stroke={liked ? heart : ink3} />
|
|
</Pressable>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
export function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
|
const { region } = useRegion();
|
|
const { open } = useSheet();
|
|
const { loggedIn, me } = useAuth();
|
|
const queryClient = useQueryClient();
|
|
const list = useInfiniteQuery({
|
|
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
|
|
initialPageParam: { path: { post_id: postId } },
|
|
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
|
});
|
|
const add = useMutation(addCommentMutation());
|
|
const agree = useMutation(agreeTermsMutation());
|
|
const s = useSoft();
|
|
const [addFailed, setAddFailed] = useState(false);
|
|
const [askTerms, setAskTerms] = useState(false);
|
|
const [notice, setNotice] = useState('');
|
|
const [text, setText] = useState(draft ?? '');
|
|
const inputRef = useRef<TextInput>(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);
|
|
add.mutate(
|
|
{ path: { post_id: postId }, body: { body } },
|
|
{
|
|
onSuccess: (res) => {
|
|
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true);
|
|
setAddFailed(!res.result?.success);
|
|
if (!res.result?.success) return;
|
|
setText('');
|
|
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) });
|
|
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
|
|
},
|
|
onError: () => setAddFailed(true),
|
|
},
|
|
);
|
|
};
|
|
|
|
// 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
|
|
const submit = () => {
|
|
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, 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);
|
|
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} postId={postId} onNotice={setNotice} />
|
|
))}
|
|
{list.hasNextPage && (
|
|
<Pressable onPress={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 disabled:opacity-50">
|
|
<Text className="text-center text-sm font-bold text-ink3">{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}</Text>
|
|
</Pressable>
|
|
)}
|
|
</>
|
|
) : loadOf(list) === 'loading' ? (
|
|
<CommentsSkel />
|
|
) : (
|
|
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} boxClassName="inset-0" />
|
|
)}
|
|
</Body>
|
|
{askTerms ? (
|
|
<View className="mx-3 gap-2 rounded-[16px] p-3" style={{ backgroundColor: s.soft }} accessibilityLabel="이용약관 동의">
|
|
<Text className="text-[13px] font-bold text-ink">댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.</Text>
|
|
<View className="flex-row gap-2">
|
|
<Pressable onPress={() => void Linking.openURL(`${SITE_URL}/terms.html`)} accessibilityRole="link" className="flex-1 rounded-[12px] bg-card p-2.5">
|
|
<Text className="text-center text-[13px] font-extrabold text-ink">이용약관 보기</Text>
|
|
</Pressable>
|
|
<Pressable onPress={agreeAndSend} disabled={agree.isPending || add.isPending} className="flex-1 rounded-[12px] bg-orange p-2.5 disabled:opacity-60">
|
|
<Text className="text-center text-[13px] font-extrabold text-white">동의하고 쓰기</Text>
|
|
</Pressable>
|
|
</View>
|
|
</View>
|
|
) : (
|
|
<View className="flex-row justify-around pt-1" accessibilityLabel="빠른 이모지">
|
|
{EMOJIS.map((e) => (
|
|
<Pressable
|
|
key={e}
|
|
disabled={add.isPending}
|
|
className="disabled:opacity-40"
|
|
onPress={() => {
|
|
setText((t) => (t + e).slice(0, 60));
|
|
inputRef.current?.focus();
|
|
}}
|
|
>
|
|
<Text className="text-[22px]">{e}</Text>
|
|
</Pressable>
|
|
))}
|
|
</View>
|
|
)}
|
|
{addFailed ? <ErrorLine className="h-4 text-xs leading-4" text="댓글을 올리지 못했어요. 다시 해 주세요." /> : <Text className="h-4 text-center text-xs leading-4 font-bold text-ink2">{notice}</Text>}
|
|
<View className="flex-row items-center gap-2.5 border-t border-line px-3 py-2.5">
|
|
<View className="flex-1">
|
|
<Field ref={inputRef} round value={text} onChangeText={setText} editable={!add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} accessibilityLabel="댓글" returnKeyType="send" onSubmitEditing={submit} />
|
|
</View>
|
|
<Pressable onPress={submit} disabled={add.isPending || (loggedIn && !text.trim())} className="disabled:opacity-40">
|
|
<Text className="font-extrabold text-rain">{add.isPending ? '올리는 중…' : '게시'}</Text>
|
|
</Pressable>
|
|
</View>
|
|
</>
|
|
);
|
|
}
|