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

+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>
);
}