feat: 댓글 신고·차단·약관 동의(관리 스크립트 포함), 구글 로그인(서버·웹·안드로이드 앱), 앱 패키지 kr.o2o.nalssigak·versionCode 1000

This commit is contained in:
minaChoi committed 2026-10-26 09:45:00 +09:00
1 parent fbebdcb796
commit 3f3a3ea039
35 files changed
+1723 -115

No files matched your search

+206 -30
View File
@@ -4,6 +4,8 @@ import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/aut
import { SITE_URL } from '../api/setup'
import {
addCommentMutation,
agreeTermsMutation,
blockAuthorMutation,
deleteCommentMutation,
getArticleOptions,
getFeedQueryKey,
@@ -11,20 +13,25 @@ import {
getSeasonWeekOptions,
likeCommentMutation,
listCommentsInfiniteOptions,
listBlockedOptions,
listBlockedQueryKey,
listCommentsInfiniteQueryKey,
listRegionsOptions,
loginMutation,
meQueryKey,
reportCommentMutation,
signupMutation,
unblockMutation,
unlikeCommentMutation,
updateMeMutation,
withdrawMutation,
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
import { ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
import { GoogleButton } from './googleLogin'
import { ARTICLE_CAT } from './lib'
import { useRegion } from './regionContext'
import { useSky } from './skyContext'
@@ -611,8 +618,88 @@ function ShareSheet({ share }: { share: SharePayload }) {
/* ---------- 댓글 ---------- */
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
const REPORT_REASONS = [
[ReportReason.ABUSE, '욕설·비하'],
[ReportReason.AD, '광고'],
[ReportReason.PRIVACY, '개인정보 노출'],
[ReportReason.OTHER, '기타'],
] as const
const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments'
function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
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)
}
const btn = 'cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50'
return (
<>
<button type="button" onClick={() => go(step === 'closed' ? 'menu' : 'closed')} aria-expanded={step !== 'closed'} aria-label="댓글 메뉴" className="ml-1.5 cursor-pointer px-1 font-extrabold text-(--ink3)">
⋯
</button>
{step !== 'closed' && (
<span className="mt-2 flex flex-wrap items-center gap-1.5" role="group" aria-label="댓글 메뉴">
{step === 'menu' && (
<>
<button type="button" className={btn} onClick={() => go('report')}>
신고하기
</button>
<button type="button" className={btn} onClick={() => go('block')}>
이 사람 차단하기
</button>
</>
)}
{step === 'report' &&
REPORT_REASONS.map(([reason, label]) => (
<button key={reason} type="button" disabled={pending} className={btn} onClick={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.'))}>
{label}
</button>
))}
{step === 'block' && (
<>
<span className="w-full text-[13px] font-bold text-(--ink)">{c.nickname}님 댓글을 더는 안 볼까요?</span>
<button type="button" disabled={pending} className={cx(btn, 'bg-(--heart) text-white')} onClick={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.'))}>
차단하기
</button>
<button type="button" disabled={pending} className={btn} onClick={() => go('closed')}>
취소
</button>
</>
)}
{failed && (
<span className="w-full text-[13px] font-bold text-(--heart)" role="alert">
잠시 뒤에 다시 해 주세요.
</span>
)}
</span>
)}
</>
)
}
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
const { region } = useRegion()
const { loggedIn } = useAuth()
const { open } = useSheet()
@@ -697,6 +784,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
</button>
</>
)}
{!c.mine && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
</small>
</div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
@@ -717,14 +805,21 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
const add = useMutation(addCommentMutation())
const agree = useMutation(agreeTermsMutation())
const [addFailed, setAddFailed] = useState(false)
const [askTerms, setAskTerms] = useState(false)
const [notice, setNotice] = useState('')
const [text, setText] = useState(draft ?? '')
const inputRef = useRef<HTMLInputElement>(null)
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
const submit = (e: FormEvent) => {
e.preventDefault()
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } })
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)
@@ -732,6 +827,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
{ 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('')
@@ -743,13 +839,36 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
)
}
// 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
const submit = (e: FormEvent) => {
e.preventDefault()
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} />)}
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} onNotice={setNotice} />)}
{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 ? '불러오는 중…' : '댓글 더 보기'}
@@ -762,24 +881,38 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} className="inset-0" />
)}
</Body>
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
{EMOJIS.map((e) => (
<button
key={e}
type="button"
disabled={add.isPending}
className="cursor-pointer disabled:opacity-40"
onClick={() => {
setText((t) => (t + e).slice(0, 60))
inputRef.current?.focus()
}}
>
{e}
</button>
))}
</div>
<p className="h-4 px-4 text-center text-xs leading-4 font-bold text-(--heart)" role="alert">
{addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'}
{askTerms ? (
<div className="mx-3 flex flex-col gap-2 rounded-[16px] bg-[#f3f6fb] p-3" role="dialog" aria-label="이용약관 동의">
<p className="m-0 text-[13px] font-bold text-(--ink)">댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.</p>
<div className="flex gap-2">
<a href="/terms.html" target="_blank" rel="noopener" className="flex-1 rounded-[12px] bg-white p-2.5 text-center text-[13px] font-extrabold text-(--ink)">
이용약관 보기
</a>
<button type="button" onClick={agreeAndSend} disabled={agree.isPending || add.isPending} className="flex-1 cursor-pointer rounded-[12px] bg-(--orange) p-2.5 text-[13px] font-extrabold text-white disabled:opacity-60">
동의하고 쓰기
</button>
</div>
</div>
) : (
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
{EMOJIS.map((e) => (
<button
key={e}
type="button"
disabled={add.isPending}
className="cursor-pointer disabled:opacity-40"
onClick={() => {
setText((t) => (t + e).slice(0, 60))
inputRef.current?.focus()
}}
>
{e}
</button>
))}
</div>
)}
<p className={cx('h-4 px-4 text-center text-xs leading-4 font-bold', addFailed ? 'text-(--heart)' : 'text-(--ink2)')} role="alert">
{addFailed ? '댓글을 올리지 못했어요. 다시 해 주세요.' : notice}
</p>
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
@@ -809,13 +942,13 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
const signup = useMutation(signupMutation())
const pending = login.isPending || signup.isPending
const done = (res: ResAuth) => {
const done = (res: ResAuth, method: 'id' | 'google' = 'id') => {
if (!res.result?.success || !res.access_token) {
setError(AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.')
setError(method === 'google' ? '구글로 로그인하지 못했어요. 다시 해 주세요.' : (AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.'))
return
}
setTokens(res.access_token, res.refresh_token ?? null)
track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' })
track(method === 'google' ? 'login' : mode === 'login' ? 'login' : 'sign_up', { method })
onLoggedIn()
}
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
@@ -823,8 +956,8 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
const submit = (e: FormEvent) => {
e.preventDefault()
setError('')
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: done, onError: fail })
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: done, onError: fail })
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: (res) => done(res), onError: fail })
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: (res) => done(res), onError: fail })
}
if (me) return <MeSheet onDone={onDone} />
@@ -833,7 +966,8 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
return (
<Body>
<form onSubmit={submit} className="flex flex-col gap-2.5">
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</p>
<p className="text-center text-sm font-semibold text-(--ink2)">글쓰기·댓글은 로그인한 뒤에 할 수 있어요.</p>
<GoogleButton onResult={(res) => done(res, 'google')} onFail={fail} />
<div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입">
{(
[
@@ -909,6 +1043,47 @@ function Withdraw({ onDone }: { onDone: () => void }) {
)
}
/** 차단한 사람: 있을 때만 보이고, 풀면 그 사람 댓글이 다시 보인다 */
function Blocked() {
const queryClient = useQueryClient()
const list = useQuery(listBlockedOptions())
const unblock = useMutation(unblockMutation())
const [failed, setFailed] = useState(false)
const users = list.data?.users ?? []
if (!users.length) return null
const release = (user_id: string) => {
setFailed(false)
unblock.mutate(
{ path: { user_id } },
{
onSuccess: (res) => {
if (!res.result?.success) return setFailed(true)
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() })
queryClient.invalidateQueries({ predicate: isCommentList })
},
onError: () => setFailed(true),
},
)
}
return (
<section aria-label="차단한 사람">
<h4 className="m-0 mb-2 text-sm font-extrabold">차단한 사람</h4>
<ul className="m-0 flex list-none flex-col gap-2 p-0">
{users.map((u) => (
<li key={u.user_id} className="flex items-center gap-2.5">
<Avatar character={u.character} color={u.color} />
<span className="flex-1 text-sm font-bold">{u.nickname}</span>
<button type="button" onClick={() => release(u.user_id)} disabled={unblock.isPending} className="cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50">
풀기
</button>
</li>
))}
</ul>
{failed && <p className="m-0 mt-1.5 text-[13px] font-bold text-(--heart)">잠시 뒤에 다시 해 주세요.</p>}
</section>
)
}
function MeSheet({ onDone }: { onDone: () => void }) {
const { me, logout } = useAuth()
const queryClient = useQueryClient()
@@ -1027,6 +1202,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {
>
로그아웃
</button>
<Blocked />
<Withdraw onDone={onDone} />
</Body>
)
+83
View File
@@ -0,0 +1,83 @@
import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'
type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */
function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id
const login = useMutation(googleLoginMutation())
const box = useRef<HTMLDivElement>(null)
const [broken, setBroken] = useState(false)
const { mutate } = login
// 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다
const cb = useRef({ onResult, onFail })
useEffect(() => {
cb.current = { onResult, onFail }
}, [onResult, onFail])
useEffect(() => {
if (!clientId || !box.current) return
let alive = true
loadGoogle().then(
(g) => {
if (!alive || !box.current) return
g.initialize({
client_id: clientId,
ux_mode: 'popup',
callback: (r) => {
if (!r.credential) return cb.current.onFail()
mutate({ body: { credential: r.credential } }, { onSuccess: (res) => cb.current.onResult(res), onError: () => cb.current.onFail() })
},
})
g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth })
},
(e: unknown) => {
console.error('[google] script', e)
if (alive) setBroken(true)
},
)
return () => {
alive = false
}
}, [clientId, mutate])
if (!clientId) return null
return (
<div className="flex flex-col gap-2">
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} />
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 아이디로 로그인해 주세요.</p>}
<p className="m-0 flex items-center gap-2 text-[12.5px] font-bold text-(--ink3) before:h-px before:flex-1 before:bg-(--line) after:h-px after:flex-1 after:bg-(--line)">또는 아이디로</p>
</div>
)
}
+1 -1
View File
@@ -3,7 +3,7 @@ type Events = {
view_gak: { index_id: number; gak_name: string; score: number; rank: number }
select_content: { content_type: 'article'; item_id: number; category: string }
share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string }
login: { method: 'id' }
login: { method: 'id' | 'google' }
sign_up: { method: 'id' }
region_change: { region_name: string; method: 'list' | 'location' }
}