feat: 앱 위치로 지역 찾기(expo-location), 게시물·주말 일정 이미지 공유(view-shot·expo-sharing)

This commit is contained in:
minaChoi committed 2026-10-14 14:49:37 +09:00
1 parent f71dd2cebb
commit 26bb6a00d2
10 files changed
+231 -31

No files matched your search

+11 -4
View File
@@ -1,13 +1,14 @@
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { loadOf, shortDay } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { Pressable, RefreshControl, ScrollView, Share, Text, View } from 'react-native';
import { useRef, useState } from 'react';
import { Pressable, RefreshControl, ScrollView, Text, View } from 'react-native';
import { DayStrip, EventRow, PickCard, PlaceCard, RankRow } from '@/components/week/sections';
import { DaysSkel, EventsSkel, PickSkel, PlacesSkel, RankSkel } from '@/components/week/skels';
import { Chips, Rail, Sec, Skel, StateBox } from '@/components/ui';
import { useRegion } from '@/lib/region';
import { shareView } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
// 불러오는 동안에도 탭 줄 높이를 지키려고 같은 칩을 미리 그린다
@@ -44,10 +45,12 @@ export default function WeekScreen() {
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready';
const refresh = () => Promise.all([week.refetch(), events.refetch(), ranking.refetch(), sel ? places.refetch() : null]);
const pickShot = useRef<View>(null);
// 고른 날 추천 카드를 이미지로
const sendPlan = () => {
if (!sel) return;
const message = [`${sel.weekday}요일 일정 · ${region.name}`, sel.headline, sel.summary, sel.pick, `날씨각 ${SITE_URL}`].filter(Boolean).join('\n');
Share.share({ message }).catch((e: unknown) => console.warn('일정 공유 실패', e));
void shareView(pickShot, { title: `${sel.weekday}요일 일정`, message });
};
const placeSub = sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? undefined : '날씨에 맞춰 골라 보여 줘요';
@@ -65,7 +68,11 @@ export default function WeekScreen() {
) : (
<StateBox load={weekLoad} onRetry={() => week.refetch()} empty="날씨가 아직 없어요." />
)}
{sel && <PickCard day={sel} />}
{sel && (
<View ref={pickShot} collapsable={false}>
<PickCard day={sel} />
</View>
)}
{(sel || weekLoad !== 'ready') && (
<>
<Text className="mx-4 mt-3.5 text-[13.5px] font-bold text-ink2">30km 안 · 데이트 명소</Text>
+14 -11
View File
@@ -3,7 +3,7 @@ import { PostType, type PostData, type ResFeed } from '@nalssigak/shared/api/cli
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query';
import { LinearGradient } from 'expo-linear-gradient';
import { useEffect, useRef, useState } from 'react';
import { Animated, Pressable, Share, Text, View } from 'react-native';
import { Animated, Pressable, Text, View } from 'react-native';
import Svg, { Path } from 'react-native-svg';
import { useCSSVariable } from 'uniwind';
@@ -13,6 +13,7 @@ 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]> = {
@@ -125,9 +126,9 @@ function FullCard({ post }: PostProps) {
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 share = () => {
Share.share({ message: `${post.title} · 날씨각 ${SITE_URL}` }).catch((e: unknown) => console.warn('공유 실패', e));
};
const shot = useRef<View>(null);
// 지금 보고 있는 슬라이드를 이미지로
const share = () => void shareView(shot, { title: post.title, message: `${post.title} · 날씨각 ${SITE_URL}` });
useEffect(() => {
if (!likeFailed) return;
@@ -179,13 +180,15 @@ function FullCard({ post }: PostProps) {
</View>
</View>
<Pressable onPress={onTap} onLayout={(e) => setWidth(e.nativeEvent.layout.width)} className="aspect-[4/5] overflow-hidden" accessibilityLabel={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}>
{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 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">
+18 -3
View File
@@ -1,7 +1,7 @@
import { listRegionsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { loadOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useDeferredValue, useState } from 'react';
import { useDeferredValue, useEffect, useRef, useState } from 'react';
import { Pressable, Text, View } from 'react-native';
import { Skel, StateBox } from '@/components/ui';
@@ -11,6 +11,8 @@ import { useSheet } from '@/lib/sheet';
import { Body, Field } from './parts';
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const;
const N14 = Array.from({ length: 14 }, (_, i) => i);
function RegionsSkel() {
@@ -25,9 +27,16 @@ function RegionsSkel() {
);
}
/** 지역 바꾸기: 구 이름으로 찾기 + 목록 */
/** 지역 바꾸기: 지금 위치로 찾기 + 구 이름으로 찾기 + 목록 */
export function RegionSheet({ onDone }: { onDone: () => void }) {
const { region, setRegion } = useRegion();
const { region, setRegion, locate, locateStatus } = useRegion();
const alive = useRef(true);
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
};
}, []);
const { me, logout } = useAuth();
const { open } = useSheet();
const [q, setQ] = useState('');
@@ -38,6 +47,12 @@ export function RegionSheet({ onDone }: { onDone: () => void }) {
return (
<Body>
<Pressable onPress={() => locate(() => alive.current && onDone())} disabled={locateStatus === 'locating'} className="items-center rounded-full border-b-[5px] border-orange-deep bg-orange p-3 disabled:opacity-60">
<Text className="font-jua text-[17px] text-white">지금 위치로 찾기</Text>
</Pressable>
<Text className="mt-2 min-h-5 text-center text-[13px] font-bold text-ink2" accessibilityLiveRegion="polite">
{LOCATE_TEXT[locateStatus]}
</Text>
<Field round value={q} onChangeText={setQ} placeholder="구 이름으로 찾기 (예: 마포)" accessibilityLabel="구 이름으로 찾기" />
{listLoad === 'loading' && <RegionsSkel />}
{listLoad !== 'loading' && !regions.length && <StateBox load={listLoad} onRetry={() => list.refetch()} empty="찾는 구가 없어요." />}
+9 -5
View File
@@ -8,7 +8,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useCSSVariable } from 'uniwind';
import { PinIcon } from '@/components/svg';
import { Avatar, Ic } from '@/components/ui';
import { Avatar, Ic, Skel } from '@/components/ui';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
@@ -54,7 +54,7 @@ function Account() {
export function TopBar() {
const pathname = usePathname();
const { region } = useRegion();
const { region, locateStatus } = useRegion();
const { open } = useSheet();
const { kind } = useSky();
const { top } = useSafeAreaInsets();
@@ -67,9 +67,13 @@ export function TopBar() {
<SeasonChip />
<Pressable onPress={() => open({ type: 'region' })} accessibilityLabel={`위치 바꾸기, 지금 ${region.name}`} className="ml-auto shrink-0 flex-row items-center gap-1 rounded-full border-b-4 border-shade bg-card px-3 pt-1 pb-1.5">
<PinIcon size={14} color={ink} />
<Text numberOfLines={1} className="text-[13.5px] font-bold text-ink">
{region.name.split(' ').at(-1)}
</Text>
{locateStatus === 'locating' ? (
<Skel className="w-[52px]" />
) : (
<Text numberOfLines={1} className="text-[13.5px] font-bold text-ink">
{region.name.split(' ').at(-1)}
</Text>
)}
</Pressable>
<Account />
</View>
+50 -4
View File
@@ -1,11 +1,15 @@
import { nearestRegion } from '@nalssigak/shared/api/client/sdk.gen';
import type { RegionData } from '@nalssigak/shared/api/client/types.gen';
import { DEFAULT_REGION } from '@nalssigak/shared/lib';
import * as Location from 'expo-location';
import * as SecureStore from 'expo-secure-store';
import { createContext, use, useCallback, useMemo, useState, type ReactNode } from 'react';
import { createContext, use, useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
const KEY = 'nalssigak.region';
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void };
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error';
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus };
const RegionContext = createContext<RegionApi | null>(null);
@@ -25,8 +29,22 @@ function readStored(): RegionData | null {
}
}
/** 위치 권한을 받아 가장 가까운 구. 권한이 없으면 'denied' */
async function findNearest(): Promise<RegionData | 'denied'> {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') return 'denied';
const pos = (await Location.getLastKnownPositionAsync({ maxAge: 600000 })) ?? (await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced }));
const { data } = await nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } });
if (!data.region) throw new Error('가까운 구를 찾지 못함');
return data.region;
}
export function RegionProvider({ children }: { children: ReactNode }) {
const [region, setRegionState] = useState<RegionData>(() => readStored() ?? DEFAULT_REGION);
const [stored] = useState(readStored);
const [region, setRegionState] = useState<RegionData>(stored ?? DEFAULT_REGION);
// 처음 켠 사람은 위치로 가장 가까운 구를 찾는 동안 지역 칩을 스켈레톤으로
const [locateStatus, setLocateStatus] = useState<LocateStatus>(stored ? 'idle' : 'locating');
const setRegion = useCallback((r: RegionData) => {
setRegionState(r);
try {
@@ -35,6 +53,34 @@ export function RegionProvider({ children }: { children: ReactNode }) {
console.warn('지역을 저장하지 못함', e);
}
}, []);
const api = useMemo(() => ({ region, setRegion }), [region, setRegion]);
const locate = useCallback(
(onFound?: () => void) => {
setLocateStatus('locating');
findNearest()
.then((r) => {
if (r === 'denied') return setLocateStatus('denied');
setLocateStatus('idle');
setRegion(r);
onFound?.();
})
.catch((e: unknown) => {
console.warn('위치로 지역을 찾지 못함', e);
setLocateStatus('error');
});
},
[setRegion],
);
// 처음 켠 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다. 못 찾으면 조용히 기본 구
useEffect(() => {
if (stored) return;
findNearest()
.then((r) => r !== 'denied' && setRegion(r))
.catch((e: unknown) => console.warn('첫 위치로 지역을 찾지 못함', e))
.finally(() => setLocateStatus('idle'));
}, [stored, setRegion]);
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus]);
return <RegionContext value={api}>{children}</RegionContext>;
}
+18
View File
@@ -0,0 +1,18 @@
import * as Sharing from 'expo-sharing';
import type { RefObject } from 'react';
import { Share, type View } from 'react-native';
import { captureRef } from 'react-native-view-shot';
/** 보이는 화면 조각을 PNG로 찍어 공유. 이미지 공유가 안 되는 곳(웹 등)이면 글로 보낸다 */
export async function shareView(ref: RefObject<View | null>, { title, message }: { title: string; message: string }) {
try {
if (ref.current && (await Sharing.isAvailableAsync())) {
const uri = await captureRef(ref, { format: 'png', quality: 1, result: 'tmpfile' });
await Sharing.shareAsync(uri, { mimeType: 'image/png', UTI: 'public.png', dialogTitle: title });
return;
}
await Share.share({ message });
} catch (e) {
console.warn('공유 실패', e);
}
}