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 (
{label}
);
}
/** λ¨μ λκΈ: β― β μ κ³ νκΈ°(μ΄μ κ³ λ₯΄κΈ°) / μ΄ μ¬λ μ°¨λ¨νκΈ°(ν λ² λ 묻기). λλλ©΄ λͺ©λ‘μ λ€μ λ°μ κ·Έ λκΈμ΄ λΉ μ§λ€ */
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 (
<>
go(step === 'closed' ? 'menu' : 'closed')} hitSlop={10} accessibilityRole="button" accessibilityState={{ expanded: step !== 'closed' }} accessibilityLabel="λκΈ λ©λ΄" className="px-1">
β―
{step !== 'closed' && (
{step === 'menu' && (
<>
go('report')} />
go('block')} />
>
)}
{step === 'report' &&
REPORT_REASONS.map(([reason, label]) => (
report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('μ κ³ νμ΄μ. νμΈνκ³ μ‘°μΉν κ²μ.'))} />
))}
{step === 'block' && (
<>
{c.nickname}λ λκΈμ λλ μ λ³ΌκΉμ?
block.mutate({ path: { comment_id: c.comment_id } }, finish('μ°¨λ¨νμ΄μ. λ΄ μ 보μμ ν μ μμ΄μ.'))} />
go('closed')} />
>
)}
{failed && (
μ μ λ€μ λ€μ ν΄ μ£ΌμΈμ.
)}
)}
>
);
}
function CommentsSkel() {
return (
{N3.map((i) => (
))}
);
}
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>(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 (
{c.nickname}
{c.official && (
<>
{' λ μ¨κ° '}{' '}
>
)}
{c.body}
{ago(c.created_at)} Β· {likeFailed ? μ’μμλ₯Ό λͺ» νμ΄μ. μ μ λ€μ λ€μ λλ¬ μ£ΌμΈμ : `μ’μμ ${count}κ°`}
{c.mine && (
<>
{' Β· '}
{remove.isPending ? 'μ§μ°λ μ€β¦' : removeFailed ? 'λͺ» μ§μ μ΄μ Β· λ€μ' : 'μ§μ°κΈ°'}
>
)}
{/* λ μ¨κ° μΊλ¦ν° λκΈμ μ΄μ λ¬Έκ΅¬λΌ μ κ³ Β·μ°¨λ¨ λ©λ΄κ° μλ€ */}
{!c.mine && !c.official && }
);
}
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(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 (
<>
{comments.length ? (
<>
{/* λ€μ λ°μ μ’μμ μν(λ‘κ·ΈμΈ λ°λ λ±)κ° νμ λ°μλλλ‘ key μ λ£λλ€ */}
{comments.map((c) => (
))}
{list.hasNextPage && (
list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 disabled:opacity-50">
{list.isFetchingNextPage ? 'λΆλ¬μ€λ μ€β¦' : 'λκΈ λ 보기'}
)}
>
) : loadOf(list) === 'loading' ? (
) : (
list.refetch()} empty="μμ§ λκΈμ΄ μμ΄μ. 첫 λκΈμ λ¨κ²¨ 보μΈμ." hold={} boxClassName="inset-0" />
)}
{askTerms ? (
λκΈμ μ°λ €λ©΄ μ΄μ©μ½κ΄μ λμν΄ μ£ΌμΈμ. μμ€Β·κ΄κ³ Β·κ°μΈμ 보 λ
ΈμΆμ μ¨κ²¨μ§κ³ , κ³μλλ©΄ μ΄μ©μ΄ μ νλΌμ.
void Linking.openURL(`${SITE_URL}/terms.html`)} accessibilityRole="link" className="flex-1 rounded-[12px] bg-card p-2.5">
μ΄μ©μ½κ΄ 보기
λμνκ³ μ°κΈ°
) : (
{EMOJIS.map((e) => (
{
setText((t) => (t + e).slice(0, 60));
inputRef.current?.focus();
}}
>
{e}
))}
)}
{addFailed ? : {notice}}
{add.isPending ? 'μ¬λ¦¬λ μ€β¦' : 'κ²μ'}
>
);
}