import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; import { PostType, type PostData, type ResFeed } from '@nalssigak/shared/api/client/types.gen'; import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'; import { LinearGradient } from 'expo-linear-gradient'; import { useEffect, useRef, useState } from 'react'; import { Animated, Pressable, Text, View } from 'react-native'; import Svg, { Path } from 'react-native-svg'; import { useCSSVariable } from 'uniwind'; import { CommentIcon, HEART, HeartIcon, SendIcon } from '@/components/post/icons'; import { Dots, Pager } from '@/components/post/pager'; import { slideBg, SlideView } from '@/components/post/slides'; import { Ic, Skel } from '@/components/ui'; import { useAuth } from '@/lib/auth'; import { useSheet } from '@/lib/sheet'; import { shareView } from '@/lib/share-image'; import { SITE_URL } from '@/lib/site'; const ACCOUNTS: Record = { [PostType.WEATHER]: ['오늘 날씨', 'sun'], [PostType.GAK]: ['오늘의 각', 'rabbit'], [PostType.SUNSET]: ['노을', 'sunset'], [PostType.SEASON]: ['계절 소식', 'maple'], [PostType.EVENT]: ['가까운 행사', 'fireworks'], [PostType.TIP]: ['날씨 상식', 'bulb'], [PostType.WEEK]: ['주말 예보', 'calendar'], [PostType.ALERT]: ['생활 알림', 'umbrella'], [PostType.TOMORROW]: ['내일 미리보기', 'moon'], [PostType.QUOTE]: ['오늘의 한 문장', 'letter'], [PostType.WEEKEND_PLAN]: ['주말 플랜', 'calendar'], [PostType.AIR]: ['미세먼지', 'vent'], [PostType.DAY_TRIP]: ['당일치기', 'picnic'], [PostType.MOON]: ['오늘 밤 달', 'moon'], [PostType.UV]: ['자외선', 'glasses'], }; type PostProps = { post: PostData }; /** 받아 둔 피드 데이터에도 좋아요를 반영한다. 안 하면 다른 탭에 다녀왔을 때 예전 값으로 다시 그려진다 */ function patchFeed(queryClient: QueryClient, postId: number, patch: Partial) { queryClient.setQueriesData({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) => feed?.posts ? { ...feed, posts: feed.posts.map((p) => (p.post_id === postId ? { ...p, ...patch } : p)) } : feed, ); } /** 한 줄 카드 (흐린 날 노을처럼 큰 그림이 필요 없는 소식) */ function LineCard({ post }: PostProps) { const [account, avatar] = ACCOUNTS[post.post_type]; return ( {account} {post.title} {post.caption} ); } /** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */ export function PostCard({ post }: PostProps) { return post.size === 'line' ? : ; } /** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */ export function PostCardSkel() { return ( ); } /** 좋아요 때 가운데에 커졌다 사라지는 하트 */ function HeartPop() { const [v] = useState(() => new Animated.Value(0)); useEffect(() => { Animated.timing(v, { toValue: 1, duration: 800, useNativeDriver: true }).start(); }, [v]); const opacity = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0, 1, 1, 0] }); const scale = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0.3, 1.1, 1, 1] }); return ( ); } function FullCard({ post }: PostProps) { const { open } = useSheet(); const { loggedIn } = useAuth(); const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String); const liked = !!post.liked; const likeCount = post.like_count; const queryClient = useQueryClient(); const like = useMutation(likePostMutation()); const unlike = useMutation(unlikePostMutation()); const [width, setWidth] = useState(0); const [index, setIndex] = useState(0); const [pop, setPop] = useState(0); const [likeFailed, setLikeFailed] = useState(0); const lastTap = useRef(0); const [account, avatar] = ACCOUNTS[post.post_type]; const n = post.slides.length; const patch = (values: Partial) => patchFeed(queryClient, post.post_id, values); const comments = () => open({ type: 'comments', postId: post.post_id }); const shot = useRef(null); // 지금 보고 있는 슬라이드를 이미지로 const share = () => void shareView(shot, { title: post.title, message: `${post.title} · 날씨각 ${SITE_URL}` }); useEffect(() => { if (!likeFailed) return; const t = setTimeout(() => setLikeFailed(0), 2500); return () => clearTimeout(t); }, [likeFailed]); // 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다) const setLike = (on: boolean) => { if (!loggedIn) return open({ type: 'login' }); if (on === liked || like.isPending || unlike.isPending) return; if (on) setPop((p) => p + 1); setLikeFailed(0); patch({ liked: on, like_count: likeCount + (on ? 1 : -1) }); const revert = () => { patch({ liked, like_count: likeCount }); setLikeFailed(Date.now()); }; (on ? like : unlike).mutate( { path: { post_id: post.post_id } }, { onSuccess: (res) => (res.result?.success ? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) }) : revert()), onError: revert, }, ); }; const onTap = () => { const now = Date.now(); if (now - lastTap.current < 320) { if (liked && loggedIn) setPop((p) => p + 1); else setLike(true); } lastTap.current = now; }; return ( 날씨각 {account} setWidth(e.nativeEvent.layout.width)} className="aspect-[4/5] overflow-hidden" accessibilityLabel={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}> {width > 0 && ( {post.slides.map((s, i) => ( ))} )} {n > 1 && ( {index + 1}/{n} )} {pop > 0 && } {likeFailed > 0 && ( {liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요. )} setLike(!liked)} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요"> 좋아요 {likeCount.toLocaleString()}개 날씨각 {post.caption} {post.comment_count ? `댓글 ${post.comment_count}개 모두 보기` : '첫 댓글 남기기'} 오늘 ); }