feat: 댓글 익명화 + 전 경기 적용
- 이메일/투표 게이트 제거 → 완전 익명 - 세션 단위 발급(sessionStorage 캐싱) — 탭 닫으면/시크릿이면 새 닉
This commit is contained in:
1 parent
8a67094510
commit
b62bedc665
8 files changed
+132
-204
No files matched your search
@@ -4,10 +4,8 @@ import { relativeTime } from "@/lib/format";
|
||||
import {
|
||||
listComments,
|
||||
postComment,
|
||||
deleteComment,
|
||||
getSessionNickname,
|
||||
getDeviceId,
|
||||
getRecentEmails,
|
||||
rememberEmail,
|
||||
ApiError,
|
||||
} from "@/lib/api";
|
||||
import type { Comment } from "@/lib/types";
|
||||
@@ -15,7 +13,10 @@ import type { Comment } from "@/lib/types";
|
||||
const FIRST = 3; // 처음 보여줄 최신 댓글 수
|
||||
const PAGE = 10; // "더보기" 한 번에 더 불러올 수
|
||||
|
||||
// 경기별 한마디(댓글). 최신 3개 + "더보기" 인라인 펼침.
|
||||
// 한 댓글을 식별하는 합성 키 (id 비노출이라 시각+내용으로 dedup/렌더)
|
||||
const keyOf = (c: Comment) => `${c.createdAt}|${c.nickname}|${c.body}`;
|
||||
|
||||
// 경기별 한마디(댓글) — 완전 익명. 최신 3개 + 더보기/접기.
|
||||
export default function Comments({
|
||||
matchId,
|
||||
lang,
|
||||
@@ -28,12 +29,10 @@ export default function Comments({
|
||||
const [total, setTotal] = useState(0);
|
||||
const [cursor, setCursor] = useState(0); // 서버에서 페이징으로 받은 개수
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [expanded, setExpanded] = useState(false); // true=전체 보기 / false=최신 FIRST개만
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const [body, setBody] = useState("");
|
||||
// 투표 폼과 동일: 칸은 비우고 입력/포커스 시 datalist 드롭다운으로 최근 이메일 자동완성
|
||||
const [email, setEmail] = useState("");
|
||||
const [recentEmails, setRecentEmails] = useState<string[]>(getRecentEmails);
|
||||
const [nickname, setNickname] = useState(""); // 세션 닉(캐싱)
|
||||
const [posting, setPosting] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
@@ -47,17 +46,18 @@ export default function Comments({
|
||||
setCursor(res.items.length);
|
||||
})
|
||||
.catch(() => {});
|
||||
getSessionNickname(matchId)
|
||||
.then((n) => alive && setNickname(n))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [matchId]);
|
||||
|
||||
// 접힘 상태면 최신 FIRST개만 노출
|
||||
const visible = expanded ? items : items.slice(0, FIRST);
|
||||
const unloaded = Math.max(0, total - items.length); // 아직 서버에서 안 받은 수
|
||||
const hiddenWhenCollapsed = Math.max(0, total - FIRST); // 접힘 시 가려진 전체 수
|
||||
const unloaded = Math.max(0, total - items.length);
|
||||
const hiddenWhenCollapsed = Math.max(0, total - FIRST);
|
||||
|
||||
// "더보기": 펼치고, 받아온 게 FIRST개뿐이면 다음 페이지도 가져온다
|
||||
async function showMore() {
|
||||
setExpanded(true);
|
||||
if (items.length <= FIRST && unloaded > 0) await loadMore();
|
||||
@@ -69,8 +69,8 @@ export default function Comments({
|
||||
try {
|
||||
const res = await listComments(matchId, PAGE, cursor);
|
||||
setItems((prev) => {
|
||||
const seen = new Set(prev.map((c) => c.id));
|
||||
return [...prev, ...res.items.filter((c) => !seen.has(c.id))];
|
||||
const seen = new Set(prev.map(keyOf));
|
||||
return [...prev, ...res.items.filter((c) => !seen.has(keyOf(c)))];
|
||||
});
|
||||
setTotal(res.total);
|
||||
setCursor((c) => c + res.items.length);
|
||||
@@ -81,46 +81,22 @@ export default function Comments({
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(id: number) {
|
||||
if (!window.confirm(t.commentDeleteConfirm)) return;
|
||||
try {
|
||||
await deleteComment(matchId, id);
|
||||
setItems((prev) => prev.filter((c) => c.id !== id));
|
||||
setTotal((n) => Math.max(0, n - 1));
|
||||
} catch {
|
||||
setError(t.commentError);
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const text = body.trim();
|
||||
const mail = email.trim();
|
||||
if (posting) return;
|
||||
if (posting || !text) return;
|
||||
setError("");
|
||||
if (!mail) {
|
||||
setError(t.commentNeedEmail);
|
||||
return;
|
||||
}
|
||||
if (!text) return;
|
||||
setPosting(true);
|
||||
try {
|
||||
const created = await postComment(matchId, {
|
||||
deviceId: getDeviceId(),
|
||||
email: mail,
|
||||
nickname,
|
||||
body: text,
|
||||
});
|
||||
rememberEmail(mail);
|
||||
setRecentEmails(getRecentEmails()); // 방금 쓴 이메일을 자동완성 목록에 반영
|
||||
setItems((prev) => [created, ...prev]); // 낙관적: 맨 위에 즉시 표시
|
||||
setTotal((n) => n + 1);
|
||||
setBody("");
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 403)
|
||||
setError(t.commentNeedVote);
|
||||
else if (e instanceof ApiError && e.status === 429)
|
||||
setError(t.commentCooldown);
|
||||
else if (e instanceof ApiError && e.status === 422)
|
||||
setError(t.commentNeedEmail);
|
||||
if (e instanceof ApiError && e.status === 429) setError(t.commentCooldown);
|
||||
else setError(t.commentError);
|
||||
} finally {
|
||||
setPosting(false);
|
||||
@@ -141,22 +117,11 @@ export default function Comments({
|
||||
|
||||
{/* 입력 */}
|
||||
<div className="mt-3 space-y-2">
|
||||
<input
|
||||
type="email"
|
||||
inputMode="email"
|
||||
autoComplete="email"
|
||||
list="tp-comment-email-suggestions"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder={t.commentEmailPh}
|
||||
className="w-full rounded-lg border border-[var(--line-d)] bg-[#0f1217] px-3 py-2.5 text-[14px] text-white outline-none focus:border-[var(--green)]"
|
||||
/>
|
||||
{recentEmails.length > 0 && (
|
||||
<datalist id="tp-comment-email-suggestions">
|
||||
{recentEmails.map((e) => (
|
||||
<option key={e} value={e} />
|
||||
))}
|
||||
</datalist>
|
||||
{nickname && (
|
||||
<p className="text-[12px] font-bold text-white/45">
|
||||
⚽ {t.commentAs}{" "}
|
||||
<span className="text-[var(--green)]">{nickname}</span>
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-end gap-2">
|
||||
<textarea
|
||||
@@ -199,8 +164,8 @@ export default function Comments({
|
||||
expanded ? "max-h-[360px] overflow-y-auto pr-1" : ""
|
||||
}`}
|
||||
>
|
||||
{visible.map((c) => (
|
||||
<li key={c.id} className="py-3 first:pt-0">
|
||||
{visible.map((c, i) => (
|
||||
<li key={`${keyOf(c)}-${i}`} className="py-3 first:pt-0">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-[13px] font-extrabold text-[var(--green)]">
|
||||
{c.nickname}
|
||||
@@ -208,15 +173,6 @@ export default function Comments({
|
||||
<span className="text-[11px] text-white/35">
|
||||
{relativeTime(c.createdAt, lang)}
|
||||
</span>
|
||||
{c.mine && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => remove(c.id)}
|
||||
className="ml-auto text-[11px] font-bold text-white/35 transition hover:text-red-400"
|
||||
>
|
||||
{t.commentDelete}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 whitespace-pre-wrap break-words text-[14px] leading-snug text-white/90">
|
||||
{c.body}
|
||||
|
||||
+21
-21
@@ -73,29 +73,20 @@ export function getLeaderboard(): Promise<Leaderboard> {
|
||||
return http<Leaderboard>(`/leaderboard`);
|
||||
}
|
||||
|
||||
// ── 댓글(경기별 한마디) ──
|
||||
// 내 이메일(localStorage 최근 이메일) 목록을 함께 보내 mine 플래그/삭제 권한 판정에 사용
|
||||
function emailQuery(emails: string[]): string {
|
||||
return emails
|
||||
.filter(Boolean)
|
||||
.map((e) => `&email=${encodeURIComponent(e)}`)
|
||||
.join("");
|
||||
}
|
||||
|
||||
// ── 댓글(경기별 한마디) — 완전 익명 ──
|
||||
export function listComments(
|
||||
matchId: string,
|
||||
limit: number,
|
||||
offset: number,
|
||||
): Promise<CommentList> {
|
||||
const q = emailQuery(getRecentEmails());
|
||||
return http<CommentList>(
|
||||
`/matches/${matchId}/comments?limit=${limit}&offset=${offset}${q}`,
|
||||
`/matches/${matchId}/comments?limit=${limit}&offset=${offset}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function postComment(
|
||||
matchId: string,
|
||||
body: { deviceId: string; email: string; body: string },
|
||||
body: { deviceId: string; nickname: string; body: string },
|
||||
): Promise<Comment> {
|
||||
return http<Comment>(`/matches/${matchId}/comments`, {
|
||||
method: "POST",
|
||||
@@ -103,16 +94,25 @@ export function postComment(
|
||||
});
|
||||
}
|
||||
|
||||
// 본인 댓글 삭제 — 내 이메일과 작성 이메일이 같으면 어느 기기에서든 삭제 가능
|
||||
export function deleteComment(
|
||||
matchId: string,
|
||||
commentId: number,
|
||||
): Promise<{ ok: boolean }> {
|
||||
const q = emailQuery(getRecentEmails());
|
||||
return http<{ ok: boolean }>(
|
||||
`/matches/${matchId}/comments/${commentId}?${q.replace(/^&/, "")}`,
|
||||
{ method: "DELETE" },
|
||||
// ── 세션 닉네임: 세션당 한 번 발급받아 sessionStorage 에 캐싱 ──
|
||||
// 탭/창을 닫으면 비워지고(껐다 켜면 새 닉), 시크릿창은 별도 저장소라 새로 발급됨.
|
||||
const SESSION_NICK_KEY = "tp_session_nick";
|
||||
export async function getSessionNickname(matchId: string): Promise<string> {
|
||||
try {
|
||||
const cached = sessionStorage.getItem(SESSION_NICK_KEY);
|
||||
if (cached) return cached;
|
||||
} catch {
|
||||
/* sessionStorage 불가 환경은 매번 발급 */
|
||||
}
|
||||
const { nickname } = await http<{ nickname: string }>(
|
||||
`/matches/${matchId}/comments/nickname`,
|
||||
);
|
||||
try {
|
||||
sessionStorage.setItem(SESSION_NICK_KEY, nickname);
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
return nickname;
|
||||
}
|
||||
|
||||
// 방문 기록 (하루 1기기 1회 집계). 실패는 무시(fire-and-forget).
|
||||
|
||||
@@ -102,15 +102,11 @@ type Dict = {
|
||||
commentsTitle: string;
|
||||
commentsCount: (n: number) => string;
|
||||
commentPh: string;
|
||||
commentEmailPh: string;
|
||||
commentAs: string;
|
||||
commentSubmit: string;
|
||||
commentMore: string;
|
||||
commentCollapse: string;
|
||||
commentDelete: string;
|
||||
commentDeleteConfirm: string;
|
||||
commentEmpty: string;
|
||||
commentNeedEmail: string;
|
||||
commentNeedVote: string;
|
||||
commentCooldown: string;
|
||||
commentError: string;
|
||||
adLabel: string;
|
||||
@@ -188,15 +184,11 @@ export const DICT: Record<Lang, Dict> = {
|
||||
commentsTitle: "한마디",
|
||||
commentsCount: (n) => `총 ${n}개`,
|
||||
commentPh: "응원 한마디 남기기...",
|
||||
commentEmailPh: "이메일",
|
||||
commentAs: "이번 닉네임",
|
||||
commentSubmit: "등록",
|
||||
commentMore: "댓글 더보기",
|
||||
commentCollapse: "접기",
|
||||
commentDelete: "삭제",
|
||||
commentDeleteConfirm: "이 댓글을 삭제할까요?",
|
||||
commentEmpty: "첫 한마디를 남겨보세요!",
|
||||
commentNeedEmail: "이메일을 입력해주세요.",
|
||||
commentNeedVote: "이 경기에 투표한 후 댓글을 쓸 수 있어요.",
|
||||
commentCooldown: "잠시 후 다시 시도해주세요.",
|
||||
commentError: "등록에 실패했습니다. 잠시 후 다시 시도해주세요.",
|
||||
adLabel: "광고",
|
||||
@@ -272,15 +264,11 @@ export const DICT: Record<Lang, Dict> = {
|
||||
commentsTitle: "Comments",
|
||||
commentsCount: (n) => `${n} total`,
|
||||
commentPh: "Leave a comment...",
|
||||
commentEmailPh: "Email (shown as masked nickname)",
|
||||
commentAs: "Your name",
|
||||
commentSubmit: "Post",
|
||||
commentMore: "Show more",
|
||||
commentCollapse: "Collapse",
|
||||
commentDelete: "Delete",
|
||||
commentDeleteConfirm: "Delete this comment?",
|
||||
commentEmpty: "Be the first to comment!",
|
||||
commentNeedEmail: "Please enter your email.",
|
||||
commentNeedVote: "Vote on this match first to leave a comment.",
|
||||
commentCooldown: "Please wait a moment before posting again.",
|
||||
commentError: "Failed to post. Please try again shortly.",
|
||||
adLabel: "AD",
|
||||
|
||||
@@ -76,11 +76,9 @@ export interface Leaderboard {
|
||||
}
|
||||
|
||||
export interface Comment {
|
||||
id: number;
|
||||
nickname: string; // 마스킹된 이메일 (ab***@gmail.com)
|
||||
nickname: string; // 축구 코믹 한국어 5글자 (서버가 기기 해시로 자동 배정)
|
||||
body: string;
|
||||
createdAt: string;
|
||||
mine: boolean; // 내(이메일) 댓글이면 true → 삭제 버튼 노출
|
||||
}
|
||||
|
||||
export interface CommentList {
|
||||
|
||||
@@ -10,9 +10,6 @@ import { useLang } from "@/lib/useLang";
|
||||
import { getMatch, matchUrl, ApiError } from "@/lib/api";
|
||||
import type { Match } from "@/lib/types";
|
||||
|
||||
// 댓글(한마디)을 노출할 경기 — 한국 vs 멕시코 (A조 2차전)
|
||||
const COMMENTS_MATCH_ID = "A_MEX_KOR_20260619";
|
||||
|
||||
// L2. 경기 상세(대결) 페이지
|
||||
export default function MatchDetail() {
|
||||
const { matchId = "" } = useParams();
|
||||
@@ -102,10 +99,8 @@ export default function MatchDetail() {
|
||||
lang={lang}
|
||||
/>
|
||||
|
||||
{/* 한국–멕시코 경기에만 한마디(댓글) 노출 */}
|
||||
{match.matchId === COMMENTS_MATCH_ID && (
|
||||
<Comments matchId={match.matchId} lang={lang} />
|
||||
)}
|
||||
{/* 한마디(댓글) — 전 경기 노출 (경기 상태 무관) */}
|
||||
<Comments matchId={match.matchId} lang={lang} />
|
||||
|
||||
{/* 하단 CTA — 전체 일정으로(다른 경기 투표). ADO2 버튼과 동일 사양(퍼플 #A65EFF) */}
|
||||
<Link
|
||||
|
||||
Reference in new issue
Block a user