feat: 앱 오늘 피드를 웹과 맞춤 — 히어로 오늘/내일 전환·좋아요·댓글·보내기·점수 근거 창, 오늘의 각 카드(gak_post), 날씨각 카드(그림 슬라이드), 행사·TOP5 띠 없앰, 좋아요·댓글 로그인 없이 (GA hero_day_switch, like hero_post·gak_post)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
skkimandClaude committed 2026-11-04 17:23:44 +09:00
1 parent e8b8cc79b6
commit 01b5f917b9
16 files changed
+449 -156

No files matched your search

+1 -1
View File
@@ -78,7 +78,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
- 앱도 같은 이벤트 이름·값으로 `track()`을 부른다 (`mobile/src/lib/analytics.ts`). 모든 이벤트에 `platform: 'app'`이 붙는다.
- **아직 GA4로 보내지 않는다 (2026-11-04).** Firebase Analytics(`google-services.json`)를 붙이면 앱 시작 때 `setAnalyticsSender`로 보내는 함수를 단다. 그 전까지 `track()`은 아무것도 보내지 않는다. 개발 빌드(`__DEV__`)는 붙인 뒤에도 보내지 않는다.
- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`).
- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`).
- 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다.
## GA4 설정
+15 -12
View File
@@ -6,9 +6,10 @@ import { Fragment, type ReactNode } from 'react';
import { RefreshControl, ScrollView } from 'react-native';
import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card';
import { GakCard } from '@/components/today/gak-card';
import { Hero } from '@/components/today/hero';
import { EventsBand, SeasonBand, Stories, StoriesSkel, TopBand } from '@/components/today/rails';
import { Sec, StateBox } from '@/components/ui';
import { SeasonBand } from '@/components/today/rails';
import { StateBox } from '@/components/ui';
import { useRegion } from '@/lib/region';
import { useSky } from '@/lib/sky';
@@ -26,26 +27,28 @@ export default function TodayScreen() {
const load = loadOf(feed);
const refresh = () => Promise.all([feed.refetch(), today.refetch()]);
// 웹처럼 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand events={bands.events} /> : null],
[6, bands?.top5?.length ? <TopBand items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
[9, bands?.season?.length ? <SeasonBand news={bands.season} /> : null],
];
// 웹처럼 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 }}>
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more="/gak" />
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} boxClassName="inset-x-3 top-3 bottom-1" />}
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{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}시 기준` : '오늘 기준'} />
) : load === 'loading' ? (
<PostCardSkel />
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} boxClassName="inset-x-3 top-3 bottom-1" />
)}
{load === 'loading' && (
<>
<PostCardSkel />
<PostCardSkel />
</>
)}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다. 다시 시도는 위 각 줄에 한 번만 */}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
{load !== 'loading' && !posts.length && (
<StateBox
load="ready"
+6 -9
View File
@@ -14,7 +14,6 @@ import { Dots, Pager } from '@/components/post/pager';
import { slideBg, SlideView, type Slide } from '@/components/post/slides';
import { Ic, Skel } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { useSheet } from '@/lib/sheet';
import { shareView } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
@@ -35,12 +34,11 @@ const ACCOUNTS: Partial<Record<PostType, readonly [string, string]>> = {
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
[PostType.MOON]: ['오늘 밤 달', 'moon'],
[PostType.UV]: ['자외선', 'glasses'],
[PostType.CARD]: ['날씨각 카드', 'stars'],
};
const isSlide = (s: PostData['slides'][number]): s is Slide => s.kind !== 'image';
/** 앱이 그릴 줄 아는 글만 (웹 전용 글 종류·이미지 슬라이드가 든 글은 뺀다) */
export const isAppPost = (p: PostData) => p.post_type in ACCOUNTS && p.slides.every(isSlide);
/** 앱이 그릴 줄 아는 글 종류만 (히어로·띠처럼 피드 반응 칸으로만 오는 종류는 뺀다) */
export const isAppPost = (p: PostData) => p.post_type in ACCOUNTS;
type PostProps = { post: PostData };
@@ -118,7 +116,6 @@ function HeartPop() {
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;
@@ -145,8 +142,8 @@ function FullCard({ post }: PostProps) {
}, [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);
@@ -171,7 +168,7 @@ function FullCard({ post }: PostProps) {
const onTap = () => {
const now = Date.now();
if (now - lastTap.current < 320) {
if (liked && loggedIn) setPop((p) => p + 1);
if (liked) setPop((p) => p + 1);
else setLike(true);
}
lastTap.current = now;
@@ -195,7 +192,7 @@ function FullCard({ post }: PostProps) {
<View ref={shot} collapsable={false}>
{width > 0 && (
<Pager width={width} height={(width * 5) / 4} onIndex={setIndex}>
{post.slides.filter(isSlide).map((s, i) => (
{post.slides.map((s: Slide, i) => (
<SlideView key={i} slide={s} bg={slideBg(post, s)} />
))}
</Pager>
+78
View File
@@ -0,0 +1,78 @@
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen';
import type { PinnedKey } from '@nalssigak/shared/lib/analytics';
import { LinearGradient } from 'expo-linear-gradient';
import { useRef, type ReactNode } from 'react';
import { Pressable, View } from 'react-native';
import { useCSSVariable } from 'uniwind';
import { CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { usePinnedLike } from '@/lib/pinned-like';
import { useSheet } from '@/lib/sheet';
import { shareView } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
type Props = { title: string; account: string; avatar: string; caption?: string; more?: ReactNode; pinned?: { key: PinnedKey; post?: PostReaction | null }; children: ReactNode };
/** 오늘의 각처럼 포스트 틀(머리줄·버튼줄·글 한 줄)만 빌려 쓰는 카드 (웹 PostFrame). 좋아요·댓글은 피드의 반응 칸(pinned)에 붙는다 */
export function PostFrame({ title, account, avatar, caption, more, pinned, children }: Props) {
const { open } = useSheet();
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
const like = usePinnedLike(pinned?.key ?? 'gak_post', pinned?.post);
const postId = pinned?.post?.post_id;
const shot = useRef<View>(null);
const share = () => void shareView(shot, { title, message: `${title} · 날씨각 ${SITE_URL}` });
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">
<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>
<View ref={shot} collapsable={false}>
{children}
</View>
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
{postId != null && (
<>
<Pressable onPress={like.toggle} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: like.liked }} accessibilityLabel="좋아요">
<HeartIcon size={26} color={like.liked ? heart : ink} filled={like.liked} />
</Pressable>
<Pressable onPress={() => open({ type: 'comments', postId })} 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>
{more != null && <View className="ml-auto">{more}</View>}
</View>
{postId != null && (
<Text className={`px-3 py-0.5 text-sm font-extrabold ${like.failed ? 'text-heart' : 'text-ink'}`} accessibilityRole={like.failed ? 'alert' : undefined}>
{like.failed ? '좋아요를 반영하지 못했어요. 다시 해 주세요.' : `좋아요 ${like.count.toLocaleString()}개`}
</Text>
)}
{!!caption && (
<Text className="px-3 pt-0.5 pb-3 text-sm text-ink">
<Text className="font-extrabold">날씨각 </Text>
{caption}
</Text>
)}
{postId != null && (
<Pressable onPress={() => open({ type: 'comments', postId })}>
<Text className="px-3 pb-3 text-sm font-semibold text-ink3">{pinned?.post?.comment_count ? `댓글 ${pinned.post.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
</Pressable>
)}
</View>
);
}
+6 -4
View File
@@ -1,4 +1,4 @@
import type { GakSlide, HoursSlide, PlanSlide, PostData, RowsSlide, SunsetSlide, WeekSlide } from '@nalssigak/shared/api/client/types.gen';
import type { GakSlide, HoursSlide, ImageSlide, PlanSlide, PostData, RowsSlide, SunsetSlide, WeekSlide } from '@nalssigak/shared/api/client/types.gen';
import { PostType, SlotTone } from '@nalssigak/shared/api/client/types.gen';
import { cardBg, clockShort } from '@nalssigak/shared/lib';
import type { SlideBg } from '@nalssigak/shared/lib/types';
@@ -14,10 +14,10 @@ import { MoonArt } from '@/components/moon';
import { Credit, Ic, Rows, Thumb } from '@/components/ui';
import { CARD_BG } from '@/lib/colors';
import { useSheet } from '@/lib/sheet';
import { imageUri } from '@/lib/site';
import { apiUri, imageUri } from '@/lib/site';
import { useSky } from '@/lib/sky';
export type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide;
export type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide | ImageSlide;
type Stops = readonly [string, string, ...string[]];
@@ -50,7 +50,7 @@ const HOUR_TONE: Record<string, { bg: string; edge: string }> = {
/** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */
export function slideBg(post: PostData, slide: Slide): SlideBg {
if (slide.kind === 'hours') return 'sky';
if (slide.kind === 'hours' || slide.kind === 'image') return 'sky';
if (slide.kind === 'sunset') return 'dusk';
if (slide.kind === 'week') return 'mint';
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter';
@@ -254,6 +254,8 @@ export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
</Base>
);
}
// 카드뉴스: 관리자가 만든 4:5 그림 한 장 (/v1/card/... 는 API 서버 경로)
if (slide.kind === 'image') return <Image source={{ uri: apiUri(slide.url) }} accessibilityLabel={slide.alt ?? undefined} style={{ flex: 1 }} contentFit="cover" />;
if (slide.kind === 'rows' && slide.image)
return (
<View className="flex-1 justify-end">
+5 -9
View File
@@ -130,8 +130,6 @@ function CommentsSkel() {
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
const { region } = useRegion();
const { loggedIn } = useAuth();
const { open } = useSheet();
const queryClient = useQueryClient();
const [heart, ink3] = useCSSVariable(['--color-heart', '--color-ink3']).map(String);
const [liked, setLiked] = useState(c.liked);
@@ -142,8 +140,8 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
const [removeFailed, setRemoveFailed] = useState(false);
const [likeFailed, setLikeFailed] = useState(false);
// 좋아요는 로그인 없이 된다 (웹과 같이)
const toggle = () => {
if (!loggedIn) return open({ type: 'login' });
if (like.isPending || unlike.isPending) return;
const next = !liked;
setLikeFailed(false);
@@ -235,8 +233,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
export function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
const { region } = useRegion();
const { open } = useSheet();
const { loggedIn, me } = useAuth();
const { me } = useAuth();
const queryClient = useQueryClient();
const list = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
@@ -264,7 +261,7 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
if (!body || add.isPending) return;
setAddFailed(false);
add.mutate(
{ path: { post_id: postId }, body: { body } },
{ path: { post_id: postId }, body: { body, region: region.code } },
{
onSuccess: (res) => {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true);
@@ -280,9 +277,8 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
);
};
// 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
// 댓글은 로그인 없이 '○○구 익명'으로 쓴다. 로그인했으면 약관에 동의해야 쓸 수 있고, 동의하면 쓰던 댓글을 바로 올린다
const submit = () => {
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } });
if (me && !me.terms_agreed) return setAskTerms(true);
send();
};
@@ -358,7 +354,7 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
<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} />
</View>
<Pressable onPress={submit} disabled={add.isPending || (loggedIn && !text.trim())} className="disabled:opacity-40">
<Pressable onPress={submit} disabled={add.isPending || !text.trim()} className="disabled:opacity-40">
<Text className="font-extrabold text-rain">{add.isPending ? '올리는 중…' : '게시'}</Text>
</Pressable>
</View>
+3 -1
View File
@@ -14,6 +14,7 @@ import { GakSheet } from './gak';
import { LoginSheet } from './login';
import { MeSheet } from './me';
import { RegionSheet } from './region';
import { WeatherWhySheet } from './weather-why';
export function SheetProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<SheetState>(null);
@@ -35,7 +36,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
);
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const;
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', weatherWhy: '날씨 점수는 이렇게 나와요' } as const;
/** 판만 아래에서 올라온다 (웹 b-sheet: 0.26초, 40px 아래·흐릿하게에서) */
function Rise({ children }: { children: ReactNode }) {
@@ -92,6 +93,7 @@ function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () =>
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />}
</View>
</Rise>
)}
+1 -1
View File
@@ -30,7 +30,7 @@ export function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLogge
return (
<Body className="gap-2.5">
<Text className="text-center text-sm font-semibold text-ink2">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</Text>
<Text className="text-center text-sm font-semibold text-ink2">글쓰기는 로그인한 뒤에 할 수 있어요.</Text>
<GoogleButton
onResult={(res) => {
setError('');
@@ -0,0 +1,86 @@
import type { WeatherWhy } from '@nalssigak/shared/api/client/types.gen';
import { View } from 'react-native';
import { Text } from '@/components/text';
import { Body, useSoft } from './parts';
/** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[]; status?: { label: string; value: string; tone?: string; detail?: string | null }[] };
// 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게 (웹 weatherWhy.tsx)
const COLOR: Record<string, string> = { 기온: '#ff7a45', 비: '#4f97e3', 햇볕: '#ffb02e', 바람: '#5fb8b0', 습도: '#8e8cf0', 미세먼지: '#b59a86' };
const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8';
// 상태 줄 항목마다 단계를 나누는 기준 (backend/services/hero_stats.py 와 같은 값)
const RULE: Record<string, string> = {
습도: '30% 아래는 건조, 60% 넘으면 습함이에요',
불쾌지수: '68 아래는 쾌적, 75부터 불쾌예요',
자외선: '3 아래는 낮음, 6부터 높음이에요',
미세먼지: '에어코리아 기준 등급이에요',
};
/** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */
export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
const s = useSoft();
return (
<Body>
<View className="flex-row items-baseline gap-2">
<Text className="font-bagel text-[44px] leading-[48px] text-ink">{d.score}</Text>
<Text className="font-jua text-[17px] text-ink2">{d.label} 날씨 점수</Text>
</View>
<View className="mt-3 h-7 flex-row gap-[3px] overflow-hidden rounded-[10px]" accessibilityRole="image" accessibilityLabel={d.why.map((w) => `${w.label} 비중 ${w.weight}% 중 ${w.score}점`).join(', ')}>
{d.why.map((w) => (
<View key={w.label} className="h-full" style={{ width: `${w.weight}%`, backgroundColor: s.bar }}>
<View className="absolute inset-y-0 left-0" style={{ width: `${w.score}%`, backgroundColor: colorOf(w.label) }} />
</View>
))}
</View>
<Text className="mt-1.5 text-[12.5px] font-semibold text-ink3">칸 넓이는 비중, 채운 만큼이 얻은 점수예요</Text>
<View className="mt-3 gap-1.5">
{d.why.map((w) => (
<View key={w.label} className="flex-row items-center gap-3 rounded-2xl px-3.5 py-2.5" style={{ backgroundColor: s.soft }}>
<View className="size-3 rounded-full" style={{ backgroundColor: colorOf(w.label) }} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] leading-tight text-ink">
{w.label} <Text className="font-sans text-[12px] font-bold text-ink3">비중 {w.weight}%</Text>
</Text>
<Text className="text-[13px] font-semibold text-ink2">{w.note}</Text>
</View>
<Text className="font-jua text-[20px] text-ink">{w.score}</Text>
</View>
))}
</View>
{!!d.status?.length && (
<>
<Text className="mt-5 font-jua text-[17px] text-ink">지금 상태</Text>
<View className="mt-2 gap-1.5">
{d.status.map((x) => (
<View key={x.label} className="flex-row items-center gap-3 rounded-2xl px-3.5 py-2.5" style={{ backgroundColor: s.soft }}>
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] leading-tight text-ink">{x.label}</Text>
{!!RULE[x.label] && <Text className="text-[12.5px] font-semibold text-ink3">{RULE[x.label]}</Text>}
</View>
<View className="items-end">
<Text className={`font-jua text-[18px] leading-tight ${x.tone === 'warn' ? 'text-[#d4552a]' : 'text-ink'}`}>
{x.value}
</Text>
{x.detail?.split(' · ').map((v) => (
<Text key={v} className="text-[12px] font-bold text-ink2">
{v}
</Text>
))}
</View>
</View>
))}
</View>
</>
)}
<Text className="mt-3 text-[13px] leading-relaxed font-semibold text-ink2">조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요.</Text>
</Body>
);
}
+53
View File
@@ -0,0 +1,53 @@
import type { PostReaction, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { MEDALS } from '@nalssigak/shared/lib';
import { Link } from 'expo-router';
import { Pressable, View } from 'react-native';
import { PostFrame } from '@/components/post/post-frame';
import { Text } from '@/components/text';
import { Grad, Ic } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
/** 오늘의 각 1~5위를 포스트 틀에 담은 카드 (웹 GakCard). 좋아요·댓글은 gak_post 에 붙는다 */
export function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) {
const { open } = useSheet();
const top = items.filter((g) => g.active).slice(0, 5);
return (
<PostFrame
title={`오늘의 각 · ${place}`}
account="오늘의 각"
avatar="rabbit"
caption="누르면 계산 근거를 보여 줘요"
pinned={{ key: 'gak_post', post }}
more={
<Link href="/gak" className="text-[13px] font-bold text-ink2">
전체 보기
</Link>
}
>
{/* 웹 b-band-2. 포스트 안은 밤에도 낮 색 */}
<Grad colors={['#fff6d8', '#f7fbff']} className="px-4 pt-3.5 pb-3">
<Text className="font-jua text-[19px] text-ink">
오늘의 각 · {place} {at}
</Text>
<View className="mt-2 gap-1.5">
{top.map((g, i) => (
<Pressable key={g.index_id} onPress={() => open({ type: 'gak', indexId: g.index_id })} accessibilityRole="button" accessibilityLabel={`${i + 1}위 ${g.name} ${g.score}점, 계산 근거 보기`} className="flex-row items-center gap-2.5 rounded-[18px] border-b-4 border-shade bg-card px-3 py-2">
{i < 3 ? <Ic name={MEDALS[i]} size={24} /> : <Text className="w-6 text-center font-jua text-ink3">{i + 1}</Text>}
<Ic name={g.icon} size={34} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] leading-tight text-ink">{g.name}</Text>
{!!g.summary && (
<Text numberOfLines={1} className="text-xs font-semibold text-ink2">
{g.summary}
</Text>
)}
</View>
<Text className="font-bagel text-[22px] text-orange">{g.score}</Text>
</Pressable>
))}
</View>
</Grad>
</PostFrame>
);
}
+137 -28
View File
@@ -1,8 +1,10 @@
import type { Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { kindOfHour, kst, type Load, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib';
import { getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { Hero as HeroData, PostReaction, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { kindOfHour, kst, loadOf, type Load, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib';
import { KINDS, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today';
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText';
import { useEffect, useState, type ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { Pressable, View, type DimensionValue, type ViewStyle } from 'react-native';
import { Text } from '@/components/text';
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
@@ -11,9 +13,15 @@ import Svg, { Defs, RadialGradient, Rect, Stop } from 'react-native-svg';
import { Fall } from '@/components/fall';
import { MoonArt } from '@/components/moon';
import { CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
import { Shoot, type ShootSpec } from '@/components/sky-bg';
import { Ic, Skel } from '@/components/ui';
import { track } from '@/lib/analytics';
import { usePinnedLike } from '@/lib/pinned-like';
import { useRegion } from '@/lib/region';
import { shareView } from '@/lib/share-image';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
import { useSky } from '@/lib/sky';
type Mode = 'now' | TimeKind;
@@ -103,18 +111,32 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
return <Text className="opacity-50">?</Text>;
}
type Props = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load };
type Props = { hero?: HeroData | null; post?: PostReaction | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load };
export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
export function Hero({ hero, post, today, ranked, feedLoad, todayLoad }: Props) {
const { open } = useSheet();
const { region } = useRegion();
const like = usePinnedLike('hero_post', post);
const shot = useRef<View>(null);
// 내일 스위치: 내일 칸 날씨는 켤 때 받고, 시간대는 화면 전체 하늘과 따로 히어로 안에서만 고른다 (웹 TodayPage Hero)
const [tmr, setTmr] = useState(false);
const [tmrKind, setTmrKind] = useState<TimeKind>('day');
const tomorrowQ = useQuery({ ...getWeatherTodayOptions({ query: { region: region.code, day: 'tomorrow' } }), enabled: tmr });
const ahead = hero?.tomorrow;
const { preview, setServerKind, setPreview } = useSky();
const mode: Mode = preview ?? 'now';
const t = kst(useNow());
const mode: Mode = tmr ? tmrKind : (preview ?? 'now');
const clock = useNow();
const t = kst(tmr ? new Date(clock.getTime() + 86400000) : clock);
const nowKind = hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi);
const kind = mode === 'now' ? nowKind : mode;
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind]);
const slots = today?.slots ?? [];
// 내일을 볼 땐 배경·글자색도 내일 고른 칸을 따른다
useEffect(() => {
if (tmr) setPreview(tmrKind);
}, [tmr, tmrKind, setPreview]);
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? [];
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad;
// 지금은 가장 가까운 3시간 칸. 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
const slotOf = (k: Mode) => {
if (k === 'now') {
@@ -127,20 +149,66 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s);
};
const weather = weatherOf(slotOf(mode));
const slotScore = mode === 'now' ? undefined : hero?.weather_slots?.[SLOT_KEY[mode]];
const score = slotScore ?? hero?.weather_score;
const slotTop = mode === 'now' ? undefined : ranked.find((g) => g.active);
const top1 = slotTop ?? hero?.top1;
const slotScore = mode === 'now' ? undefined : (tmr ? ahead?.weather_slots : hero?.weather_slots)?.[SLOT_KEY[mode]];
const score = tmr ? slotScore : (slotScore ?? hero?.weather_score);
// 점수를 누르면 보고 있는 시간대(지금이면 지금 구간)의 날씨 점수 근거
const whyKey = mode === 'now' ? SLOT_KEY[nowKind] : SLOT_KEY[mode];
const why = (tmr ? ahead?.weather_why : hero?.weather_why)?.[whyKey];
const whyLabel = tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label;
const slotTop = mode === 'now' || tmr ? undefined : ranked.find((g) => g.active);
const top1 = tmr ? ahead?.top1 : (slotTop ?? hero?.top1);
const dark = kind === 'sunset' || kind === 'night';
const moon = dark && hero?.moon_name && hero.moon_pct != null ? { pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null;
const moon = !tmr && dark && hero?.moon_name && hero.moon_pct != null ? { pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null;
// 말풍선 머리말: 지금은 / 낮은 / 내일은 / 내일 낮은
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label;
const bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null;
const status = hero?.status ?? [];
const tmrWhen = mode === 'now' ? '내일' : `내일 ${PREVIEW[mode].label}`;
const bubble = tmr
? top1
? top1.score >= 70
? `${tmrWhen}은 ${top1.name}!`
: `${tmrWhen}은 쉬어 가요`
: null
: slotTop
? slotTop.score >= 70
? `${when}은 ${slotTop.name}!`
: `${when}은 쉬어 가요`
: hero
? (hero.bubble ?? '지금은 쉬어 가요')
: failed(feedLoad)
? '앗, 날씨를 못 불러왔어요'
: null;
// 내일은 최저·최고 기온과 고른 시간대 습도
const temps = slots.flatMap((x) => (x.temp_c != null ? [x.temp_c] : []));
const humidity = tmr && mode !== 'now' ? slotOf(mode)?.humidity : null;
const status = tmr
? [
...(temps.length
? [
{ label: '최저', value: deg(Math.min(...temps)), tone: 'info' },
{ label: '최고', value: deg(Math.max(...temps)), tone: 'info' },
]
: []),
...(humidity != null ? [{ label: '습도', value: `${humidity}%`, tone: 'info' }] : []),
]
: (hero?.status ?? []);
const openWhy = () => why && score != null && open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } });
const switchDay = (v: boolean) => {
// 내일로 넘어갈 땐 지금 보던 시간대 그대로 시작해 배경이 튀지 않게
if (v && !tmr) setTmrKind(kind);
if (v !== tmr) track('hero_day_switch', { day: v ? 'tomorrow' : 'today' });
setTmr(v);
};
const share = () => {
const title = `${region.name} ${tmr ? '내일' : '오늘'} 날씨`;
void shareView(shot, { title, message: `${title} · 날씨각 ${SITE_URL}` });
};
const gray = !dark && weather !== 'clear' && weather !== 'partly';
const rain = weather === 'rain' || weather === 'sleet';
const snow = weather === 'snow' || weather === 'sleet';
const orb = ORB[kind === 'sunset' ? 'sunset' : kind === 'night' ? 'night' : 'sun'];
const text = dark ? 'text-white' : 'text-[#28304a]';
const icon = dark ? '#ffffff' : '#28304a';
const strip = dark ? 'rgb(255 255 255 / 0.14)' : 'rgb(255 255 255 / 0.42)';
// 가운데가 밝은 달이면 진한 글씨에 흰 번짐, 가운데가 어두운 달(초승·그믐·삭)이면 흰 글씨
const orbText: { color: string; textShadowColor?: string; textShadowRadius?: number } = !moon
? { color: orb.text }
@@ -149,7 +217,7 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
: { color: '#fff', textShadowColor: 'rgba(10,14,40,0.6)', textShadowRadius: 8 };
return (
<View className="mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3">
<View ref={shot} collapsable={false} className="mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3">
<LinearGradient colors={HERO_BG[gray ? 'gray' : kind]} locations={kind === 'night' ? [0, 0.6, 1] : [0, 0.5, 1]} style={{ position: 'absolute', inset: 0 }} />
{kind === 'night' && STARS.map((s, i) => <View key={i} className="absolute size-[3px] rounded-full bg-white" style={{ left: s.left, top: s.top, opacity: s.opacity }} />)}
{kind === 'night' && SHOOTS.map((s, i) => <Shoot key={i} {...s} />)}
@@ -159,9 +227,42 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
{snow && FLAKES.map((p, i) => <Particle key={`s${i}`} {...p} snow light={dark} />)}
</View>
)}
<Text className={`text-[14px] font-bold opacity-80 ${text}`}>
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</Text>
<View className="z-[3] flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
<View className="flex-row rounded-full p-[3px]" style={{ backgroundColor: strip }} accessibilityRole="radiogroup" accessibilityLabel="오늘 또는 내일 날씨">
{(
[
[false, '오늘'],
[true, '내일'],
] as const
).map(([v, l]) => (
<Pressable key={l} onPress={() => switchDay(v)} accessibilityRole="radio" accessibilityState={{ checked: tmr === v }} className={`rounded-full px-2.5 py-0.5 ${tmr === v ? 'bg-white' : ''}`}>
<Text className={`font-jua text-[13px] ${tmr === v ? 'text-[#d4552a]' : `opacity-75 ${text}`}`}>{l}</Text>
</Pressable>
))}
</View>
<Text className={`text-[13px] font-bold opacity-80 ${text}`}>
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</Text>
</View>
<View className="flex-row items-center">
{post && (
<>
<Pressable onPress={like.toggle} hitSlop={6} accessibilityRole="button" accessibilityState={{ selected: like.liked }} accessibilityLabel={like.failed ? '좋아요를 반영하지 못했어요. 다시 눌러 주세요' : '오늘 날씨 좋아요'} className={`h-8 flex-row items-center gap-1 px-[5px] ${like.liked ? '' : 'opacity-80'}`}>
<HeartIcon size={22} color={like.liked ? '#ff3b5c' : icon} filled={like.liked} />
{like.count > 0 && <Text className={`text-[13px] font-extrabold ${text}`}>{like.count.toLocaleString()}</Text>}
</Pressable>
<Pressable onPress={() => open({ type: 'comments', postId: post.post_id })} hitSlop={6} accessibilityRole="button" accessibilityLabel="오늘 날씨 댓글" className="h-8 flex-row items-center gap-1 px-[5px] opacity-80">
<CommentIcon size={22} color={icon} />
{post.comment_count > 0 && <Text className={`text-[13px] font-extrabold ${text}`}>{post.comment_count.toLocaleString()}</Text>}
</Pressable>
</>
)}
<Pressable onPress={share} hitSlop={6} accessibilityRole="button" accessibilityLabel="오늘 날씨 보내기" className="h-8 flex-row items-center px-[5px] opacity-80">
<SendIcon size={22} color={icon} />
</Pressable>
</View>
</View>
<View className="h-[146px] items-center">
<Fall d={0} f={5600} amp={8}>
<View className="mt-2 size-32 items-center justify-center" style={moon ? undefined : { boxShadow: `0 20px 40px ${kind === 'night' ? 'rgb(190 180 255 / 0.35)' : kind === 'sunset' ? 'rgb(255 150 110 / 0.4)' : 'rgb(240 106 58 / 0.32)'}`, borderRadius: 64 }}>
@@ -183,12 +284,15 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
<Rect x="-1" y="-1" width="2" height="2" rx="1" fill="url(#orb)" opacity={gray ? 0.85 : 1} />
</Svg>
)}
<Text className="font-jua text-[12px]" style={orbText}>
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</Text>
<Text className="font-bagel text-[52px] leading-[52px]" style={orbText}>
{heroVal(feedLoad, score, 'w-[84px] h-10')}
</Text>
{/* 점수 근거가 있으면 해를 눌러도 근거 창 */}
<Pressable disabled={!why || score == null} onPress={openWhy} className="items-center" accessibilityLabel={why && score != null ? `${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기` : undefined}>
<Text className="font-jua text-[12px]" style={orbText}>
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</Text>
<Text className="font-bagel text-[52px] leading-[52px]" style={orbText}>
{heroVal(feedLoad, score, 'w-[84px] h-10')}
</Text>
</Pressable>
</View>
</Fall>
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
@@ -217,19 +321,24 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
</Text>
</Text>
))}
{why && score != null && (
<Text onPress={openWhy} accessibilityRole="button" accessibilityLabel={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`} style={{ color: dark ? '#ffb38a' : '#d4552a' }}>
{' '}· 점수 근거 ›
</Text>
)}
</Text>
)}
</View>
<View className="mt-2.5 flex-row gap-1 rounded-[18px] p-[3px]" style={{ backgroundColor: dark ? 'rgb(255 255 255 / 0.14)' : 'rgb(255 255 255 / 0.42)' }} accessibilityRole="tablist" accessibilityLabel="하루 흐름, 누르면 그 시간대 하늘로">
{KINDS.map((k) => {
const isNow = k === nowKind;
const isNow = !tmr && k === nowKind;
const s = slotOf(isNow ? 'now' : k);
const on = k === kind;
return (
<Pressable key={k} accessibilityRole="tab" accessibilityState={{ selected: on }} onPress={() => setPreview(isNow ? null : k)} className={`flex-1 items-center rounded-[14px] py-1.5 ${on ? 'bg-white' : ''}`} style={on ? { boxShadow: '0 4px 12px rgb(40 48 74 / 0.1)' } : undefined}>
<Pressable key={k} accessibilityRole="tab" accessibilityState={{ selected: on }} onPress={() => (tmr ? setTmrKind(k) : setPreview(isNow ? null : k))} className={`flex-1 items-center rounded-[14px] py-1.5 ${on ? 'bg-white' : ''}`} style={on ? { boxShadow: '0 4px 12px rgb(40 48 74 / 0.1)' } : undefined}>
<Text className={`text-[13px] font-bold ${on ? 'text-[#d4552a]' : `opacity-75 ${text}`}`}>{isNow ? '지금' : PREVIEW[k].label}</Text>
<Ic name={k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)]} size={22} style={{ marginVertical: 2 }} />
<Text className={`font-jua text-[15px] ${on ? 'text-[#28304a]' : text}`}>{heroVal(todayLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</Text>
<Text className={`font-jua text-[15px] ${on ? 'text-[#28304a]' : text}`}>{heroVal(slotsLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</Text>
</Pressable>
);
})}
+4 -90
View File
@@ -1,62 +1,18 @@
import type { BandArticle, BandEvent, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { cardBg, MEDALS } from '@nalssigak/shared/lib';
import type { BandArticle } from '@nalssigak/shared/api/client/types.gen';
import { cardBg } from '@nalssigak/shared/lib';
import { LinearGradient } from 'expo-linear-gradient';
import { Link, type Href } from 'expo-router';
import type { Href } from 'expo-router';
import type { ReactNode } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic, Rail, Sec, Skel, Thumb } from '@/components/ui';
import { Rail, Sec, Thumb } from '@/components/ui';
import { CARD_BG, BAND_BG } from '@/lib/colors';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
const CARD = 'overflow-hidden rounded-[22px] border-b-[5px] border-shade bg-card';
/** 오늘의 각 순위: 동그라미 + 이름 + 점수. 지금 시간대가 아닌 각은 흐리게 */
export function Stories({ items }: { items: TopIndex[] }) {
const { open } = useSheet();
return (
<Rail>
{items.map((g, i) => (
<Pressable key={g.index_id} onPress={() => open({ type: 'gak', indexId: g.index_id })} accessibilityLabel={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={`w-[72px] items-center gap-1 ${g.active ? '' : 'opacity-55'}`}>
<View className="size-[68px]">
{!g.active || g.score < 50 ? (
<View className="absolute inset-0 rounded-full bg-[#d6deea]" />
) : (
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 34 }} />
)}
<View className="m-[3px] flex-1 items-center justify-center rounded-full border-[3px] border-page bg-page">
<Ic name={g.icon} size={42} />
</View>
{i < 3 && g.active && <Ic name={MEDALS[i]} size={25} style={{ position: 'absolute', right: -4, bottom: -4 }} />}
</View>
<Text numberOfLines={1} className="font-jua text-[13px] text-ink">
{g.name}
</Text>
{g.active ? <Text className="font-bagel text-[12.5px] leading-[14px] text-orange">{g.score}</Text> : <Text className="text-[11px] leading-[14px] font-extrabold text-ink3">지금 아님</Text>}
</Pressable>
))}
</Rail>
);
}
const SKELS = Array.from({ length: 6 }, (_, i) => i);
export function StoriesSkel() {
return (
<Rail>
{SKELS.map((i) => (
<View key={i} className="w-[72px] items-center gap-1.5">
<View className="size-[68px] rounded-full bg-skel" />
<Skel className="w-12" />
<Skel className="w-6" />
</View>
))}
</Rail>
);
}
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: Href; children: ReactNode }) {
const { kind } = useSky();
return (
@@ -75,48 +31,6 @@ function useCardBg() {
return CARD_BG[kind === 'night' ? 'night' : 'day'];
}
export function EventsBand({ events }: { events: BandEvent[] }) {
const bg = useCardBg();
return (
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week">
<Rail>
{events.map((e, i) => (
<Link key={e.event_id} href="/week" asChild>
<Pressable className={`w-[200px] ${CARD}`}>
<Thumb image={e.image} icon={e.icon} iconSize={76} className="h-[116px]">
<LinearGradient colors={bg[cardBg(e.icon, i)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
<View className={`absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] ${e.status_label === '진행 중' ? 'bg-[#1f9d62]' : 'bg-orange'}`}>
<Text className="text-[11.5px] font-extrabold text-white">{e.status_label}</Text>
</View>
</Thumb>
<Text className="px-3 pt-2.5 pb-3 font-jua text-[16.5px] leading-snug text-ink">{e.name}</Text>
</Pressable>
</Link>
))}
</Rail>
</Band>
);
}
export function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) {
const { open } = useSheet();
return (
<Band tone={2} title="지금 뜨는 각 TOP 5" sub={sub} to="/gak">
<Rail>
{items.slice(0, 5).map((g, i) => (
<Pressable key={g.index_id} onPress={() => open({ type: 'gak', indexId: g.index_id })} className="w-[138px] gap-1 rounded-[22px] border-b-[5px] border-shade bg-card p-3">
{i < 3 ? <Ic name={MEDALS[i]} size={26} style={{ position: 'absolute', top: 8, left: 8 }} /> : <Text className="absolute top-2.5 left-3 font-jua text-ink3">{i + 1}위</Text>}
<Ic name={g.icon} size={58} style={{ alignSelf: 'center' }} />
<Text className="font-jua text-base text-ink">{g.name}</Text>
<Text className="font-bagel text-[22px] leading-[24px] text-orange">{g.score}</Text>
{g.summary && <Text className="text-xs font-semibold text-ink2">{g.summary}</Text>}
</Pressable>
))}
</Rail>
</Band>
);
}
export function SeasonBand({ news }: { news: BandArticle[] }) {
const bg = useCardBg();
const { open } = useSheet();
+3 -1
View File
@@ -1,8 +1,10 @@
import { configureApi } from '@nalssigak/shared/api/setup';
import * as SecureStore from 'expo-secure-store';
import { API_URL } from '@/lib/site';
configureApi({
baseUrl: process.env.EXPO_PUBLIC_API_BASE_URL ?? 'http://localhost:9810',
baseUrl: API_URL,
storage: {
getItem: (key) => SecureStore.getItem(key),
setItem: (key, value) => SecureStore.setItem(key, value),
+43
View File
@@ -0,0 +1,43 @@
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { PostReaction, ResFeed } from '@nalssigak/shared/api/client/types.gen';
import type { PinnedKey } from '@nalssigak/shared/lib/analytics';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { track } from '@/lib/analytics';
/** 히어로·오늘의 각처럼 포스트 틀이 아닌 카드의 좋아요 (웹 pinnedLike.ts). 로그인 없이 된다. 화면을 먼저 바꾸고 실패하면 되돌린다 */
export function usePinnedLike(key: PinnedKey, r?: PostReaction | null) {
const queryClient = useQueryClient();
const like = useMutation(likePostMutation());
const unlike = useMutation(unlikePostMutation());
const [failed, setFailed] = useState(false);
const liked = !!r?.liked;
const count = r?.like_count ?? 0;
const patch = (values: Partial<PostReaction>) =>
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
feed?.[key] && feed[key].post_id === r?.post_id ? { ...feed, [key]: { ...feed[key], ...values } } : feed,
);
const toggle = () => {
if (!r || like.isPending || unlike.isPending) return;
const on = !liked;
setFailed(false);
patch({ liked: on, like_count: count + (on ? 1 : -1) });
const revert = () => {
patch({ liked, like_count: count });
setFailed(true);
};
(on ? like : unlike).mutate(
{ path: { post_id: r.post_id } },
{
onSuccess: (res) => {
if (!res.result?.success) return revert();
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) });
if (on) track('like', { content_type: key, item_id: r.post_id });
},
onError: revert,
},
);
};
return { liked, count, failed, toggle };
}
+3
View File
@@ -1,5 +1,7 @@
import { createContext, use } from 'react';
import type { WeatherWhyPayload } from '@/components/sheets/weather-why';
type CommentsState = { type: 'comments'; postId: number; draft?: string };
export type SheetState =
@@ -10,6 +12,7 @@ export type SheetState =
| { type: 'login'; then?: CommentsState }
| { type: 'me' }
| { type: 'region' }
| { type: 'weatherWhy'; why: WeatherWhyPayload }
| null;
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void };
+5
View File
@@ -2,3 +2,8 @@ export const SITE_URL = (process.env.EXPO_PUBLIC_SITE_URL ?? 'https://weather.o2
/** 서버가 주는 사진 경로가 '/season/..' 처럼 사이트 기준이면 사이트 주소를 붙인다 */
export const imageUri = (path: string) => (path.startsWith('/') ? `${SITE_URL}${path}` : path);
/** API 서버 주소. 카드뉴스 그림(/v1/card/...)처럼 API 서버에서 주는 경로에 붙인다 */
export const API_URL = (process.env.EXPO_PUBLIC_API_BASE_URL ?? 'http://localhost:9810').replace(/\/+$/, '');
export const apiUri = (path: string) => (path.startsWith('/') ? `${API_URL}${path}` : path);