Files
o2o-weather/mobile/src/components/post/post-card.tsx
T

230 lines
10 KiB
TypeScript

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, readonly [string, string]> = {
[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<PostData>) {
queryClient.setQueriesData<ResFeed>({ 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 (
<View className="mx-3 mt-3.5 flex-row items-center gap-3 rounded-[22px] border-b-4 border-shade bg-card px-4 py-3" accessibilityLabel={post.title}>
<Ic name={post.icon || avatar} size={40} />
<View className="flex-1">
<Text className="text-xs font-bold text-ink3">{account}</Text>
<Text className="text-sm text-ink2">
<Text className="font-jua text-base text-ink">{post.title}</Text> {post.caption}
</Text>
</View>
</View>
);
}
/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */
export function PostCard({ post }: PostProps) {
return post.size === 'line' ? <LineCard post={post} /> : <FullCard post={post} />;
}
/** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */
export function PostCardSkel() {
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityElementsHidden>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<View className="size-[34px] rounded-full bg-skel" />
<View className="gap-1.5">
<Skel className="w-12" />
<Skel className="w-16" />
</View>
</View>
<View className="aspect-[4/5] bg-skel" />
<View className="flex-row gap-3.5 px-3 pt-2.5 pb-1">
<View className="size-7 rounded-full bg-skel" />
<View className="size-7 rounded-full bg-skel" />
<View className="size-7 rounded-full bg-skel" />
</View>
<View className="gap-2 px-3 pt-1 pb-3">
<Skel className="w-20" />
<Skel className="w-4/5" />
<Skel className="w-32" />
<Skel className="w-8" />
</View>
</View>
);
}
/** 좋아요 때 가운데에 커졌다 사라지는 하트 */
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 (
<Animated.View pointerEvents="none" className="absolute inset-0 items-center justify-center" style={{ opacity, transform: [{ scale }] }}>
<Svg viewBox="0 0 24 24" width={112} height={112} fill="#ff3b5c">
<Path d={HEART} />
</Svg>
</Animated.View>
);
}
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<PostData>) => patchFeed(queryClient, post.post_id, values);
const comments = () => open({ type: 'comments', postId: post.post_id });
const shot = useRef<View>(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 (
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={post.title}>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<View className="size-[34px] rounded-full p-0.5">
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 17 }} />
<View className="flex-1 items-center justify-center rounded-full bg-card">
<Ic name={avatar} size={22} />
</View>
</View>
<View>
<Text className="text-sm leading-tight font-extrabold text-ink">날씨각</Text>
<Text className="text-xs font-semibold text-ink2">{account}</Text>
</View>
</View>
<Pressable onPress={onTap} onLayout={(e) => setWidth(e.nativeEvent.layout.width)} className="aspect-[4/5] overflow-hidden" accessibilityLabel={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}>
<View ref={shot} collapsable={false}>
{width > 0 && (
<Pager width={width} height={(width * 5) / 4} onIndex={setIndex}>
{post.slides.map((s, i) => (
<SlideView key={i} slide={s} bg={slideBg(post, s)} />
))}
</Pager>
)}
</View>
{n > 1 && (
<View pointerEvents="none" className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px]">
<Text className="text-xs font-extrabold text-white">
{index + 1}/{n}
</Text>
</View>
)}
{pop > 0 && <HeartPop key={pop} />}
{likeFailed > 0 && (
<View pointerEvents="none" className="absolute inset-x-0 bottom-4 items-center px-4" accessibilityRole="alert">
<Text className="overflow-hidden rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요.</Text>
</View>
)}
</Pressable>
<Dots n={n} index={index} />
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
<Pressable onPress={() => setLike(!liked)} 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">좋아요 {likeCount.toLocaleString()}개</Text>
<Text className="px-3 py-0.5 text-sm text-ink">
<Text className="font-extrabold">날씨각 </Text>
{post.caption}
</Text>
<Pressable onPress={comments}>
<Text className="px-3 pt-[3px] text-sm font-semibold text-ink3">{post.comment_count ? `댓글 ${post.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
</Pressable>
<Text className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-ink3">오늘</Text>
</View>
);
}