feat: 앱 동네 이야기 — /talk 주제별 글·내 글, 오늘 피드 쓰기 칸과 포스트 두 장마다 사람 글, 사진 올리기(expo-image-picker, 카메라·마이크 권한 없음), 이야기 댓글·좋아요·신고·안 보기·지우기, 내 정보 내 글. 기념일 목록을 shared로 (GA talk_post·talk_comment·feed_item_view, like·report·block talk)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
skkimandClaude committed 2026-11-04 17:35:23 +09:00
1 parent e40a9a0539
commit c15f045c64
16 files changed
+941 -300

No files matched your search

+84 -10
View File
@@ -1,17 +1,53 @@
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { PostType } from '@nalssigak/shared/api/client/types.gen';
import { kst, loadOf } from '@nalssigak/shared/lib';
import { atSlot, PREVIEW } from '@nalssigak/shared/lib/today';
import { useQuery } from '@tanstack/react-query';
import { Fragment, type ReactNode } from 'react';
import { RefreshControl, ScrollView } from 'react-native';
import { Fragment, useRef, type ReactNode } from 'react';
import { RefreshControl, ScrollView, View, type LayoutRectangle } from 'react-native';
import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card';
import { Composer, TalkPost } from '@/components/talk/talk';
import { GakCard } from '@/components/today/gak-card';
import { Hero } from '@/components/today/hero';
import { SeasonBand } from '@/components/today/rails';
import { StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useRegion } from '@/lib/region';
import { useSky } from '@/lib/sky';
import { useTopicTalks } from '@/lib/talk';
// 사람 글은 포스트 두 장마다 한 장씩 최신순으로 끼운다
const TALK_EVERY = 2;
type Spot = { item: 'talk' | 'event'; position: number; y: number; h: number };
/** 피드에 섞인 사람 글·행사 포스트가 처음 반쯤 보일 때 한 번 GA 로 보낸다 (웹 Seen) */
function useSeen() {
const spots = useRef(new Map<string, Spot>());
const sent = useRef(new Set<string>());
const view = useRef({ y: 0, h: 0 });
const check = () => {
const { y, h } = view.current;
if (!h) return;
for (const [key, s] of spots.current) {
if (sent.current.has(key) || !s.h) continue;
const shown = Math.min(y + h, s.y + s.h) - Math.max(y, s.y);
if (shown < s.h / 2) continue;
sent.current.add(key);
track('feed_item_view', { item_type: s.item, position: s.position });
}
};
const at = (item: Spot['item'], position: number) => (l: LayoutRectangle) => {
spots.current.set(`${item}:${position}`, { item, position, y: l.y, h: l.height });
check();
};
const onScroll = (y: number, h: number) => {
view.current = { y, h };
check();
};
return { at, onScroll };
}
export default function TodayScreen() {
const { region } = useRegion();
@@ -25,15 +61,31 @@ export default function TodayScreen() {
const bands = f?.bands;
const nowAt = f?.hero?.now_at;
const load = loadOf(feed);
const refresh = () => Promise.all([feed.refetch(), today.refetch()]);
const talkList = useTopicTalks();
const talks = talkList.talks;
const talkAt = (i: number) => ((i + 1) % TALK_EVERY === 0 ? talks[(i + 1) / TALK_EVERY - 1] : undefined);
const talkFrom = Math.floor(posts.length / TALK_EVERY);
const eventNo = new Map(posts.filter((p) => p.post_type === PostType.EVENT).map((p, n) => [p.post_id, n + 1]));
const seen = useSeen();
const refresh = () => Promise.all([feed.refetch(), today.refetch(), talkList.refetch()]);
// 웹처럼 9번째 글 뒤에 계절 이야기 띠를 넣고, 글이 모자라면 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [[9, bands?.season?.length ? <SeasonBand news={bands.season} /> : null]];
return (
// 지역마다 새로 그려 넘긴 슬라이드 위치가 남지 않게 한다
<ScrollView key={region.code} contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={feed.isRefetching && !feed.isPlaceholderData} onRefresh={refresh} />} style={{ opacity: feed.isPlaceholderData ? 0.6 : 1 }}>
<ScrollView
key={region.code}
contentContainerClassName="pb-6"
refreshControl={<RefreshControl refreshing={feed.isRefetching && !feed.isPlaceholderData} onRefresh={refresh} />}
style={{ opacity: feed.isPlaceholderData ? 0.6 : 1 }}
keyboardShouldPersistTaps="handled"
scrollEventThrottle={200}
onLayout={(e) => seen.onScroll(0, e.nativeEvent.layout.height)}
onScroll={(e) => seen.onScroll(e.nativeEvent.contentOffset.y, e.nativeEvent.layoutMeasurement.height)}
>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<Composer />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
@@ -62,12 +114,34 @@ export default function TodayScreen() {
boxClassName="inset-x-3 top-3.5"
/>
)}
{posts.map((p, i) => (
<Fragment key={p.post_id}>
<PostCard post={p} />
{bandAt.find(([at]) => at === i + 1)?.[1]}
</Fragment>
))}
{posts.map((p, i) => {
const t = talkAt(i);
const ev = eventNo.get(p.post_id);
return (
<Fragment key={p.post_id}>
{ev ? (
<View onLayout={(e) => seen.at('event', ev)(e.nativeEvent.layout)}>
<PostCard post={p} />
</View>
) : (
<PostCard post={p} />
)}
{bandAt.find(([at]) => at === i + 1)?.[1]}
{t && (
<View onLayout={(e) => seen.at('talk', (i + 1) / TALK_EVERY)(e.nativeEvent.layout)}>
<TalkPost key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
</View>
)}
</Fragment>
);
})}
{/* 포스트가 모자라 끼울 자리가 없던 사람 글은 맨 뒤에 */}
{feed.isSuccess &&
talks.slice(talkFrom).map((t, n) => (
<View key={t.talk_id} onLayout={(e) => seen.at('talk', talkFrom + n + 1)(e.nativeEvent.layout)}>
<TalkPost t={t} />
</View>
))}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
</ScrollView>
);
+71
View File
@@ -0,0 +1,71 @@
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen';
import { router, useLocalSearchParams } from 'expo-router';
import { FlatList, Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { ScreenHeader } from '@/components/screen-header';
import { Composer, TalkCard } from '@/components/talk/talk';
import { Text } from '@/components/text';
import { Sec } from '@/components/ui';
import { useAuth } from '@/lib/auth';
import { useSheet } from '@/lib/sheet';
import { openTopics, TOPICS, useMyTalks, useTopicTalks } from '@/lib/talk';
type Tab = TalkTopic | 'all' | 'mine';
/** 주제별 사람 글: 위 주제 탭(한 줄 가로로 밀기, 끝에 '내 글'), 아래 글 목록. ?topic= · ?mine=1 로 연다 (웹 TalkPage) */
export default function TalkScreen() {
const params = useLocalSearchParams<{ topic?: string; mine?: string }>();
const { loggedIn } = useAuth();
const { open } = useSheet();
const raw = Number(params.topic);
const tab: Tab = params.mine ? 'mine' : TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : 'all';
const topicList = useTopicTalks(tab === 'all' || tab === 'mine' ? undefined : tab);
const mineList = useMyTalks(tab === 'mine' && loggedIn);
const { talks, loaded, more, loadMore } = tab === 'mine' ? mineList : topicList;
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...openTopics(), ['mine', '내 글']];
const go = (k: Tab) => router.setParams(k === 'mine' ? { mine: '1', topic: undefined } : k === 'all' ? { mine: undefined, topic: undefined } : { mine: undefined, topic: String(k) });
const head = (
<View>
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
<View accessibilityRole="tablist" accessibilityLabel="글 주제">
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerClassName="gap-1.5 px-4 pb-1">
{tabs.map(([k, label]) => (
<Pressable key={label} onPress={() => go(k)} accessibilityRole="tab" accessibilityState={{ selected: tab === k }} className={`rounded-full px-3 py-1.5 ${tab === k ? 'bg-ink-btn' : 'bg-card'}`}>
<Text className={`text-[13px] font-extrabold ${tab === k ? 'text-white' : 'text-ink2'}`}>{label}</Text>
</Pressable>
))}
</ScrollView>
</View>
<Composer />
{tab === 'mine' && !loggedIn ? (
<Text className="mx-4 mt-6 text-center text-[14px] font-semibold text-ink3">
로그인하면 내가 쓴 글을 모아 볼 수 있어요.{' '}
<Text onPress={() => open({ type: 'login' })} className="font-extrabold text-orange">
로그인
</Text>
</Text>
) : (
loaded && !talks.length && <Text className="mx-4 mt-6 text-center text-[14px] font-semibold text-ink3">{tab === 'mine' ? '아직 쓴 글이 없어요. 위 칸에서 첫 글을 써 주세요.' : '아직 이 주제 글이 없어요. 위 칸에서 첫 글을 써 주세요.'}</Text>
)}
</View>
);
return (
<View className="flex-1">
<ScreenHeader title="동네 이야기" />
<FlatList
data={talks}
keyExtractor={(t) => `${t.talk_id}:${t.liked}:${t.like_count}`}
renderItem={({ item }) => <TalkCard t={item} />}
ListHeaderComponent={head}
contentContainerClassName="pb-8"
keyboardShouldPersistTaps="handled"
// 목록 끝이 가까워지면 다음 쪽을 받는다 (글이 많아도 버튼 없이 이어서)
onEndReached={() => more && loadMore()}
onEndReachedThreshold={1}
refreshControl={tab !== 'mine' ? <RefreshControl refreshing={topicList.refetching} onRefresh={() => topicList.refetch()} /> : undefined}
/>
</View>
);
}
+10 -1
View File
@@ -1,4 +1,4 @@
import Svg, { Path } from 'react-native-svg';
import Svg, { Circle, Path } from 'react-native-svg';
export const HEART = 'M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z';
@@ -27,3 +27,12 @@ export function SendIcon({ size, color }: P) {
</Svg>
);
}
export function CameraIcon({ size, color }: P) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
<Path d="M4 8.5A1.5 1.5 0 0 1 5.5 7h2.2l1.5-2h5.6l1.5 2h2.2A1.5 1.5 0 0 1 20 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 17.5z" />
<Circle cx={12} cy={13} r={3.5} />
</Svg>
);
}
+31
View File
@@ -0,0 +1,31 @@
import { router } from 'expo-router';
import { Pressable, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg';
import { useCSSVariable } from 'uniwind';
import { Text } from '@/components/text';
import { useSky } from '@/lib/sky';
/** 탭 밖 화면(사주·이야기·게임 등) 머리줄: 뒤로 가기와 제목. 뒤로 갈 곳이 없으면(링크로 바로 열림) 오늘 탭으로 */
export function ScreenHeader({ title, right }: { title: string; right?: React.ReactNode }) {
const { top } = useSafeAreaInsets();
const { kind } = useSky();
const ink = String(useCSSVariable('--color-ink'));
const back = () => (router.canGoBack() ? router.back() : router.replace('/'));
return (
<View style={{ paddingTop: top, backgroundColor: kind === 'night' ? 'rgb(14 20 51 / 0.35)' : 'rgb(255 255 255 / 0.18)' }}>
<View className="h-[54px] flex-row items-center gap-1 px-2">
<Pressable onPress={back} hitSlop={8} accessibilityRole="button" accessibilityLabel="뒤로" className="size-10 items-center justify-center">
<Svg viewBox="0 0 24 24" width={24} height={24} fill="none" stroke={ink} strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round">
<Path d="M15 5l-7 7 7 7" />
</Svg>
</Pressable>
<Text numberOfLines={1} className="flex-1 font-jua text-[21px] text-ink">
{title}
</Text>
{right}
</View>
</View>
);
}
+58 -28
View File
@@ -1,5 +1,6 @@
import {
addCommentMutation,
addTalkCommentMutation,
agreeTermsMutation,
blockAuthorMutation,
deleteCommentMutation,
@@ -8,6 +9,8 @@ import {
listBlockedQueryKey,
listCommentsInfiniteOptions,
listCommentsInfiniteQueryKey,
listTalkCommentsInfiniteOptions,
listTalkCommentsInfiniteQueryKey,
meQueryKey,
reportCommentMutation,
unlikeCommentMutation,
@@ -24,7 +27,7 @@ import { Avatar, Skel, StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
import { useSheet, type CommentTarget } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
import { Body, ErrorLine, Field, HeartIcon, useSoft } from './parts';
@@ -38,7 +41,13 @@ const REPORT_REASONS = [
[ReportReason.PRIVACY, '개인정보 노출'],
[ReportReason.OTHER, '기타'],
] as const;
export const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments';
export const isCommentList = (q: { queryKey: readonly unknown[] }) => ['listComments', 'listTalkComments'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '');
const isTalkList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listTalks';
/** 댓글 목록 캐시 키: 지우기·신고 뒤 다시 받을 때 쓴다 */
function commentListKey(to: CommentTarget) {
return 'talkId' in to ? listTalkCommentsInfiniteQueryKey({ path: { talk_id: to.talkId } }) : listCommentsInfiniteQueryKey({ path: { post_id: to.postId } });
}
function Chip({ label, onPress, disabled, danger }: { label: string; onPress: () => void; disabled?: boolean; danger?: boolean }) {
const s = useSoft();
@@ -50,7 +59,7 @@ function Chip({ label, onPress, disabled, danger }: { label: string; onPress: ()
}
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
function CommentMenu({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
const { loggedIn } = useAuth();
const { open } = useSheet();
const queryClient = useQueryClient();
@@ -73,7 +82,7 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
});
const go = (next: typeof step) => {
setFailed(false);
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', postId } });
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', ...to } });
setStep(next);
};
@@ -128,7 +137,7 @@ function CommentsSkel() {
);
}
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
function CommentRow({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
const { region } = useRegion();
const queryClient = useQueryClient();
const [heart, ink3] = useCSSVariable(['--color-heart', '--color-ink3']).map(String);
@@ -163,7 +172,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
}
revert();
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) });
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: commentListKey(to) });
else setLikeFailed(true);
},
onError: () => {
@@ -182,13 +191,14 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
{
onSuccess: async (res) => {
if (!res.result?.success) return setRemoveFailed(true);
const key = listCommentsInfiniteQueryKey({ path: { post_id: postId } });
const key = commentListKey(to);
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 } }) });
if ('talkId' in to) queryClient.invalidateQueries({ predicate: isTalkList });
else queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
},
onError: () => setRemoveFailed(true),
},
@@ -221,7 +231,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
)}
</Text>
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
{!c.mine && !c.official && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
{!c.mine && !c.official && <CommentMenu c={c} to={to} onNotice={onNotice} />}
</View>
</View>
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="댓글 좋아요" className="pt-1">
@@ -231,16 +241,31 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
);
}
export function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
/** 포스트 댓글, 또는 사람 글 댓글(로그인한 사람만 쓴다) */
export function CommentsSheet({ to, draft }: { to: CommentTarget; draft?: string }) {
const { region } = useRegion();
const { me } = useAuth();
const { open } = useSheet();
const queryClient = useQueryClient();
const list = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
initialPageParam: { path: { post_id: postId } },
const talkId = 'talkId' in to ? to.talkId : undefined;
const postId = 'postId' in to ? to.postId : undefined;
// 둘 중 하나만 받는다
const postList = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId ?? 0 } }),
initialPageParam: { path: { post_id: postId ?? 0 } },
getNextPageParam: (last) => last.next_cursor ?? undefined,
enabled: postId != null,
});
const add = useMutation(addCommentMutation());
const talkList = useInfiniteQuery({
...listTalkCommentsInfiniteOptions({ path: { talk_id: talkId ?? 0 } }),
initialPageParam: { path: { talk_id: talkId ?? 0 } },
getNextPageParam: (last) => last.next_cursor ?? undefined,
enabled: talkId != null,
});
const list = talkId != null ? talkList : postList;
const addPost = useMutation(addCommentMutation());
const addTalk = useMutation(addTalkCommentMutation());
const add = { isPending: addPost.isPending || addTalk.isPending };
const agree = useMutation(agreeTermsMutation());
const s = useSoft();
const [addFailed, setAddFailed] = useState(false);
@@ -260,25 +285,30 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
const body = text.trim();
if (!body || add.isPending) return;
setAddFailed(false);
add.mutate(
{ path: { post_id: postId }, body: { body, region: region.code } },
{
onSuccess: (res) => {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true);
setAddFailed(!res.result?.success);
if (!res.result?.success) return;
const handlers = {
onSuccess: (res: { result?: { success?: boolean; desc?: string } }) => {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true);
setAddFailed(!res.result?.success);
if (!res.result?.success) return;
setText('');
queryClient.invalidateQueries({ queryKey: commentListKey(to) });
if (talkId != null) {
track('talk_comment', { talk_id: talkId });
queryClient.invalidateQueries({ predicate: isTalkList });
} else if (postId != null) {
track('comment', { post_id: postId });
setText('');
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) });
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
},
onError: () => setAddFailed(true),
}
},
);
onError: () => setAddFailed(true),
};
if (talkId != null) addTalk.mutate({ path: { talk_id: talkId }, body: { body } }, handlers);
else if (postId != null) addPost.mutate({ path: { post_id: postId }, body: { body, region: region.code } }, handlers);
};
// 댓글은 로그인 없이 '○○구 익명'으로 쓴다. 로그인했으면 약관에 동의해야 쓸 수 있고, 동의하면 쓰던 댓글을 바로 올린다
const submit = () => {
if (talkId != null && !me) return open({ type: 'login', then: { type: 'comments', ...to, draft: text } });
if (me && !me.terms_agreed) return setAskTerms(true);
send();
};
@@ -306,7 +336,7 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
<>
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
{comments.map((c) => (
<CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} onNotice={setNotice} />
<CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} to={to} onNotice={setNotice} />
))}
{list.hasNextPage && (
<Pressable onPress={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 disabled:opacity-50">
@@ -352,7 +382,7 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
{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} />
<Field ref={inputRef} round value={text} onChangeText={setText} editable={!add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : talkId != null ? '로그인하고 댓글 달기…' : '댓글 달기…'} accessibilityLabel="댓글" returnKeyType="send" onSubmitEditing={submit} />
</View>
<Pressable onPress={submit} disabled={add.isPending || !text.trim()} className="disabled:opacity-40">
<Text className="font-extrabold text-rain">{add.isPending ? '올리는 중…' : '게시'}</Text>
+1 -1
View File
@@ -90,7 +90,7 @@ function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () =>
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />}
{state.type === 'comments' && <CommentsSheet to={'talkId' in state ? { talkId: state.talkId } : { postId: state.postId }} draft={state.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={state.why} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
+2
View File
@@ -8,6 +8,7 @@ import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Avatar, Ic } from '@/components/ui';
import { MyTalks } from '@/components/talk/talk';
import { useAuth } from '@/lib/auth';
import { isCommentList } from './comments';
@@ -202,6 +203,7 @@ export function MeSheet({ onDone }: { onDone: () => void }) {
</Pressable>
</View>
<Text className={`min-h-5 text-center text-[13px] font-bold ${saving ? 'text-ink2' : 'text-heart'}`}>{saving ? (saving.nickname == null ? '저장 중…' : '') : error}</Text>
<MyTalks />
<Pressable
onPress={() => {
logout();
+426
View File
@@ -0,0 +1,426 @@
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 { holidayByTopic } from '@nalssigak/shared/lib/holiday';
import { useMutation } from '@tanstack/react-query';
import { Image } from 'expo-image';
import * as ImagePicker from 'expo-image-picker';
import { LinearGradient } from 'expo-linear-gradient';
import { useRef, useState } from 'react';
import { Pressable, TextInput, View } from 'react-native';
import { useCSSVariable } from 'uniwind';
import { CameraIcon, CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { Avatar } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { CARD_BG } from '@/lib/colors';
import { useRegion } from '@/lib/region';
import { useShare } from '@/lib/share-image';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
import { openTopics, talkImage, talkMeta, useMyTalks, useRefreshTalks } from '@/lib/talk';
const BODY_MAX = 100;
const PHOTO_MAX = 10 * 1024 * 1024;
// 서버 ErrorType 이름 → 안내
const WRITE_ERRORS: Record<string, string> = {
LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.',
DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.',
INVALID_INPUT: '100자 안으로 써 주세요.',
};
const REASONS = [
[TalkReport.ABUSE, '욕설·비하'],
[TalkReport.SPAM, '광고·도배'],
[TalkReport.PRIVACY, '개인정보 노출'],
[TalkReport.ETC, '기타'],
] as const;
type Photo = { uri: string; name: string; type: string };
/** 고른 사진을 올려 주소를 받는다. 앱의 사진은 Blob 이 아니라 {uri} 라서 FormData 를 직접 만든다 */
async function uploadPhoto(photo: Photo) {
const form = new FormData();
form.append('file', photo as unknown as Blob);
const { data } = await uploadTalkImage({ body: { file: photo as unknown as Blob }, bodySerializer: () => form });
if (!data.result?.success || !data.image) throw new Error(data.result?.desc ?? 'upload');
return data.image;
}
/** 이야기 쓰는 칸: 로그인해야 쓴다. 주제·사진(하나)을 붙여 올린다 */
export function Composer() {
const { region } = useRegion();
const { loggedIn, me } = useAuth();
const { open } = useSheet();
const s = useSoft();
const [ink2] = useCSSVariable(['--color-ink2']).map(String);
const refresh = useRefreshTalks();
const add = useMutation(addTalkMutation());
const [text, setText] = useState('');
const [topic, setTopic] = useState<TalkTopic>(TalkTopic.LOCAL);
const [error, setError] = useState<string | null>(null);
const [photo, setPhoto] = useState<Photo | null>(null);
const [uploading, setUploading] = useState(false);
const busy = add.isPending || uploading;
const place = region.name.split(' ').at(-1);
const pick = async () => {
if (!loggedIn) return open({ type: 'login' });
try {
const res = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], quality: 0.85 });
const a = res.canceled ? undefined : res.assets[0];
if (!a) return;
if (a.fileSize && a.fileSize > PHOTO_MAX) return setError('사진은 10MB까지 올릴 수 있어요.');
setError(null);
setPhoto({ uri: a.uri, name: a.fileName ?? 'photo.jpg', type: a.mimeType ?? 'image/jpeg' });
} catch (e) {
console.error('[talk] pick photo', e);
setError('사진을 고르지 못했어요. 다시 해 주세요.');
}
};
const submit = async () => {
if (!loggedIn) return open({ type: 'login' });
const body = text.trim();
if (!body || busy) return;
setError(null);
let image: string | undefined;
if (photo) {
setUploading(true);
try {
image = await uploadPhoto(photo);
} catch (e) {
console.error('[talk] photo upload', e);
return setError('사진을 올리지 못했어요. 사진 파일인지 확인해 주세요.');
} finally {
setUploading(false);
}
}
add.mutate(
{ body: { region_code: region.code, body, image, topic } },
{
onSuccess: (res) => {
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.');
track('talk_post', { topic, with_image: !!image });
setText('');
setPhoto(null);
setTopic(TalkTopic.LOCAL);
refresh();
},
onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
},
);
};
return (
<View className="mx-3 mt-3.5 rounded-[22px] border-b-[5px] border-shade bg-card p-3">
{/* 로그인 전엔 칸을 눌러도 키보드 대신 로그인 창 */}
<Pressable disabled={loggedIn} onPress={() => open({ type: 'login' })}>
<TextInput
value={text}
onChangeText={setText}
editable={loggedIn && !busy}
maxLength={BODY_MAX}
multiline
numberOfLines={2}
placeholder={`지금 ${place} 날씨 어때요?`}
placeholderTextColor={s.placeholder}
accessibilityLabel="동네 이야기 쓰기"
className="min-h-[60px] rounded-2xl px-3 py-2.5 text-[14.5px] text-ink"
style={{ backgroundColor: s.soft, textAlignVertical: 'top' }}
pointerEvents={loggedIn ? 'auto' : 'none'}
/>
</Pressable>
{photo && (
<View className="mt-2 w-[96px]">
<Image source={{ uri: photo.uri }} style={{ width: 96, aspectRatio: 4 / 5, borderRadius: 12 }} contentFit="cover" accessibilityLabel="올릴 사진" />
<Pressable onPress={() => setPhoto(null)} accessibilityRole="button" accessibilityLabel="사진 빼기" className="absolute -top-1.5 -right-1.5 size-6 items-center justify-center rounded-full bg-ink-btn">
<Text className="text-[13px] font-extrabold text-white">×</Text>
</Pressable>
</View>
)}
<View className="mt-2 flex-row flex-wrap gap-1.5" accessibilityRole="radiogroup" accessibilityLabel="글 주제">
{openTopics().map(([k, label]) => (
<Pressable key={k} onPress={() => setTopic(k)} accessibilityRole="radio" accessibilityState={{ checked: topic === k }} className={`rounded-full px-2.5 py-1 ${topic === k ? 'bg-ink-btn' : ''}`} style={topic === k ? undefined : { backgroundColor: s.soft }}>
<Text className={`text-[12.5px] font-extrabold ${topic === k ? 'text-white' : 'text-ink2'}`}>{label}</Text>
</Pressable>
))}
</View>
<View className="mt-1.5 flex-row items-center gap-2">
{/* 주제 칩과 헷갈리지 않게 글자 대신 카메라 아이콘 */}
<Pressable onPress={pick} disabled={busy} hitSlop={6} accessibilityRole="button" accessibilityLabel="사진 붙이기" className="size-8 items-center justify-center rounded-full disabled:opacity-40" style={{ backgroundColor: s.soft }}>
<CameraIcon size={18} color={ink2} />
</Pressable>
<Text numberOfLines={1} className="min-w-0 flex-1 text-xs font-bold text-ink3">
{me ? `${me.nickname} · ${place} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}
</Text>
<Text className="text-xs font-bold text-ink3">
{text.length}/{BODY_MAX}
</Text>
<Pressable onPress={submit} disabled={busy || (loggedIn && !text.trim())} accessibilityRole="button" className="rounded-full bg-orange px-3.5 py-1.5 disabled:opacity-40">
<Text className="text-[13px] font-extrabold text-white">{busy ? '올리는 중…' : '올리기'}</Text>
</Pressable>
</View>
{!!error && (
<Text accessibilityRole="alert" className="mt-1 text-xs font-bold text-heart">
{error}
</Text>
)}
</View>
);
}
type Menu = 'closed' | 'open' | 'confirm' | 'report' | 'done';
/** 좋아요: 로그인 없이 된다. 화면을 먼저 바꾸고, 실패하면 되돌린다 */
function useTalkLike(t: TalkData) {
const [liked, setLiked] = useState(t.liked);
const [count, setCount] = useState(t.like_count);
const like = useMutation(likeTalkMutation());
const unlike = useMutation(unlikeTalkMutation());
const toggle = () => {
if (like.isPending || unlike.isPending) return;
const next = !liked;
setLiked(next);
setCount((n) => n + (next ? 1 : -1));
const revert = () => {
setLiked(!next);
setCount(t.like_count);
};
(next ? like : unlike).mutate(
{ path: { talk_id: t.talk_id } },
{
onSuccess: (res) => {
if (!res.result?.success || res.like_count == null) return revert();
if (next) track('like', { content_type: 'talk', item_id: t.talk_id });
setCount(res.like_count);
},
onError: revert,
},
);
};
return { liked, count, toggle };
}
function Chip({ label, danger, onPress, disabled }: { label: string; danger?: boolean; onPress: () => void; disabled?: boolean }) {
return (
<Pressable onPress={onPress} disabled={disabled} className={`rounded-full px-3 py-1 ${danger ? 'bg-[#fdecec]' : 'bg-[#eef4fc]'}`}>
<Text className={`text-[12.5px] font-extrabold ${danger ? 'text-heart' : 'text-[#28304a]'}`}>{label}</Text>
</Pressable>
);
}
/** 글 메뉴(⋯)를 눌렀을 때 나오는 버튼 줄: 내 글은 지우기, 남의 글은 안 보기·신고 */
function TalkMenu({ t, menu, setMenu, className }: { t: TalkData; menu: Menu; setMenu: (m: Menu) => void; className?: string }) {
const { loggedIn } = useAuth();
const { open } = useSheet();
const refresh = useRefreshTalks();
const remove = useMutation(deleteTalkMutation());
const report = useMutation(reportTalkMutation());
const block = useMutation(blockTalkAuthorMutation());
const [failed, setFailed] = useState(false);
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
const after = (done?: () => void) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true);
done?.();
setMenu('done');
refresh();
},
onError: () => setFailed(true),
});
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }));
return (
<View className={`flex-row flex-wrap items-center gap-1.5 ${className ?? ''}`} accessibilityLabel="글 메뉴">
{menu === 'done' ? (
<Text className="text-[12.5px] font-extrabold text-[#1f9d62]">처리했어요</Text>
) : t.mine && menu === 'confirm' ? (
<>
<Text className="text-[12.5px] font-extrabold text-ink2">지울까요?</Text>
<Chip label="지우기" danger disabled={remove.isPending} onPress={() => remove.mutate({ path: { talk_id: t.talk_id } }, after())} />
<Chip label="취소" onPress={() => setMenu('closed')} />
</>
) : t.mine ? (
<Chip label="지우기" danger onPress={() => setMenu('confirm')} />
) : menu === 'report' ? (
REASONS.map(([reason, label]) => <Chip key={reason} label={label} disabled={report.isPending} onPress={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after(() => track('report', { content_type: 'talk', reason })))} />)
) : (
<>
<Chip label="이 사람 글 안 보기" disabled={block.isPending} onPress={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after(() => track('block', { content_type: 'talk' }))))} />
<Chip label="신고하기" danger onPress={() => guard(() => setMenu('report'))} />
</>
)}
{failed && <Text className="text-[12.5px] font-extrabold text-heart">못 했어요. 다시 해 주세요</Text>}
</View>
);
}
function MenuButton({ menu, setMenu }: { menu: Menu; setMenu: (m: Menu) => void }) {
return (
<Pressable onPress={() => setMenu(menu === 'closed' ? 'open' : 'closed')} hitSlop={12} accessibilityRole="button" accessibilityState={{ expanded: menu !== 'closed' }} accessibilityLabel="글 메뉴">
<Text className="text-[15px] font-extrabold tracking-[1px] text-ink3">⋯</Text>
</Pressable>
);
}
function MineBadge() {
return (
<Text className="overflow-hidden rounded-full bg-[#ffe8dc] px-1.5 text-[11px] font-extrabold text-[#c2471b]">
{' 내 글 '}
</Text>
);
}
/** 한 줄 글: 목록·내 정보의 내 글 */
function TalkRow({ t, last }: { t: TalkData; last?: boolean }) {
const { liked, count, toggle } = useTalkLike(t);
const [menu, setMenu] = useState<Menu>('closed');
const [heart, ink3] = useCSSVariable(['--color-heart', '--color-ink3']).map(String);
const src = talkImage(t);
return (
<View className={`flex-row items-start gap-2.5 py-2.5 ${last ? '' : 'border-b border-line'}`}>
<Avatar character={t.character} color={t.color} mood={t.mood} />
<View className="min-w-0 flex-1">
<Text className="text-xs font-bold text-ink3">
<Text className="font-extrabold text-ink">{t.nickname} </Text>
{t.mine && (
<>
<MineBadge />{' '}
</>
)}
{talkMeta(t)}
</Text>
<Text className="mt-0.5 text-[14.5px] text-ink">{t.body}</Text>
{!!src && <Image source={{ uri: src }} style={{ marginTop: 8, width: '100%', aspectRatio: 4 / 5, borderRadius: 16, backgroundColor: '#eef4fc' }} contentFit="cover" />}
<Text className="mt-0.5 text-xs font-bold text-ink3">
{t.ago} · 좋아요 {count}개
</Text>
{menu !== 'closed' && <TalkMenu t={t} menu={menu} setMenu={setMenu} className="mt-1.5" />}
</View>
{/* 글 메뉴(⋯)는 하트 옆 오른쪽 위에: 아래 줄 끝에 두면 말줄임표처럼 읽힌다 */}
<View className="flex-row items-start gap-4">
<MenuButton menu={menu} setMenu={setMenu} />
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요" className="pt-1">
<HeartIcon size={16} color={liked ? heart : ink3} filled={liked} />
</Pressable>
</View>
</View>
);
}
// 사진 없는 글을 크게 띄울 때 주제별 바탕
const TOPIC_BG: Partial<Record<TalkTopic, string>> = { [TalkTopic.SKY]: 'peach', [TalkTopic.RAIN]: 'sky', [TalkTopic.FOLIAGE]: 'butter', [TalkTopic.OUTFIT]: 'lilac' };
/** 오늘 피드에 끼우는 사람 글: 운영 포스트와 같은 틀. 사진이 없으면 글을 4:5 칸에 크게. 두 번 누르면 좋아요 */
export function TalkPost({ t }: { t: TalkData }) {
const { open } = useSheet();
const { liked, count, toggle } = useTalkLike(t);
const [menu, setMenu] = useState<Menu>('closed');
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
const shot = useRef<View>(null);
const lastTap = useRef(0);
const shareView = useShare();
const src = talkImage(t);
const bg = (t.topic && (TOPIC_BG[t.topic] ?? holidayByTopic(t.topic)?.bg)) || 'mint';
const title = `${t.nickname}의 글`;
const share = () => void shareView(shot, { title, message: `${t.body} · 날씨각 ${SITE_URL}` });
const comments = () => open({ type: 'comments', talkId: t.talk_id });
const onTap = () => {
const now = Date.now();
if (now - lastTap.current < 320 && !liked) toggle();
lastTap.current = now;
};
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={title}>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<Avatar character={t.character} color={t.color} mood={t.mood} />
<View className="min-w-0 flex-1">
<Text className="text-sm leading-tight font-extrabold text-ink">
{t.nickname}
{t.mine && (
<>
{' '}
<MineBadge />
</>
)}
</Text>
<Text numberOfLines={1} className="text-xs font-semibold text-ink2">
{talkMeta(t)}
</Text>
</View>
<MenuButton menu={menu} setMenu={setMenu} />
</View>
{menu !== 'closed' && <TalkMenu t={t} menu={menu} setMenu={setMenu} className="px-3 pb-2.5" />}
<Pressable onPress={onTap} className="aspect-[4/5] overflow-hidden">
<View ref={shot} collapsable={false} className="flex-1">
{src ? (
<Image source={{ uri: src }} style={{ flex: 1, backgroundColor: '#eef4fc' }} contentFit="cover" />
) : (
// 포스트 안은 밤에도 낮 색 (웹 b-day)
<View className="flex-1 items-center justify-center px-7">
<LinearGradient colors={CARD_BG.day[bg] ?? CARD_BG.day.mint} style={{ position: 'absolute', inset: 0 }} />
<Text className={`text-center font-jua text-[26px] leading-snug ${bg === 'night' ? 'text-white' : 'text-[#28304a]'}`}>{t.body}</Text>
</View>
)}
</View>
</Pressable>
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
<Pressable onPress={toggle} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요">
<HeartIcon size={26} color={liked ? heart : ink} filled={liked} />
</Pressable>
<Pressable onPress={comments} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
<CommentIcon size={26} color={ink} />
</Pressable>
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
<SendIcon size={26} color={ink} />
</Pressable>
</View>
<Text className="px-3 py-0.5 text-sm font-extrabold text-ink">좋아요 {count.toLocaleString()}개</Text>
{!!src && (
<Text className="px-3 py-0.5 text-sm text-ink">
<Text className="font-extrabold">{t.nickname} </Text>
{t.body}
</Text>
)}
<Pressable onPress={comments}>
<Text className="px-3 pt-[3px] text-sm font-semibold text-ink3">{t.comment_count ? `댓글 ${t.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
</Pressable>
<Text className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-ink3">{t.ago}</Text>
</View>
);
}
/** 이야기 탭 목록의 글 한 장 */
export function TalkCard({ t }: { t: TalkData }) {
return (
<View className="mx-3 mt-3 rounded-[20px] border-b-4 border-shade bg-card px-3" accessibilityLabel={`${t.nickname}의 글`}>
<TalkRow t={t} last />
</View>
);
}
/** 내 정보 창의 내가 쓴 글 */
export function MyTalks() {
const { talks, loaded, more, loadMore } = useMyTalks();
const s = useSoft();
if (!loaded) return null;
return (
<View accessibilityLabel="내 글">
<Text className="mb-1 text-sm font-extrabold text-ink">내 글</Text>
{talks.length ? talks.map((t, i) => <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} last={i === talks.length - 1} />) : <Text className="text-[13px] font-semibold text-ink3">아직 쓴 글이 없어요</Text>}
{more && (
<Pressable onPress={() => loadMore()} className="mt-1 rounded-[14px] py-2.5" style={{ backgroundColor: s.soft }}>
<Text className="text-center text-[13.5px] font-extrabold text-ink2">더 보기</Text>
</Pressable>
)}
</View>
);
}
+3 -1
View File
@@ -2,7 +2,9 @@ import { createContext, use } from 'react';
import type { WeatherWhyPayload } from '@/components/sheets/weather-why';
type CommentsState = { type: 'comments'; postId: number; draft?: string };
/** 댓글이 달린 곳: 운영 포스트 또는 사람 글 */
export type CommentTarget = { postId: number } | { talkId: number };
type CommentsState = { type: 'comments'; draft?: string } & CommentTarget;
export type SheetState =
| { type: 'gak'; indexId: number }
+75
View File
@@ -0,0 +1,75 @@
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen';
import { kst } from '@nalssigak/shared/lib';
import { HOLIDAYS, holidayOn } from '@nalssigak/shared/lib/holiday';
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import { useRegion } from '@/lib/region';
import { apiUri } from '@/lib/site';
// 글 주제와 이름 (웹 talkState.ts)
export const TOPICS = [
[TalkTopic.LOCAL, '동네 이야기'],
[TalkTopic.SKY, '하늘·노을'],
[TalkTopic.RAIN, '비·눈'],
[TalkTopic.FOLIAGE, '단풍·꽃'],
[TalkTopic.OUTFIT, '오늘 옷차림'],
...HOLIDAYS.map((h) => [h.topic, h.name] as const),
] as const;
export const topicName = (t?: number) => TOPICS.find(([k]) => k === t)?.[1] ?? '동네 이야기';
/** 지금 고를 수 있는 주제: 기념일 주제는 그 기간에만 */
export function openTopics() {
const on = holidayOn()?.topic;
return TOPICS.filter(([k]) => !HOLIDAYS.some((h) => h.topic === k) || k === on);
}
/** 주제별 글 페이지 목록 (topic 없으면 전체) */
export function useTopicTalks(topic?: TalkTopic) {
const { region } = useRegion();
const list = useInfiniteQuery({
...listTalksInfiniteOptions({ query: { region: region.code, ...(topic ? { topic } : {}) } }),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
});
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
refetch: list.refetch,
refetching: list.isRefetching,
};
}
/** 내가 쓴 글 (최신순) */
export function useMyTalks(enabled = true) {
const list = useInfiniteQuery({
...listMyTalksInfiniteOptions(),
enabled,
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
});
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
};
}
export function useRefreshTalks() {
const queryClient = useQueryClient();
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') });
}
/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */
function slotWord(iso: string) {
const h = kst(iso).h;
return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤';
}
export const talkMeta = (t: TalkData) => [t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ');
/** 올린 사진은 API 서버 경로(/v1/talk/image/...) */
export const talkImage = (t: TalkData) => (t.image ? apiUri(t.image) : undefined);