feat: 앱 단풍 지도 — /foliage 지도(두 손가락 확대·이동, 눌러 가까운 명소)·단계별 명소 목록, 단풍철 오늘 피드 맨 앞 카드(foliage_post 좋아요·댓글)와 아이콘. 명소 데이터·계산을 shared/lib/foliage.ts 로 (GA foliage_open·foliage_spot)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
skkimandClaude committed 2026-11-04 17:52:23 +09:00
1 parent 6daa2f4d2a
commit e5cdfa2642
11 files changed
+966 -180

No files matched your search

@@ -0,0 +1,272 @@
import { ICON_R, LAND_CX, labelBoxes, nearest, placeLabels, placeProvinces, PROVINCES, spread, type Box, type Spot, type Stage } from '@nalssigak/shared/lib/foliage';
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type Ref } from 'react';
import { Pressable, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native';
import { Label, MapImage, Marker, MAP_INK, PAPER, Province, useLabelSizes } from '@/components/foliage/parts';
import { Text } from '@/components/text';
type Cam = { s: number; tx: number; ty: number };
const DOT_R: Record<Stage, number> = { peak: ICON_R, first: 4, before: 3, gone: 3 };
const MAX_ZOOM = 5;
const FIT_TOP = 30;
const FIT_BOTTOM = 14;
// 이름 우선순위(절정 단풍 > 절정 은행 > 첫 단풍 > 나머지)와 그 이름이 나오기 시작하는 배율(처음 화면 대비)
const pri = (m: Spot) => (m.stage === 'peak' ? (m.kind === 'maple' ? 0 : 1) : m.stage === 'first' ? 2 : 3);
const LABEL_FROM = [1, 1.6, 2.5, 3.5];
// 점이 나오기 시작하는 배율: 처음엔 절정 잎만 보여 차분하게
const DOT_FROM: Record<Stage, number> = { peak: 1, first: 1.6, before: 2.5, gone: 2.5 };
const ZOOM_BTNS = [
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const;
export type FoliageMapHandle = { focus: (m: Spot) => void };
type Props = { spots: Spot[]; sel: string | null; onSelect: (name: string | null) => void; height: number; ref?: Ref<FoliageMapHandle> };
/**
* 단풍 지도 페이지의 지도: 두 손가락으로 확대·이동, 한 손가락으로 이동, 누르면 가까운 명소 고르기, 두 번 누르면 확대 (웹 FoliagePage 지도).
* 앱은 지도를 스크롤 밖에 고정해 손짓이 페이지 스크롤과 다투지 않는다
*/
export function FoliageMap({ spots, sel, onSelect, height, ref }: Props) {
const vpRef = useRef<View>(null);
const origin = useRef({ x: 0, y: 0 });
const [box, setBox] = useState({ W: 0, H: 0 });
const [view, setView] = useState<Cam>({ s: 1, tx: 0, ty: 0 });
const viewRef = useRef(view);
useLayoutEffect(() => {
viewRef.current = view;
}, [view]);
const [size, measure] = useLabelSizes();
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<Cam>(() => {
const { W, H } = box;
if (!W || !spots.length) return { s: 1, tx: 0, ty: 0 };
const xs = spots.map((m) => m.x);
const ys = spots.map((m) => m.y);
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
// 위쪽은 맨 북쪽 이름표가 잘리지 않게 FIT_TOP 만큼 띄우고, 아래는 제주까지만
const h = H - FIT_TOP - FIT_BOTTOM;
// 가로는 땅 가운데(LAND_CX)에 맞추되 동·서 끝 명소가 다 들어오게
const half = Math.max(LAND_CX - x0, x1 - LAND_CX) + 0.07;
const s = Math.min(W / (2 * half * W), h / ((y1 - y0) * W));
return { s, tx: W / 2 - LAND_CX * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s };
}, [box, spots]);
const clamp = useCallback(
(v: Cam): Cam => {
const { W, H } = box;
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s));
const w = W * s;
// 지도 그림 가장자리가 화면 안쪽으로 너무 들어오지 않게
const tx = Math.min(W * 0.25, Math.max(W * 0.75 - w, v.tx));
const ty = Math.min(H * 0.25, Math.max(H * 0.75 - w, v.ty));
return { s, tx, ty };
},
[box, fit],
);
const anim = useRef(0);
const set = useCallback((v: Cam) => {
cancelAnimationFrame(anim.current);
setView(v);
}, []);
const animateTo = useCallback(
(to: Cam) => {
cancelAnimationFrame(anim.current);
const from = viewRef.current;
const target = clamp(to);
const start = performance.now();
const step = (now: number) => {
const k = Math.min(1, (now - start) / 280);
const e = 1 - (1 - k) ** 3;
setView({ s: from.s + (target.s - from.s) * e, tx: from.tx + (target.tx - from.tx) * e, ty: from.ty + (target.ty - from.ty) * e });
if (k < 1) anim.current = requestAnimationFrame(step);
};
anim.current = requestAnimationFrame(step);
},
[clamp],
);
const zoomAt = useCallback(
(f: number, cx: number, cy: number, smooth = false) => {
const v = viewRef.current;
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s * f));
const k = s / v.s;
const next = clamp({ s, tx: cx - (cx - v.tx) * k, ty: cy - (cy - v.ty) * k });
if (smooth) animateTo(next);
else set(next);
},
[fit, clamp, animateTo, set],
);
const focus = useCallback(
(m: Spot) => {
const { W, H } = box;
const s = Math.max(viewRef.current.s, fit.s * 2.5);
animateTo({ s, tx: W / 2 - m.x * W * s, ty: H * 0.42 - m.y * W * s });
},
[box, fit, animateTo],
);
useImperativeHandle(ref, () => ({ focus }), [focus]);
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로. 그 뒤 크기가 바뀌면 지금 화면을 범위 안으로
const started = useRef(false);
const linked = useRef(sel);
useEffect(() => {
if (!box.W) return;
if (started.current) {
set(clamp(viewRef.current));
return;
}
started.current = true;
set(fit);
const m = spots.find((s) => s.name === linked.current);
if (m) focus(m);
}, [box, fit, spots, set, clamp, focus]);
useEffect(() => () => cancelAnimationFrame(anim.current), []);
const pts = useMemo(() => {
const ratio = view.s / fit.s;
const visible = spots.filter((m) => m.name === sel || ratio >= DOT_FROM[m.stage] - 0.01);
return spread(visible.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: DOT_R[m.stage] })));
}, [spots, view, box.W, fit.s, sel]);
const ptsRef = useRef(pts);
useLayoutEffect(() => {
ptsRef.current = pts;
}, [pts]);
const labelAt = useMemo(() => {
const ratio = view.s / fit.s;
const order = pts.filter((p) => p.m.name === sel || ratio >= LABEL_FROM[pri(p.m)]).sort((a, b) => Number(b.m.name === sel) - Number(a.m.name === sel) || pri(a.m) - pri(b.m));
// 오른쪽 위 +/− 단추 자리는 비운다
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }];
return placeLabels(order, pts, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.stage === 'peak' || p.m.name === sel);
}, [pts, size, sel, view.s, fit.s, box]);
const provs = useMemo(
() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: view.tx + v.x * box.W * view.s, y: view.ty + v.y * box.W * view.s })), pts, labelBoxes(labelAt, size)),
[view, box.W, pts, labelAt, size],
);
// 손짓 상태: 두 손가락 거리·가운데, 한 손가락 시작점과 움직였는지, 마지막으로 누른 때(두 번 누르기)
const gesture = useRef<{ pinch: { d: number; x: number; y: number } | null; one: { x: number; y: number; moved: boolean } | null; lastTap: number }>({ pinch: null, one: null, lastTap: 0 });
const local = (t: { pageX: number; pageY: number }) => ({ x: t.pageX - origin.current.x, y: t.pageY - origin.current.y });
const pickAt = (x: number, y: number) => {
const best = nearest(ptsRef.current, x, y);
onSelect(best && best !== sel ? best : null);
};
const begin = (e: GestureResponderEvent) => {
const g = gesture.current;
const ts = e.nativeEvent.touches;
if (ts.length >= 2) {
const [a, b] = [local(ts[0]), local(ts[1])];
g.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
g.one = null;
} else if (ts.length === 1) {
g.pinch = null;
g.one = { ...local(ts[0]), moved: false };
}
};
const onGrant = (e: GestureResponderEvent) => {
cancelAnimationFrame(anim.current);
// 지도 칸의 화면 위치: 손가락 좌표(pageX)를 지도 안 좌표로 바꾸는 데 쓴다
vpRef.current?.measure((_x, _y, _w, _h, px, py) => {
origin.current = { x: px, y: py };
});
begin(e);
};
const onMove = (e: GestureResponderEvent) => {
const g = gesture.current;
const ts = e.nativeEvent.touches;
if (ts.length >= 2) {
if (!g.pinch) return begin(e);
const [a, b] = [local(ts[0]), local(ts[1])];
const d = Math.hypot(a.x - b.x, a.y - b.y);
const x = (a.x + b.x) / 2;
const y = (a.y + b.y) / 2;
const v = viewRef.current;
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, (v.s * d) / g.pinch.d));
const k = s / v.s;
set(clamp({ s, tx: x - (g.pinch.x - v.tx) * k, ty: y - (g.pinch.y - v.ty) * k }));
g.pinch = { d, x, y };
return;
}
// 두 손가락에서 한 손가락이 떨어지면 남은 손가락으로 이어서 이동 (누르기로는 안 친다)
if (!g.one || g.pinch) {
if (ts.length === 1) g.one = { ...local(ts[0]), moved: true };
g.pinch = null;
return;
}
const p = local(ts[0]);
if (Math.hypot(p.x - g.one.x, p.y - g.one.y) > 6) g.one.moved = true;
if (!g.one.moved) return;
const v = viewRef.current;
set(clamp({ s: v.s, tx: v.tx + p.x - g.one.x, ty: v.ty + p.y - g.one.y }));
g.one = { ...p, moved: true };
};
const onRelease = (e: GestureResponderEvent) => {
const g = gesture.current;
const tap = g.one && !g.one.moved ? g.one : null;
g.one = null;
g.pinch = null;
if (!tap) return;
// 두 번 누르기: 300ms 안에 또 누르면 확대
if (e.nativeEvent.timestamp - g.lastTap < 300) {
g.lastTap = 0;
zoomAt(2, tap.x, tap.y, true);
} else {
g.lastTap = e.nativeEvent.timestamp;
pickAt(tap.x, tap.y);
}
};
const onEnd = () => {
gesture.current.one = null;
gesture.current.pinch = null;
};
const onLayout = (e: LayoutChangeEvent) => {
const { width, height: h } = e.nativeEvent.layout;
setBox({ W: width, H: h });
vpRef.current?.measure((_x, _y, _w, _h, px, py) => {
origin.current = { x: px, y: py };
});
};
const markers = [...pts].sort((a, b) => Number(a.m.stage === 'peak') - Number(b.m.stage === 'peak'));
return (
<View
ref={vpRef}
onLayout={onLayout}
onStartShouldSetResponder={() => true}
onMoveShouldSetResponder={() => true}
onResponderTerminationRequest={() => false}
onResponderGrant={onGrant}
onResponderMove={onMove}
onResponderRelease={onRelease}
onResponderTerminate={onEnd}
className="overflow-hidden"
style={{ height, backgroundColor: PAPER }}
accessibilityLabel="단풍 지도"
>
{box.W > 0 ? <MapImage style={{ left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} /> : null}
{provs.map((v) => (
<Province key={v.name} name={v.name} x={v.x} y={v.y} />
))}
{markers.map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<Label key={m.name} m={m} at={labelAt[m.name]} sel={m.name === sel} onPress={() => onSelect(m.name === sel ? null : m.name)} onLayout={measure(m.name)} accessibilityLabel={`${m.name} 고르기`} />
))}
<View className="absolute top-2.5 right-2.5 gap-2" style={{ zIndex: 4 }}>
{ZOOM_BTNS.map(([t, label, f]) => (
<Pressable key={t} onPress={() => zoomAt(f, box.W / 2, box.H / 2, true)} accessibilityRole="button" accessibilityLabel={label} className="size-9 items-center justify-center rounded-full bg-white" style={{ boxShadow: '0 2px 6px rgba(40,48,74,0.2)' }}>
<Text className="text-[20px] leading-6 font-bold" style={{ color: MAP_INK }}>
{t}
</Text>
</Pressable>
))}
</View>
</View>
);
}