feat: 계절 지도 자리에 첫눈 지도·해돋이 지도 — 단풍 지도가 끝나면 첫눈 지도(~12/20, 지점 42곳 평년 첫눈 날짜 + 앞으로 7일 눈 예보, GET /v1/season/first-snow), 12/21부터 해돋이 지도(~2월, 명소 50곳 해 뜨는 시각, 12월엔 새해 첫날 기준). 오늘 탭 아이콘·피드 맨 앞 카드(foliage_post 좋아요·댓글 자리를 이어받음)·/first-snow·/sunrise 페이지·공유 이미지. 지도 확대·이동은 mapView.ts 로 꺼내 단풍 지도와 같이 씀 (GA first_snow_open·first_snow_spot·sunrise_open·sunrise_spot·sunrise_day)

This commit is contained in:
skkim committed 2026-11-20 11:18:54 +09:00
1 parent 4e69c4ac44
commit d7dfc1ba82
30 files changed
+1973 -255

No files matched your search

+16
View File
@@ -42,3 +42,19 @@ class Res_ArticleList(Res_WebPacketProtocol):
class Res_Article(Res_WebPacketProtocol):
article: Optional[ArticleSummary] = None
body: list[str] = []
class FirstSnowSpot(WebPacketProtocol):
name: str
region: str # 시·도
lat: float
lon: float
normal: str # 평년 첫눈 날짜 "MM-DD" (1991~2020 평균)
top: bool = False # 처음 화면에 이름까지 보이는 대표 지점
snow_date: Optional[date] = None # 앞으로 7일 안에 눈 예보가 있는 첫 날. 없으면 비움
snow_cm: Optional[float] = None # 그날 눈 오는 양(cm)
class Res_FirstSnow(Res_WebPacketProtocol):
forecast: bool = False # 눈 예보를 받았는지. False 면 snow_date 는 모두 비어 있다(평년 날짜만)
spots: list[FirstSnowSpot] = []
+9 -1
View File
@@ -5,7 +5,9 @@ from fastapi import APIRouter, Depends, Path, Query
from common.database.model.models import Article
from common.enums import ArticleCategory, ErrorType
from common.models.errors import error_info
from router.v1.season.protocol import ArticleSummary, Res_Article, Res_ArticleList, Res_SeasonWeek, TermData
from common.utils.kma_time import now_kst
from router.v1.season.protocol import ArticleSummary, FirstSnowSpot, Res_Article, Res_ArticleList, Res_FirstSnow, Res_SeasonWeek, TermData
from services.first_snow_service import FirstSnowService
from services.season_service import SeasonService
router = APIRouter(prefix="/v1/season", tags=["season"])
@@ -44,3 +46,9 @@ async def get_article(article_id: int = Path(...), service: SeasonService = Depe
if err is not ErrorType.SUCCESS:
return Res_Article(result=error_info(err))
return Res_Article(article=_summary(a), body=a.body)
@router.get("/first-snow", response_model=Res_FirstSnow, response_model_exclude_none=True, summary="첫눈 지도: 지점별 평년 첫눈 날짜와 앞으로 7일 눈 예보")
async def get_first_snow(service: FirstSnowService = Depends()) -> Res_FirstSnow:
forecast, spots = await service.spots(now_kst())
return Res_FirstSnow(forecast=forecast, spots=[FirstSnowSpot(**s.__dict__) for s in spots])
+27 -1
View File
@@ -1,5 +1,5 @@
import asyncio
from datetime import datetime, timedelta, timezone
from datetime import date, datetime, timedelta, timezone
import httpx
@@ -87,6 +87,32 @@ async def _fetch_weather_chunk(client: httpx.AsyncClient, points: list[tuple[flo
return await _get_forecast(client, params, len(points))
async def fetch_snow(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 7) -> list[dict]:
"""좌표마다 날짜별(한국 날짜) 눈 오는 양 (모델 지정 없음). 응답 순서는 좌표 순서와 같다."""
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
async def all_chunks() -> list[dict]:
results = await asyncio.gather(*[_fetch_snow_chunk(client, c, days) for c in chunks])
return [d for r in results for d in r]
return await guarded("openmeteo:snow", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
async def _fetch_snow_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
params = {
"latitude": ",".join(f"{lat:.2f}" for lat, _ in points),
"longitude": ",".join(f"{lon:.2f}" for _, lon in points),
"daily": "snowfall_sum", "forecast_days": days, "timezone": "Asia/Seoul",
}
return await _get_forecast(client, params, len(points))
def parse_snow(data: dict) -> list[tuple[date, float]]:
"""날짜별 눈 오는 양(cm). 값이 없는 날은 뺀다."""
d = data["daily"]
return [(date.fromisoformat(t), float(v)) for t, v in zip(d["time"], d["snowfall_sum"]) if v is not None]
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
lat, lon = round(point[0], 2), round(point[1], 2)
h = data["hourly"]
+48
View File
@@ -0,0 +1,48 @@
{
"source": "기상청 「계절관측지침(2026.4.)」 부록 기후계절 평년값(1991~2020년) 첫눈. 북춘천은 춘천, 북강릉은 강릉으로 적음. 먼 섬(백령도·울릉도·흑산도)과 평년 첫눈이 해를 넘기는 거제(1/14)는 뺌",
"basis": "normal 은 평년 첫눈 날짜(월-일). lat·lon 은 그 도시의 대략 위치(지도에 찍고 눈 예보를 받는 자리). top 은 처음 화면에 이름까지 보이는 대표 지점",
"spots": [
{ "name": "서울", "region": "서울", "lat": 37.57, "lon": 126.97, "normal": "11-20", "top": true },
{ "name": "인천", "region": "인천", "lat": 37.48, "lon": 126.62, "normal": "11-23" },
{ "name": "수원", "region": "경기", "lat": 37.27, "lon": 126.99, "normal": "11-21" },
{ "name": "파주", "region": "경기", "lat": 37.89, "lon": 126.77, "normal": "11-20" },
{ "name": "이천", "region": "경기", "lat": 37.26, "lon": 127.48, "normal": "11-20" },
{ "name": "철원", "region": "강원", "lat": 38.15, "lon": 127.3, "normal": "11-18" },
{ "name": "춘천", "region": "강원", "lat": 37.95, "lon": 127.75, "normal": "11-21", "top": true },
{ "name": "원주", "region": "강원", "lat": 37.34, "lon": 127.95, "normal": "11-21" },
{ "name": "대관령", "region": "강원", "lat": 37.68, "lon": 128.72, "normal": "11-05", "top": true },
{ "name": "속초", "region": "강원", "lat": 38.25, "lon": 128.56, "normal": "12-10" },
{ "name": "강릉", "region": "강원", "lat": 37.8, "lon": 128.86, "normal": "12-07", "top": true },
{ "name": "동해", "region": "강원", "lat": 37.51, "lon": 129.12, "normal": "12-11" },
{ "name": "태백", "region": "강원", "lat": 37.17, "lon": 128.99, "normal": "11-10" },
{ "name": "서산", "region": "충남", "lat": 36.78, "lon": 126.49, "normal": "11-20" },
{ "name": "천안", "region": "충남", "lat": 36.78, "lon": 127.12, "normal": "11-19" },
{ "name": "보령", "region": "충남", "lat": 36.33, "lon": 126.56, "normal": "11-22" },
{ "name": "청주", "region": "충북", "lat": 36.64, "lon": 127.44, "normal": "11-23" },
{ "name": "충주", "region": "충북", "lat": 36.97, "lon": 127.95, "normal": "11-24" },
{ "name": "추풍령", "region": "충북", "lat": 36.22, "lon": 127.99, "normal": "11-17" },
{ "name": "대전", "region": "대전", "lat": 36.37, "lon": 127.37, "normal": "11-20", "top": true },
{ "name": "전주", "region": "전북", "lat": 35.82, "lon": 127.15, "normal": "11-29", "top": true },
{ "name": "군산", "region": "전북", "lat": 36.0, "lon": 126.76, "normal": "11-26" },
{ "name": "남원", "region": "전북", "lat": 35.41, "lon": 127.33, "normal": "11-24" },
{ "name": "광주", "region": "광주", "lat": 35.17, "lon": 126.89, "normal": "11-29", "top": true },
{ "name": "목포", "region": "전남", "lat": 34.82, "lon": 126.38, "normal": "11-29" },
{ "name": "순천", "region": "전남", "lat": 35.02, "lon": 127.37, "normal": "11-24" },
{ "name": "여수", "region": "전남", "lat": 34.74, "lon": 127.74, "normal": "12-13" },
{ "name": "완도", "region": "전남", "lat": 34.4, "lon": 126.7, "normal": "12-08" },
{ "name": "안동", "region": "경북", "lat": 36.57, "lon": 128.71, "normal": "11-29" },
{ "name": "구미", "region": "경북", "lat": 36.13, "lon": 128.32, "normal": "11-30" },
{ "name": "울진", "region": "경북", "lat": 36.99, "lon": 129.41, "normal": "12-09" },
{ "name": "포항", "region": "경북", "lat": 36.03, "lon": 129.38, "normal": "12-18" },
{ "name": "대구", "region": "대구", "lat": 35.88, "lon": 128.62, "normal": "12-05", "top": true },
{ "name": "거창", "region": "경남", "lat": 35.67, "lon": 127.91, "normal": "12-13" },
{ "name": "진주", "region": "경남", "lat": 35.16, "lon": 128.04, "normal": "12-18" },
{ "name": "창원", "region": "경남", "lat": 35.17, "lon": 128.57, "normal": "12-27" },
{ "name": "통영", "region": "경남", "lat": 34.85, "lon": 128.44, "normal": "12-27" },
{ "name": "울산", "region": "울산", "lat": 35.56, "lon": 129.32, "normal": "12-24" },
{ "name": "부산", "region": "부산", "lat": 35.1, "lon": 129.03, "normal": "12-23", "top": true },
{ "name": "제주", "region": "제주", "lat": 33.51, "lon": 126.53, "normal": "12-10", "top": true },
{ "name": "서귀포", "region": "제주", "lat": 33.25, "lon": 126.57, "normal": "12-20" },
{ "name": "성산", "region": "제주", "lat": 33.39, "lon": 126.88, "normal": "12-13" }
]
}
+76
View File
@@ -0,0 +1,76 @@
import json
from dataclasses import dataclass
from datetime import date, datetime
from pathlib import Path
from typing import Optional
import httpx
from redis.exceptions import RedisError
from common.cache.redis_client import REDIS
from common.logger import LOG
from common.utils.kma_time import KST
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_snow, parse_snow
# 지점별 평년 첫눈 날짜 (기상청 계절관측지침, 1991~2020). 출처·기준은 파일 안에 적혀 있다
SPOTS: list[dict] = json.loads((Path(__file__).parent / "first_snow.json").read_text(encoding="utf-8"))["spots"]
_DAYS = 7
# 하루 눈 오는 양이 이만큼(cm)은 돼야 '눈 예보'로 친다 (0 에 가까운 값은 뺀다)
_MIN_CM = 0.1
# 눈 예보는 3시간에 한 번만 받는다. 첫 사용자가 볼 때 받아 Redis 에 둔다
_KEY = "firstsnow:forecast"
_TTL_SEC = 3 * 3600
@dataclass
class SnowSpot:
name: str
region: str
lat: float
lon: float
normal: str
top: bool
snow_date: Optional[date] = None
snow_cm: Optional[float] = None
def first_snow_day(days: list[tuple[date, float]], today: date) -> Optional[tuple[date, float]]:
"""오늘부터 눈 예보가 있는 첫 날과 그날 양. 없으면 None."""
return next(((d, cm) for d, cm in sorted(days) if d >= today and cm >= _MIN_CM), None)
class FirstSnowService:
async def spots(self, now: datetime) -> tuple[bool, list[SnowSpot]]:
"""(눈 예보를 받았는지, 지점 목록). 예보를 못 받아도 평년 날짜는 돌려준다."""
forecast = await self._forecast()
today = now.astimezone(KST).date()
out = []
for s in SPOTS:
hit = first_snow_day(forecast[s["name"]], today) if forecast and s["name"] in forecast else None
out.append(SnowSpot(
name=s["name"], region=s["region"], lat=s["lat"], lon=s["lon"], normal=s["normal"], top=bool(s.get("top")),
snow_date=hit[0] if hit else None, snow_cm=round(hit[1], 1) if hit else None,
))
return forecast is not None, out
async def _forecast(self) -> Optional[dict[str, list[tuple[date, float]]]]:
"""지점 이름 → 날짜별 눈 오는 양. Redis 에 있으면 그것을, 없으면 Open-Meteo 에서 받아 둔다. 못 받으면 None."""
try:
cached = await REDIS.conn.get(_KEY)
if cached:
return {name: [(date.fromisoformat(d), cm) for d, cm in days] for name, days in json.loads(cached).items()}
except RedisError as e:
LOG.error(f"[first_snow] cache read: {e}")
try:
async with httpx.AsyncClient(timeout=10) as client:
data = await fetch_snow(client, [(s["lat"], s["lon"]) for s in SPOTS], _DAYS)
except OpenMeteoRequestFailed as e:
LOG.error(f"[first_snow] {e}")
return None
forecast = {s["name"]: parse_snow(d) for s, d in zip(SPOTS, data)}
try:
await REDIS.conn.set(_KEY, json.dumps({name: [[d.isoformat(), cm] for d, cm in days] for name, days in forecast.items()}), ex=_TTL_SEC)
except RedisError as e:
LOG.error(f"[first_snow] cache write: {e}")
return forecast
+70
View File
@@ -0,0 +1,70 @@
from datetime import date, timedelta
import pytest
from httpx import ASGITransport, AsyncClient
import services.first_snow_service as first_snow_service
from common.utils.kma_time import now_kst
from router.router import app
from services.external.open_meteo import OpenMeteoRequestFailed, parse_snow
from services.first_snow_service import SPOTS, first_snow_day
def _daily(start: date, cms: list) -> dict:
return {"daily": {"time": [(start + timedelta(days=i)).isoformat() for i in range(len(cms))], "snowfall_sum": cms}}
def test_parse_snow_skips_days_without_value():
rows = parse_snow(_daily(date(2026, 11, 20), [0.0, None, 1.4]))
assert rows == [(date(2026, 11, 20), 0.0), (date(2026, 11, 22), 1.4)]
def test_first_snow_day_is_first_day_from_today_with_enough_snow():
today = date(2026, 11, 22)
days = [(date(2026, 11, 21), 3.0), (date(2026, 11, 22), 0.05), (date(2026, 11, 24), 0.7), (date(2026, 11, 25), 2.0)]
assert first_snow_day(days, today) == (date(2026, 11, 24), 0.7) # 어제 눈과 0에 가까운 값은 뺀다
assert first_snow_day([(date(2026, 11, 23), 0.0)], today) is None
def test_spot_data_has_normal_dates_and_unique_names():
names = [s["name"] for s in SPOTS]
assert len(names) == len(set(names)) and len(names) >= 40
for s in SPOTS:
month, day = map(int, s["normal"].split("-"))
assert month in (11, 12) and 1 <= day <= 31
assert 33 <= s["lat"] <= 39 and 125 <= s["lon"] <= 130
@pytest.mark.anyio
async def test_first_snow_api_marks_spots_with_snow_forecast(monkeypatch):
today = now_kst().date()
calls = []
async def fake_fetch(client, points, days):
calls.append(len(points))
# 첫 지점만 모레 눈, 나머지는 눈 없음
return [_daily(today, [0.0, 0.0, 1.2, 0.0] if i == 0 else [0.0] * 4) for i in range(len(points))]
monkeypatch.setattr(first_snow_service, "fetch_snow", fake_fetch)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/season/first-snow")).json()
again = (await client.get("/v1/season/first-snow")).json()
assert body["result"]["success"] is True and body["forecast"] is True
assert len(body["spots"]) == len(SPOTS)
first = body["spots"][0]
assert first["name"] == SPOTS[0]["name"] and first["normal"] == SPOTS[0]["normal"]
assert first["snow_date"] == (today + timedelta(days=2)).isoformat() and first["snow_cm"] == 1.2
assert all("snow_date" not in s for s in body["spots"][1:])
assert again == body and calls == [len(SPOTS)] # 두 번째는 Redis 에 둔 예보를 쓴다
@pytest.mark.anyio
async def test_first_snow_api_returns_normal_dates_when_forecast_fails(monkeypatch):
async def failing_fetch(client, points, days):
raise OpenMeteoRequestFailed("down")
monkeypatch.setattr(first_snow_service, "fetch_snow", failing_fetch)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/season/first-snow")).json()
assert body["result"]["success"] is True and body["forecast"] is False
assert len(body["spots"]) == len(SPOTS) and all("snow_date" not in s for s in body["spots"])
+7 -2
View File
@@ -39,7 +39,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
| `앱_연결_오류` (코드 `app_bridge_error`) | 앱 안에서 웹이 앱에 시킨 일이 실패함 (사용자가 구글 계정창·공유창을 닫거나 위치 권한을 거부한 것은 안 보냄) | `action: 'google_login' \| 'share' \| 'location'` | `googleLogin.tsx` `AppGoogleButton`, `Sheets.tsx` `ShareSheet` `send`, `region.tsx` `findNearest` |
| `첫화면_멈춤` (코드 `boot_stuck`) | 8초 넘게 '날씨 불러오는 중' 첫 화면이 남음 (페이지마다 한 번) | `reason`(첫 오류 문구, 100자), `seconds`, `tries`(연달아 다시 불러온 횟수), `app_started`(앱 파일 실행 여부) | `index.html` 첫 화면 스크립트 |
| `창_열기` (코드 `sheet_open`) | 아래에서 올라오는 창이 열림 (각·글·보내기·댓글·로그인·내 정보·지역·내 각·홈 화면 추가·점수 근거·이야기 등) | `sheet`(창 종류: `gak`·`article`·`share`·`comments`·`login`·`me`·`region`·`mix`·`myGak`·`install`·`weatherWhy`·`talk`·`seasonWeek`·`contact`) | `Sheets.tsx` `SheetProvider` `open` |
| `좋아요` (코드 `like`) | 좋아요 성공 (취소는 안 보냄) | `content_type: 'post' \| 'comment' \| 'talk' \| 'hero_post' \| 'gak_post' \| 'foliage_post' \| 'events_post' \| 'season_post'`, `item_id`(포스트·댓글·글 번호) | `Post.tsx` `FullCard`, `pinnedLike.ts`, `Sheets.tsx` `CommentRow`, `talk.tsx` |
| `좋아요` (코드 `like`) | 좋아요 성공 (취소는 안 보냄) | `content_type: 'post' \| 'comment' \| 'talk' \| 'hero_post' \| 'gak_post' \| 'foliage_post' \| 'events_post' \| 'season_post'`, `item_id`(포스트·댓글·글 번호). `foliage_post`는 계절 지도 카드 자리라 단풍 지도가 끝나면 첫눈 지도 카드(~12/20), 그 뒤 해돋이 지도 카드(~2월)의 좋아요가 이 값으로 찍힌다 | `Post.tsx` `FullCard`, `pinnedLike.ts`, `Sheets.tsx` `CommentRow`, `talk.tsx` |
| `댓글` (코드 `comment`) | 댓글 올리기 성공 | `post_id` | `Sheets.tsx` `CommentsSheet` `send` |
| `이야기_댓글` (코드 `talk_comment`) | 사람 글에 댓글 올리기 성공 (로그인한 사람만) | `talk_id`(글 번호) | `Sheets.tsx` `CommentsSheet` `send` |
| `약관_동의` (코드 `terms_agree`) | 댓글 쓰기 전 이용약관 동의 성공 | 없음 | `Sheets.tsx` `CommentsSheet` `agreeAndSend` |
@@ -57,6 +57,11 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
| `쇼츠_미리보기` (코드 `shorts_preview`) | 오늘 화면 쇼츠 줄 카드가 소리 없이 재생을 시작함 (카드마다 한 번. 웹만) | `video_id`, `trigger: 'hover' \| 'auto'`(데스크톱에서 마우스를 올림·터치 기기에서 첫 터치 뒤 첫 카드 자동) | `Shorts.tsx` `ShortCard` |
| `단풍지도_열기` (코드 `foliage_open`) | 단풍 지도 페이지(/foliage)를 엶 | 없음 | `FoliagePage.tsx` |
| `단풍명소_보기` (코드 `foliage_spot`) | 단풍 명소를 고름 | `spot_name`, `from: 'page' \| 'card'`(지도 페이지·오늘 화면 카드) | `FoliagePage.tsx`, `foliageMap.tsx` |
| `첫눈지도_열기` (코드 `first_snow_open`) | 첫눈 지도 페이지(/first-snow)를 엶 | 없음 | `FirstSnowPage.tsx` |
| `첫눈지점_보기` (코드 `first_snow_spot`) | 첫눈 지도에서 지점을 고름 | `spot_name`, `from: 'page' \| 'card'`(지도 페이지·오늘 화면 카드) | `FirstSnowPage.tsx`, `firstSnowMap.tsx` |
| `해돋이지도_열기` (코드 `sunrise_open`) | 해돋이 지도 페이지(/sunrise)를 엶 | 없음 | `SunrisePage.tsx` |
| `해돋이명소_보기` (코드 `sunrise_spot`) | 해돋이 명소를 고름 | `spot_name`, `from: 'page' \| 'card'`(지도 페이지·오늘 화면 카드) | `SunrisePage.tsx`, `sunriseMap.tsx` |
| `해돋이날짜_전환` (코드 `sunrise_day`) | 해돋이 지도 페이지에서 날짜 칩을 바꿈 (12월에만 칩이 둘) | `day: 'newyear' \| 'next'`(새해 첫날·오늘/내일) | `SunrisePage.tsx` |
| `내각_저장` (코드 `my_gak_save`) | 내 각 만들기 성공 (로그인 전엔 기기에 저장) | `gak_name` | `myGakState.ts` `create` |
| `토스소개_시작` (코드 `toss_intro_start`) | 토스판 첫 소개 화면에서 '시작하기' | 없음 | `tossIntro.tsx` |
| `설치배너_닫기` (코드 `install_banner_close`) | '홈 화면에 추가' 띠를 × 로 닫음 | 없음 | `installBanner.tsx` |
@@ -64,7 +69,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
| `문의_누름` (코드 `contact_click`) | 문의 창에서 전화·이메일을 누름 (창 열림은 `창_열기`의 `sheet: 'contact'`) | `method: 'phone' \| 'email'` | `Sheets.tsx` `ContactSheet` |
| `타로_뽑기` (코드 `fortune_draw`) | 오늘 한 장에서 카드를 뽑음 (하루 한 번, 다시 열 때는 안 보냄) | `card`(각 코드) | `fortune.tsx` `useTodayCard` |
| `하루_기록` (코드 `day_log`) | 저녁 체크인을 적어 둠 (고쳐 적어도 보냄). 다녀온 곳 이름은 보내지 않음 | `mood`(1~5), `went_out`, `card_hit`(맞았어요 true·글쎄요 false·안 고름 null) | `fortune.tsx` `useTodayCard` |
| `오늘아이콘_누름` (코드 `today_icon`) | 오늘 탭 아이콘 줄에서 아이콘을 누름 | `icon`(`tarot`·`saju`·`game`·`foliage`·`shorts`·`myGak`·`talk`) | `todayIcons.tsx` `TodayIcons` |
| `오늘아이콘_누름` (코드 `today_icon`) | 오늘 탭 아이콘 줄에서 아이콘을 누름 | `icon`(`tarot`·`saju`·`game`·`foliage`·`firstSnow`·`sunrise`·`shorts`·`myGak`·`talk`) | `todayIcons.tsx` `TodayIcons` |
| `사주_입력` (코드 `saju_input`) | 날씨 사주 생년월일을 넣음 (생년월일 값은 보내지 않음) | `with_time` | `SajuPage.tsx` `BirthForm` |
| `사주_결과` (코드 `saju_view`) | 날씨 사주 결과가 뜸 | `scene`(내 기운 이름), `score`, `strength`(신강·중화·신약), `top_element`(가장 센 오행) | `SajuPage.tsx` `Reading` |
| `게임_시작` (코드 `game_start`) | 구름 합치기 한 판의 첫 그림을 떨어뜨림 (페이지만 열고 안 한 사람과 구분) | `again`(다시 하기로 시작), `logged_in`, `wind_ms`(오늘 우리 구 풍속), `theme`(그림: `basic`·`halloween`·`pepero`·`christmas`·`chuseok`·`suneung`·`newyear`, `holiday.ts`) | `CloudMergePage.tsx` `onUp` |
+4
View File
@@ -205,6 +205,10 @@
<p>같은 날씨끼리 합쳐 해를 만드는 구름 합치기 게임이에요. 우리 동네 지금 바람만큼 구름이 옆으로 밀려 떨어져요.</p>
<h2><a href="/foliage">단풍 지도</a></h2>
<p>산림청 단풍 절정 예측으로 전국 단풍 명소의 절정 시기를 지도에서 확인하세요.</p>
<h2><a href="/first-snow">첫눈 지도</a></h2>
<p>서울, 춘천, 대전, 광주, 대구, 부산, 제주 등 전국 지역별 평년 첫눈 날짜와 앞으로 7일 눈 예보를 지도에서 확인하세요.</p>
<h2><a href="/sunrise">해돋이 지도</a></h2>
<p>정동진, 호미곶, 간절곶, 성산일출봉 같은 전국 해돋이 명소의 새해 첫날 해 뜨는 시각을 지도에서 확인하세요.</p>
<h2><a href="/talk">동네 이야기</a></h2>
<p>지금 우리 동네 하늘과 노을, 비·눈, 단풍·꽃, 오늘 옷차림 이야기를 동네 사람들과 나눠요.</p>
<h2><a href="/shorts">날씨 쇼츠</a></h2>
+55
View File
@@ -0,0 +1,55 @@
{
"basis": "해 뜨는 시각은 좌표로 계산(shared/lib/sunrise.ts, 해발 0m 기준이라 높은 산 위에서는 몇 분 더 일찍 보인다). top 은 처음 화면에 이름까지 보이는 대표 명소. src 가 tourapi 면 backend/seed 의 관광공사 좌표, manual 이면 직접 넣은 좌표",
"spots": [
{ "name": "정동진", "coast": "east", "region": "강원 강릉", "lat": 37.69136, "lon": 129.03257, "top": true, "src": "tourapi" },
{ "name": "경포해변", "coast": "east", "region": "강원 강릉", "lat": 37.80341, "lon": 128.91021, "src": "tourapi" },
{ "name": "낙산사", "coast": "east", "region": "강원 양양", "lat": 38.1247, "lon": 128.6281, "top": true, "src": "manual" },
{ "name": "하조대", "coast": "east", "region": "강원 양양", "lat": 38.02299, "lon": 128.72427, "src": "tourapi" },
{ "name": "속초해변", "coast": "east", "region": "강원 속초", "lat": 38.19055, "lon": 128.60193, "src": "tourapi" },
{ "name": "화진포", "coast": "east", "region": "강원 고성", "lat": 38.47838, "lon": 128.43938, "src": "tourapi" },
{ "name": "추암 촛대바위", "coast": "east", "region": "강원 동해", "lat": 37.47946, "lon": 129.16024, "top": true, "src": "tourapi" },
{ "name": "망상해변", "coast": "east", "region": "강원 동해", "lat": 37.59221, "lon": 129.08964, "src": "tourapi" },
{ "name": "망양정", "coast": "east", "region": "경북 울진", "lat": 36.96872, "lon": 129.41251, "src": "tourapi" },
{ "name": "영덕 해맞이공원", "coast": "east", "region": "경북 영덕", "lat": 36.4397, "lon": 129.4395, "src": "manual" },
{ "name": "호미곶", "coast": "east", "region": "경북 포항", "lat": 36.0766, "lon": 129.5668, "top": true, "src": "manual" },
{ "name": "문무대왕릉", "coast": "east", "region": "경북 경주", "lat": 35.73968, "lon": 129.48349, "src": "tourapi" },
{ "name": "대왕암공원", "coast": "east", "region": "울산 동구", "lat": 35.49046, "lon": 129.43527, "src": "tourapi" },
{ "name": "간절곶", "coast": "east", "region": "울산 울주", "lat": 35.3594, "lon": 129.3605, "top": true, "src": "manual" },
{ "name": "해동용궁사", "coast": "east", "region": "부산 기장", "lat": 35.1884, "lon": 129.2233, "src": "manual" },
{ "name": "송정해변", "coast": "east", "region": "부산 해운대", "lat": 35.17873, "lon": 129.19972, "src": "tourapi" },
{ "name": "해운대", "coast": "east", "region": "부산 해운대", "lat": 35.15908, "lon": 129.16028, "top": true, "src": "tourapi" },
{ "name": "광안리", "coast": "east", "region": "부산 수영", "lat": 35.15319, "lon": 129.11898, "src": "tourapi" },
{ "name": "오륙도 스카이워크", "coast": "east", "region": "부산 남구", "lat": 35.1006, "lon": 129.1244, "src": "tourapi" },
{ "name": "태종대", "coast": "east", "region": "부산 영도", "lat": 35.0528, "lon": 129.0857, "src": "manual" },
{ "name": "향일암", "coast": "south", "region": "전남 여수", "lat": 34.5914, "lon": 127.8032, "top": true, "src": "manual" },
{ "name": "오동도", "coast": "south", "region": "전남 여수", "lat": 34.7445, "lon": 127.7663, "src": "manual" },
{ "name": "보리암", "coast": "south", "region": "경남 남해", "lat": 34.7534, "lon": 127.9826, "src": "manual" },
{ "name": "이순신공원", "coast": "south", "region": "경남 통영", "lat": 34.8405, "lon": 128.4405, "src": "manual" },
{ "name": "정남진 전망대", "coast": "south", "region": "전남 장흥", "lat": 34.51169, "lon": 126.97464, "src": "tourapi" },
{ "name": "완도타워", "coast": "south", "region": "전남 완도", "lat": 34.31029, "lon": 126.76628, "src": "tourapi" },
{ "name": "땅끝전망대", "coast": "south", "region": "전남 해남", "lat": 34.29471, "lon": 126.52504, "top": true, "src": "tourapi" },
{ "name": "성산일출봉", "coast": "south", "region": "제주 서귀포", "lat": 33.4581, "lon": 126.9426, "top": true, "src": "manual" },
{ "name": "함덕 서우봉", "coast": "south", "region": "제주 제주", "lat": 33.5439, "lon": 126.66836, "src": "tourapi" },
{ "name": "한라산 백록담", "coast": "south", "region": "제주", "lat": 33.3617, "lon": 126.5292, "src": "manual" },
{ "name": "왜목마을", "coast": "west", "region": "충남 당진", "lat": 37.04448, "lon": 126.52614, "top": true, "src": "tourapi" },
{ "name": "마량포구", "coast": "west", "region": "충남 서천", "lat": 36.12915, "lon": 126.50501, "src": "tourapi" },
{ "name": "거잠포", "coast": "west", "region": "인천 영종", "lat": 37.42213, "lon": 126.42545, "src": "tourapi" },
{ "name": "마니산", "coast": "west", "region": "인천 강화", "lat": 37.6126, "lon": 126.4336, "src": "manual" },
{ "name": "남산", "coast": "inland", "region": "서울 중구", "lat": 37.55105, "lon": 126.98788, "top": true, "src": "tourapi" },
{ "name": "아차산", "coast": "inland", "region": "서울 광진", "lat": 37.5546, "lon": 127.1009, "src": "manual" },
{ "name": "하늘공원", "coast": "inland", "region": "서울 마포", "lat": 37.5691, "lon": 126.88634, "src": "tourapi" },
{ "name": "인왕산", "coast": "inland", "region": "서울 종로", "lat": 37.58401, "lon": 126.96397, "src": "tourapi" },
{ "name": "남한산성", "coast": "inland", "region": "경기 광주", "lat": 37.4781, "lon": 127.184, "src": "tourapi" },
{ "name": "두물머리", "coast": "inland", "region": "경기 양평", "lat": 37.533, "lon": 127.314, "src": "manual" },
{ "name": "수원화성 서장대", "coast": "inland", "region": "경기 수원", "lat": 37.2797, "lon": 127.0095, "src": "manual" },
{ "name": "설악산 대청봉", "coast": "inland", "region": "강원 양양·속초", "lat": 38.1191, "lon": 128.4654, "src": "manual" },
{ "name": "태백산 천제단", "coast": "inland", "region": "강원 태백", "lat": 37.0957, "lon": 128.915, "src": "manual" },
{ "name": "소백산 비로봉", "coast": "inland", "region": "충북 단양·경북 영주", "lat": 36.9575, "lon": 128.4848, "src": "manual" },
{ "name": "덕유산 향적봉", "coast": "inland", "region": "전북 무주", "lat": 35.8597, "lon": 127.7464, "src": "manual" },
{ "name": "지리산 천왕봉", "coast": "inland", "region": "경남 산청·함양", "lat": 35.337, "lon": 127.7306, "top": true, "src": "manual" },
{ "name": "무등산 서석대", "coast": "inland", "region": "광주 동구", "lat": 35.1293, "lon": 126.989, "src": "manual" },
{ "name": "앞산전망대", "coast": "inland", "region": "대구 남구", "lat": 35.82436, "lon": 128.58714, "src": "tourapi" },
{ "name": "식장산", "coast": "inland", "region": "대전 동구", "lat": 36.3037, "lon": 127.4846, "src": "manual" },
{ "name": "옥정호 국사봉", "coast": "inland", "region": "전북 임실", "lat": 35.64272, "lon": 127.14646, "src": "tourapi" }
]
}
+4
View File
@@ -1,12 +1,14 @@
import { BrowserRouter, Route, Routes } from 'react-router'
import { BLayout } from './b/BLayout'
import { CloudMergePage } from './b/CloudMergePage'
import { FirstSnowPage } from './b/FirstSnowPage'
import { FoliagePage } from './b/FoliagePage'
import { SajuPage } from './b/SajuPage'
import { GakPage } from './b/GakPage'
import { SeasonPage } from './b/SeasonPage'
import { ShortsPage } from './b/Shorts'
import { SkyPage } from './b/SkyPage'
import { SunrisePage } from './b/SunrisePage'
import { TalkPage } from './b/TalkPage'
import { TodayPage } from './b/TodayPage'
import { WeekPage } from './b/WeekPage'
@@ -24,6 +26,8 @@ export default function App() {
<Route path="week" element={<WeekPage />} />
<Route path="season" element={<SeasonPage />} />
<Route path="foliage" element={<FoliagePage />} />
<Route path="first-snow" element={<FirstSnowPage />} />
<Route path="sunrise" element={<SunrisePage />} />
<Route path="saju" element={<SajuPage />} />
<Route path="talk" element={<TalkPage />} />
<Route path="shorts/:id?" element={<ShortsPage />} />
+260
View File
@@ -0,0 +1,260 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { firstSnowHeadline, SNOW_DOT, SNOW_LABEL_INK, SNOW_MAP_IMG, SNOW_PAPER, SNOW_SHADOW, SNOW_STAGE, snowSoon, useFirstSnow, type SnowSpot, type SnowStage } from './firstSnow'
import { ICON_R, LABEL, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, md, placeLabels, placeProvinces, spread, useLabelSize, type Box, type Pt } from './foliage'
import { useMapView } from './mapView'
import { useSheet } from './sheetContext'
import { FirstSnowMapShare, FirstSnowSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Ic, StateBox, TAP44 } from './ui'
import { track } from '../lib/analytics'
const DOT_R = 4
// 눈 예보도 없고 대표 지점도 아닌 곳의 이름이 나오기 시작하는 배율(처음 화면 대비): 처음엔 차분하게
const LABEL_FROM = 2.2
const TAP_R = 24
const SHARE_ICON = 'relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-(--ink2) [&_svg]:stroke-[1.9]'
const SHARE_BTN = `${SHARE_ICON} bg-white/80`
const GROUPS: [SnowStage, string][] = [
['soon', '눈 예보가 있는 곳'],
['before', '평년 첫눈이 다가오는 곳'],
['passed', '평년 첫눈이 지난 곳'],
]
const BADGE: Record<SnowStage, string> = { soon: 'bg-[#dcebff] text-[#1f5fae]', before: 'bg-(--chip) text-(--ink2)', passed: 'bg-(--chip) text-(--ink2)' }
/** 눈 오는 양을 말로: 1cm 가 안 되면 '조금' */
const amount = (cm: number | null) => (cm && cm >= 1 ? `${Math.round(cm)}cm 안팎` : '조금')
/** 지도·목록에 크게 적는 날짜: 눈 예보가 있으면 그날, 없으면 평년 첫눈 날짜 */
const day = (m: SnowSpot) => md(m.snowDate ?? m.normal)
// 눈 예보가 있는 곳은 눈송이, 나머지는 점(평년 첫눈 전은 하늘색, 지난 곳은 회색. 고르면 점을 크게)
function SnowMark({ m, big }: { m: SnowSpot; big?: boolean }) {
if (m.stage === 'soon') return <Ic name="snow" className={cx('relative', big ? 'size-8' : 'size-5', SNOW_SHADOW)} />
return <i className={cx('relative', SNOW_DOT[m.stage], big ? 'size-3.5' : 'size-[7px]')} />
}
function Marker({ p, sel }: { p: Pt<SnowSpot>; sel: boolean }) {
return (
<span className={cx('pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center', sel && 'z-[3]')} style={{ left: p.x, top: p.y }}>
{/* 고른 지점은 속이 빈 고리만: 옆 지점을 가리지 않게 */}
{sel && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<SnowMark m={p.m} big={sel && p.m.stage !== 'soon'} />
</span>
)
}
/** 첫눈 지도 페이지: 지점 42곳의 평년 첫눈 날짜와 앞으로 7일 눈 예보를 지도에서 확대해 보고 목록으로 고른다. 확대·이동은 mapView.ts */
export function FirstSnowPage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { today, spots, forecast, load, refetch } = useFirstSnow()
const [sel, setSel] = useState<string | null>(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<SnowSpot | null>(null)
const [shareReq, setShareReq] = useState(0)
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
useEffect(() => track('first_snow_open', {}), [])
useEffect(() => {
if (sel) track('first_snow_spot', { spot_name: sel, from: 'page' })
}, [sel])
const vpRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(vpRef, spots)
const ptsRef = useRef<Pt<SnowSpot>[]>([])
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
const { box, view, fit, zoomAt, focus } = useMapView(vpRef, spots, params.get('spot'), pickAt)
const pts = useMemo(
() => spread(spots.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: m.stage === 'soon' ? ICON_R : DOT_R }))),
[spots, view, box.W],
)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
const labelAt = useMemo(() => {
const ratio = view.s / fit.s
// 고른 지점 > 눈 예보가 있는 곳 > 대표 지점 > 나머지(확대해야 나옴)
const rank = (m: SnowSpot) => (m.name === sel ? 0 : m.stage === 'soon' ? 1 : m.top ? 2 : 3)
const order = pts.filter((p) => rank(p.m) < 3 || ratio >= LABEL_FROM).sort((a, b) => rank(a.m) - rank(b.m))
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }]
// 이름이 아직 안 나오는 작은 점은 이름표가 덮어도 된다
return placeLabels(order, order, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => rank(p.m) < 3)
}, [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 chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: SnowSpot) => {
setSel(m.name)
const el = vpRef.current
if (el) window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - 120, behavior: 'smooth' })
focus(m)
}
// 보내기: 공유 창이 이미지(지점 하나면 그 지점 지도 조각, 아니면 전체 지도)와 링크를 같이 보낸다
const share = (m?: SnowSpot) => {
setShareSpot(m ?? null)
setShareReq((n) => n + 1)
}
useEffect(() => {
if (!shareReq) return
const el = shareSpot ? spotShotRef.current : mapShotRef.current
if (el) open({ type: 'share', share: { title: shareSpot ? `${shareSpot.name} 첫눈` : '첫눈 지도', slides: [el] } })
}, [shareReq, shareSpot, open])
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
const title = firstSnowHeadline(spots, forecast)
const soon = snowSoon(spots)
return (
<div className="pb-6">
<div className="flex items-start gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative mt-0.5 grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<p className="m-0 flex items-center gap-1 text-[13px] font-extrabold opacity-75">
<Ic name="snow" className="size-4" />
첫눈 지도 · {md(today)}
</p>
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal text-balance">{title}</h2>
</div>
{spots.length > 0 && (
<button type="button" onClick={() => share()} aria-label="첫눈 지도 보내기" className={cx(SHARE_BTN, 'mt-0.5 shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
<SendIcon />
</button>
)}
</div>
<div ref={vpRef} className={cx('b-keep-bg relative mt-2 h-[min(122vw,calc(100dvh-330px),560px)] min-h-[300px] touch-pan-y overflow-hidden select-none', SNOW_PAPER)}>
{spots.length > 0 && <img src={MAP_SRC} alt="첫눈 지도" draggable={false} className={SNOW_MAP_IMG} style={{ left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} />}
{spots.length > 0 &&
provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{[...pts].sort((a, b) => Number(a.m.stage === 'soon') - Number(b.m.stage === 'soon')).map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 고르기`}
onClick={() => setSel(m.name === sel ? null : m.name)}
className={cx(LABEL, 'cursor-pointer border-0', m.name === sel ? 'z-[3] bg-[#28304a] text-[#ffffff]' : m.stage === 'soon' ? SNOW_LABEL_INK : 'bg-[#ffffffeb] text-[#5b6075]', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name} <span className="tabular-nums opacity-80">{day(m)}</span>
</button>
))}
{spots.length > 0 && (
<div className="absolute top-2.5 right-2.5 z-[4] flex flex-col gap-2">
{(
[
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const
).map(([t, label, f]) => (
<button key={t} type="button" aria-label={label} onClick={() => zoomAt(f, box.W / 2, box.H / 2, true)} className="b-keep-bg grid size-9 cursor-pointer place-items-center rounded-full bg-[#ffffff] text-[20px] font-bold text-[#28304a] shadow-[0_2px_6px_rgb(40_48_74/0.2)]">
{t}
</button>
))}
</div>
)}
{!spots.length && <StateBox load={load} onRetry={() => refetch()} empty="첫눈 정보가 아직 없어요." className="absolute inset-x-3 top-1/2 -translate-y-1/2" />}
</div>
{/* 고른 지점은 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */}
{chosen ? (
<div className="mx-3 mt-2 flex h-[60px] items-center gap-3 rounded-[18px] bg-white px-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<span className="grid size-8 shrink-0 place-items-center">
<SnowMark m={chosen} big />
</span>
<div className="min-w-0 flex-1">
<p className="m-0 flex items-center gap-1.5">
<b className="truncate font-jua text-[18px] leading-tight font-normal">{chosen.name}</b>
<span className={cx('shrink-0 rounded-full px-1.5 py-px text-[11px] font-extrabold', BADGE[chosen.stage])}>{SNOW_STAGE[chosen.stage]}</span>
</p>
<p className="m-0 truncate text-[12px] font-bold text-(--ink3)">
평년 첫눈 {md(chosen.normal)}
{chosen.snowDate && ` · ${md(chosen.snowDate)} 눈 예보(${amount(chosen.snowCm)})`}
</p>
</div>
<button type="button" onClick={() => share(chosen)} aria-label={`${chosen.name} 보내기`} className={cx(SHARE_BTN, TAP44)}>
<SendIcon />
</button>
</div>
) : (
<div className="mx-3 mt-2 flex h-[60px] flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="snow" className={cx('size-4', SNOW_SHADOW)} />눈 예보 날짜
</span>
<span className="flex items-center gap-1">
<i className={cx(SNOW_DOT.before, 'size-[7px]')} />
평년 첫눈 날짜
</span>
<span className="flex items-center gap-1">
<i className={cx(SNOW_DOT.passed, 'size-[7px]')} />
평년 첫눈 지남
</span>
</div>
)}
<div className="px-4">
{GROUPS.map(([g, heading]) => {
const rows = g === 'soon' ? soon : spots.filter((m) => m.stage === g)
if (!rows.length) return null
return (
<section key={g} aria-label={heading} className="pt-5">
<h3 className="m-0 flex items-baseline gap-1.5 px-1 pb-1.5 font-jua text-[19px] font-normal">
{heading}
<span className="font-sans text-[13px] font-extrabold text-(--ink3)">{rows.length}곳</span>
</h3>
<ul className="m-0 list-none border-t border-(--line) p-0">
{rows.map((m) => (
<li key={m.name} className={cx('flex items-center border-b border-(--line)', m.name === sel && 'bg-[rgb(91_155_224/0.1)]')}>
<button type="button" onClick={() => pickFromList(m)} aria-current={m.name === sel || undefined} className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 py-2.5 pl-1 text-left">
<span className="grid size-7 shrink-0 place-items-center">
<SnowMark m={m} big />
</span>
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-(--ink3)">
{m.region} · {g === 'soon' ? `눈 ${amount(m.snowCm)} · 평년 첫눈 ${md(m.normal)}` : '평년 첫눈'}
</small>
</span>
<b className={cx('shrink-0 font-jua text-[18px] font-normal tabular-nums', g === 'soon' ? 'text-[#2f7fd6]' : 'text-(--ink2)')}>{day(m)}</b>
</button>
<button type="button" onClick={() => share(m)} aria-label={`${m.name} 보내기`} className={cx(SHARE_ICON, 'ml-1', TAP44)}>
<SendIcon />
</button>
</li>
))}
</ul>
</section>
)
})}
<FirstSnowSpotShare spot={shareSpot} soon={soon} ref={spotShotRef} />
<FirstSnowMapShare title={title} today={today} soon={soon} spots={spots} ref={mapShotRef} />
<p className="m-0 px-1.5 pt-4 text-[11.5px] leading-relaxed font-semibold text-(--ink3)">
평년 첫눈은 기상청 1991~2020년 평균이에요(춘천·강릉은 북춘천·북강릉 관측소). 눈 예보는 앞으로 7일을 보고, 실제 첫눈은 평년 날짜·예보와 다를 수 있어요
{!forecast && load === 'ready' ? ' · 지금은 눈 예보를 받지 못해 평년 날짜만 보여 드려요' : ''}
</p>
</div>
</div>
)
}
+13 -238
View File
@@ -1,20 +1,17 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { ICON_R, LABEL, LABEL_INK, LAND_CX, LEAF_SHADOW, MAP_IMG, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
import { ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
import { useMapView } from './mapView'
import { useSheet } from './sheetContext'
import { FoliageMapShare, FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
import { track } from '../lib/analytics'
type View = { s: number; tx: number; ty: number }
type Filter = 'all' | Kind
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]
@@ -53,14 +50,13 @@ function Marker({ p, sel }: { p: Pt; sel: boolean }) {
)
}
/** 단풍 지도 페이지: 명소 67곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
/** 단풍 지도 페이지: 명소 67곳을 지도에서 확대해 보고 목록으로 고른다. 확대·이동은 mapView.ts */
export function FoliagePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { today, spots } = useFoliage()
const [filter, setFilter] = useState<Filter>('all')
const [sel, setSel] = useState<string | null>(params.get('spot'))
const linked = useRef(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<Spot | null>(null)
const [shareReq, setShareReq] = useState(0)
@@ -73,111 +69,24 @@ export function FoliagePage() {
}, [sel])
const vpRef = useRef<HTMLDivElement>(null)
const [box, setBox] = useState({ W: 0, H: 0 })
const [view, setView] = useState<View>({ s: 1, tx: 0, ty: 0 })
const viewRef = useRef(view)
useLayoutEffect(() => {
viewRef.current = view
}, [view])
const size = useLabelSize(vpRef, spots)
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<View>(() => {
const { W, H } = box
if (!W) 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: View): View => {
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: View) => {
cancelAnimationFrame(anim.current)
setView(v)
}, [])
const animateTo = useCallback(
(to: View) => {
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],
)
useLayoutEffect(() => {
const el = vpRef.current
if (!el) return
const ro = new ResizeObserver(() => setBox({ W: el.clientWidth, H: el.clientHeight }))
ro.observe(el)
return () => ro.disconnect()
}, [])
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로
const started = useRef(false)
useEffect(() => {
if (!box.W) return
if (started.current) {
set(clamp(viewRef.current))
return
const ptsRef = useRef<Pt[]>([])
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
started.current = true
set(fit)
const m = spots.find((s) => s.name === linked.current)
if (m) focus(m)
}, [box, fit, spots, set, clamp, focus])
setSel((cur) => (best && best !== cur ? best : null))
}, [])
const { box, view, fit, zoomAt, focus } = useMapView(vpRef, spots, params.get('spot'), pickAt)
const pts = useMemo(() => {
const ratio = view.s / fit.s
const visible = shown.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] })))
}, [shown, view, box.W, fit.s, sel])
const ptsRef = useRef(pts)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
@@ -193,140 +102,6 @@ export function FoliagePage() {
[view, box.W, pts, labelAt, size],
)
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
// 손가락: 두 손가락은 확대·이동, 한 손가락은 확대했을 때만 지도 이동(아니면 페이지 스크롤), 두 번 누르면 확대
useEffect(() => {
const el = vpRef.current
if (!el) return
let pinch: { d: number; x: number; y: number } | null = null
let one: { x: number; y: number; moved: boolean; scroll: boolean } | null = null
let lastTap = 0
const local = (t: { clientX: number; clientY: number }) => {
const r = el.getBoundingClientRect()
return { x: t.clientX - r.left, y: t.clientY - r.top }
}
const zoomed = () => viewRef.current.s > fit.s * 1.01
const onStart = (e: TouchEvent) => {
if ((e.target as HTMLElement).closest('button')) {
one = null
return
}
cancelAnimationFrame(anim.current)
if (e.touches.length === 2) {
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
one = null
} else if (e.touches.length === 1) {
one = { ...local(e.touches[0]), moved: false, scroll: false }
}
}
const onMove = (e: TouchEvent) => {
if (e.touches.length === 2 && pinch) {
e.preventDefault()
const [a, b] = [local(e.touches[0]), local(e.touches[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) / pinch.d))
const k = s / v.s
set(clamp({ s, tx: x - (pinch.x - v.tx) * k, ty: y - (pinch.y - v.ty) * k }))
pinch = { d, x, y }
return
}
if (e.touches.length !== 1 || !one) return
const p = local(e.touches[0])
const first = !one.moved
if (Math.hypot(p.x - one.x, p.y - one.y) > 6) one.moved = true
if (!zoomed() || one.scroll) return
const v = viewRef.current
const next = clamp({ s: v.s, tx: v.tx + p.x - one.x, ty: v.ty + p.y - one.y })
// 첫 움직임이 세로인데 지도가 그쪽 끝에 닿아 더 못 가면 이번 손짓은 페이지 스크롤로 넘긴다
if (first && Math.abs(p.y - one.y) > Math.abs(p.x - one.x) && next.ty === v.ty) {
one.scroll = true
return
}
e.preventDefault()
set(next)
one = { ...p, moved: one.moved, scroll: false }
}
const onEnd = (e: TouchEvent) => {
if (e.touches.length < 2) pinch = null
if (e.touches.length || !one || one.moved) {
if (!e.touches.length) one = null
return
}
e.preventDefault()
const now = Date.now()
if (now - lastTap < 300) {
lastTap = 0
zoomAt(2, one.x, one.y, true)
} else {
lastTap = now
pickAt(one.x, one.y)
}
one = null
}
// 마우스: 끌어서 이동, 누르면 고르기, 두 번 누르면 확대, 트랙패드 오므리기(ctrl+휠)로 확대
let drag: { x: number; y: number; moved: boolean } | null = null
const onDown = (e: PointerEvent) => {
if (e.pointerType !== 'mouse' || (e.target as HTMLElement).closest('button')) return
cancelAnimationFrame(anim.current)
drag = { ...local(e), moved: false }
}
const onPMove = (e: PointerEvent) => {
if (!drag) return
const p = local(e)
if (Math.hypot(p.x - drag.x, p.y - drag.y) > 3) drag.moved = true
const v = viewRef.current
set(clamp({ s: v.s, tx: v.tx + p.x - drag.x, ty: v.ty + p.y - drag.y }))
drag = { ...p, moved: drag.moved }
}
const onUp = () => {
if (drag && !drag.moved) pickAt(drag.x, drag.y)
drag = null
}
const onDbl = (e: MouseEvent) => {
// +/− 를 빨리 두 번 누른 건 확대로 치지 않는다
if ((e.target as HTMLElement).closest('button')) return
const p = local(e)
zoomAt(2, p.x, p.y, true)
}
const onWheel = (e: WheelEvent) => {
if (!e.ctrlKey) return
e.preventDefault()
const p = local(e)
zoomAt(Math.exp(-e.deltaY * 0.01), p.x, p.y)
}
el.addEventListener('touchstart', onStart, { passive: true })
el.addEventListener('touchmove', onMove, { passive: false })
el.addEventListener('touchend', onEnd, { passive: false })
el.addEventListener('pointerdown', onDown)
window.addEventListener('pointermove', onPMove)
window.addEventListener('pointerup', onUp)
el.addEventListener('dblclick', onDbl)
el.addEventListener('wheel', onWheel, { passive: false })
return () => {
el.removeEventListener('touchstart', onStart)
el.removeEventListener('touchmove', onMove)
el.removeEventListener('touchend', onEnd)
el.removeEventListener('pointerdown', onDown)
window.removeEventListener('pointermove', onPMove)
window.removeEventListener('pointerup', onUp)
el.removeEventListener('dblclick', onDbl)
el.removeEventListener('wheel', onWheel)
}
}, [fit, clamp, set, zoomAt, pickAt])
const chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: Spot) => {
setSel(m.name)
+248
View File
@@ -0,0 +1,248 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { ICON_R, LABEL, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, md, placeLabels, placeProvinces, spread, useLabelSize, type Box, type Pt } from './foliage'
import { useMapView } from './mapView'
import { useSheet } from './sheetContext'
import { SunriseMapShare, SunriseSpotShare } from './shareCards'
import { clock, COAST, direction, dokdoRise, SUN_DOT, SUN_LABEL_INK, SUN_MAP_IMG, SUN_SHADOW, sunriseHeadline, useSunrise, type Coast, type SunSpot } from './sunrise'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
import { track } from '../lib/analytics'
type Filter = 'all' | Coast
const DOT_R = 4
// 대표 명소가 아닌 곳의 이름이 나오기 시작하는 배율(처음 화면 대비): 처음엔 대표 명소 이름만 보여 차분하게
const LABEL_FROM = 2.2
const TAP_R = 24
const SHARE_ICON = 'relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-(--ink2) [&_svg]:stroke-[1.9]'
const SHARE_BTN = `${SHARE_ICON} bg-white/80`
const FILTERS: [Filter, string][] = [['all', '전체'], ...(Object.entries(COAST) as [Coast, string][])]
// 대표 명소는 해 아이콘, 나머지는 주황 점(고르면 점을 크게)
function SunMark({ m, big }: { m: SunSpot; big?: boolean }) {
if (m.top) return <Ic name="sun" className={cx('relative', big ? 'size-8' : 'size-5', SUN_SHADOW)} />
return <i className={cx('relative', SUN_DOT, big ? 'size-3.5' : 'size-[7px]')} />
}
function Marker({ p, sel }: { p: Pt<SunSpot>; sel: boolean }) {
return (
<span className={cx('pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center', sel && 'z-[3]')} style={{ left: p.x, top: p.y }}>
{/* 고른 명소는 속이 빈 고리만: 옆 명소를 가리지 않게 */}
{sel && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<SunMark m={p.m} big={sel && !p.m.top} />
</span>
)
}
/** 해돋이 지도 페이지: 명소 50곳의 해 뜨는 시각을 지도에서 확대해 보고 이른 순 목록으로 고른다. 확대·이동은 mapView.ts */
export function SunrisePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { days, day, setDay, spots } = useSunrise()
const [filter, setFilter] = useState<Filter>('all')
const [sel, setSel] = useState<string | null>(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<SunSpot | null>(null)
const [shareReq, setShareReq] = useState(0)
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.coast === filter), [spots, filter])
useEffect(() => track('sunrise_open', {}), [])
useEffect(() => {
if (sel) track('sunrise_spot', { spot_name: sel, from: 'page' })
}, [sel])
const vpRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(vpRef, spots)
const ptsRef = useRef<Pt<SunSpot>[]>([])
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
const { box, view, fit, zoomAt, focus } = useMapView(vpRef, spots, params.get('spot'), pickAt)
const pts = useMemo(
() => spread(shown.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: m.top ? ICON_R : DOT_R }))),
[shown, view, box.W],
)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
const labelAt = useMemo(() => {
const ratio = view.s / fit.s
// 고른 명소 > 대표 명소 > 나머지(확대해야 나옴), 같은 급이면 해가 이른 순(pts 는 이른 순)
const rank = (m: SunSpot) => (m.name === sel ? 0 : m.top ? 1 : 2)
const order = pts.filter((p) => p.m.name === sel || p.m.top || ratio >= LABEL_FROM).sort((a, b) => rank(a.m) - rank(b.m))
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }]
// 이름이 아직 안 나오는 작은 점은 이름표가 덮어도 된다: 동해안처럼 점이 몰린 곳에서도 대표 명소 이름이 보이게
return placeLabels(order, order, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.top || 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 chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: SunSpot) => {
setSel(m.name)
const el = vpRef.current
if (el) window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - 120, behavior: 'smooth' })
focus(m)
}
// 보내기: 공유 창이 이미지(명소 하나면 그 명소 지도 조각, 아니면 전체 지도)와 링크를 같이 보낸다
const share = (m?: SunSpot) => {
setShareSpot(m ?? null)
setShareReq((n) => n + 1)
}
useEffect(() => {
if (!shareReq) return
const el = shareSpot ? spotShotRef.current : mapShotRef.current
if (el) open({ type: 'share', share: { title: shareSpot ? `${shareSpot.name} 해돋이` : '해돋이 지도', slides: [el] } })
}, [shareReq, shareSpot, open])
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
const pickDay = (key: typeof day.key) => {
setDay(key)
track('sunrise_day', { day: key })
}
const when = `${day.label} ${md(day.date)}`
const tops = spots.filter((m) => m.top)
return (
<div className="pb-6">
<div className="flex items-start gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative mt-0.5 grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<p className="m-0 flex items-center gap-1 text-[13px] font-extrabold opacity-75">
<Ic name="sun" className="size-4" />
해돋이 지도 · {when}
</p>
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal text-balance">{sunriseHeadline(day, spots)}</h2>
</div>
<button type="button" onClick={() => share()} aria-label="해돋이 지도 보내기" className={cx(SHARE_BTN, 'mt-0.5 shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
<SendIcon />
</button>
</div>
{days.length > 1 && <Chips label="날짜" items={days.map((d) => [d.key, `${d.label} ${md(d.date)}`] as const)} value={day.key} onChange={pickDay} />}
<div ref={vpRef} className="b-keep-bg relative mt-2 h-[min(122vw,calc(100dvh-330px),560px)] min-h-[300px] touch-pan-y overflow-hidden bg-[#fff6ea] select-none">
<img src={MAP_SRC} alt="해돋이 지도" draggable={false} className={cx(SUN_MAP_IMG, 'max-w-none')} style={{ left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{[...pts].sort((a, b) => Number(a.m.top) - Number(b.m.top)).map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 고르기`}
onClick={() => setSel(m.name === sel ? null : m.name)}
className={cx(LABEL, 'cursor-pointer border-0', m.name === sel ? 'z-[3] bg-[#28304a] text-[#ffffff]' : m.top ? SUN_LABEL_INK : 'bg-[#ffffffeb] text-[#5b6075]', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name} <span className="tabular-nums opacity-80">{clock(m.rise)}</span>
</button>
))}
<div className="absolute top-2.5 right-2.5 z-[4] flex flex-col gap-2">
{(
[
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const
).map(([t, label, f]) => (
<button key={t} type="button" aria-label={label} onClick={() => zoomAt(f, box.W / 2, box.H / 2, true)} className="b-keep-bg grid size-9 cursor-pointer place-items-center rounded-full bg-[#ffffff] text-[20px] font-bold text-[#28304a] shadow-[0_2px_6px_rgb(40_48_74/0.2)]">
{t}
</button>
))}
</div>
</div>
{/* 고른 명소는 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */}
{chosen ? (
<div className="mx-3 mt-2 flex h-[60px] items-center gap-3 rounded-[18px] bg-white px-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<span className="grid size-8 shrink-0 place-items-center">
<SunMark m={chosen} big />
</span>
<div className="min-w-0 flex-1">
<p className="m-0 flex items-center gap-1.5">
<b className="truncate font-jua text-[18px] leading-tight font-normal">{chosen.name}</b>
<span className="shrink-0 rounded-full bg-[#ffe8d2] px-1.5 py-px text-[11px] font-extrabold text-[#a34f12]">{COAST[chosen.coast]}</span>
</p>
<p className="m-0 flex gap-1 text-[12px] font-bold text-(--ink3)">
<span className="truncate">{chosen.region}</span>
<span className="shrink-0">
· {clock(chosen.dawn)}부터 밝아져요 · {direction(chosen.az)}쪽
</span>
</p>
</div>
<b className="shrink-0 font-jua text-[22px] font-normal text-(--orange) tabular-nums">{clock(chosen.rise)}</b>
<button type="button" onClick={() => share(chosen)} aria-label={`${chosen.name} 보내기`} className={cx(SHARE_BTN, TAP44)}>
<SendIcon />
</button>
</div>
) : (
<div className="mx-3 mt-2 flex h-[60px] flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="sun" className={cx('size-4', SUN_SHADOW)} />
대표 명소
</span>
<span className="flex items-center gap-1">
<i className={cx(SUN_DOT, 'size-[7px]')} />그 밖의 명소
</span>
<span className="text-(--ink3)">숫자는 해 뜨는 시각</span>
</div>
)}
<Chips label="바다·산" items={FILTERS} value={filter} onChange={setFilter} />
<div className="px-4">
<section aria-label="해가 먼저 뜨는 순서" className="pt-5">
<h3 className="m-0 flex items-baseline gap-1.5 px-1 pb-1.5 font-jua text-[19px] font-normal">
해가 먼저 뜨는 순서
<span className="font-sans text-[13px] font-extrabold text-(--ink3)">{shown.length}곳</span>
</h3>
<ol className="m-0 list-none border-t border-(--line) p-0">
{shown.map((m) => (
<li key={m.name} className={cx('flex items-center border-b border-(--line)', m.name === sel && 'bg-[rgb(255_122_69/0.08)]')}>
<button type="button" onClick={() => pickFromList(m)} aria-current={m.name === sel || undefined} className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 py-2.5 pl-1 text-left">
<span className="grid size-7 shrink-0 place-items-center">
<SunMark m={m} big />
</span>
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-(--ink3)">
{m.region} · {clock(m.dawn)}부터 밝아져요
</small>
</span>
<b className="shrink-0 font-jua text-[18px] font-normal text-(--orange) tabular-nums">{clock(m.rise)}</b>
</button>
<button type="button" onClick={() => share(m)} aria-label={`${m.name} 보내기`} className={cx(SHARE_ICON, 'ml-1', TAP44)}>
<SendIcon />
</button>
</li>
))}
</ol>
</section>
<SunriseSpotShare spot={shareSpot} when={when} tops={tops} ref={spotShotRef} />
<SunriseMapShare title={sunriseHeadline(day, spots)} when={when} tops={tops} ranked={spots} ref={mapShotRef} />
<p className="m-0 px-1.5 pt-4 text-[11.5px] leading-relaxed font-semibold text-(--ink3)">
해 뜨는 시각은 명소 위치로 계산한 값이에요(바다 높이 기준, 1분쯤 다를 수 있어요). 높은 산 위에서는 몇 분 더 일찍 보여요 · 우리나라에서 가장 먼저 뜨는 독도는 {clock(dokdoRise(day.date))}
</p>
</div>
</div>
)
}
+5 -1
View File
@@ -16,7 +16,9 @@ import {
import { cx } from '../lib/utils'
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
import { fall } from './lib'
import { FirstSnowCard } from './firstSnowMap'
import { FoliageCard } from './foliageMap'
import { SunriseCard } from './sunriseMap'
import { InstallBanner } from './installBanner'
import { MoonArt } from './moon'
import { MyGakRow } from './myGak'
@@ -645,8 +647,10 @@ export function TodayPage() {
{load !== 'loading' && !posts.length && (
<StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" />
)}
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */}
{/* 계절 지도 카드를 포스트 맨 앞에: 단풍 지도 → 첫눈 지도 → 해돋이 지도 순으로 한 번에 하나만. 좋아요·댓글 자리(foliage_post)는 같이 쓴다 */}
{load !== 'loading' && posts.length > 0 && <FoliageCard post={f?.foliage_post} />}
{load !== 'loading' && posts.length > 0 && <FirstSnowCard post={f?.foliage_post} />}
{load !== 'loading' && posts.length > 0 && <SunriseCard post={f?.foliage_post} />}
{posts.map((p, i) => {
const t = talkAt(i)
const ev = eventNo.get(p.post_id)
+31
View File
@@ -0,0 +1,31 @@
import { useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getFirstSnowOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { loadOf } from '@nalssigak/shared/lib'
import { firstSnowInSeason, firstSnowOn } from '@nalssigak/shared/lib/firstSnow'
import { foliageToday } from '@nalssigak/shared/lib/foliage'
// 단계·제목 계산은 shared/lib/firstSnow.ts. 지도 그림·이름표 배치는 단풍 지도 것을 같이 쓴다(foliage.ts). 여기는 웹 화면에 붙는 것만
export { firstSnowHeadline, firstSnowInSeason, SNOW_STAGE, snowNote, snowSoon } from '@nalssigak/shared/lib/firstSnow'
export type { SnowSpot, SnowStage } from '@nalssigak/shared/lib/firstSnow'
// 눈 예보는 서버가 3시간에 한 번 받는다. 화면은 30분 동안은 다시 묻지 않는다
const STALE_MS = 30 * 60_000
/** 지점 42곳의 평년 첫눈 날짜와 눈 예보(평년 첫눈이 이른 순). enabled 가 false 면 받지 않는다. 첫눈 지도철이 아니면 inSeason 이 false */
export function useFirstSnow(enabled = true) {
const [today] = useState(() => foliageToday())
const q = useQuery({ ...getFirstSnowOptions(), staleTime: STALE_MS, enabled })
const spots = useMemo(() => firstSnowOn(today, q.data?.spots ?? []), [today, q.data])
return { today, spots, forecast: !!q.data?.forecast, load: loadOf(q), refetch: q.refetch, inSeason: firstSnowInSeason(today) }
}
// 지도 그림은 단풍 지도와 같은 것. 색을 다 빼고 옅게 해서 눈 내린 땅처럼 보이게, 양옆 귀퉁이의 단풍잎 장식은 잘라 낸다
export const SNOW_MAP_IMG = 'pointer-events-none absolute max-w-none select-none mix-blend-multiply brightness-[1.25] saturate-0 opacity-70 [clip-path:inset(0_8%_0_14%)]'
// 지도 바탕: 차가운 흰색
export const SNOW_PAPER = 'bg-[#f3f6fb]'
// 눈 예보가 있는 곳의 이름표
export const SNOW_LABEL_INK = 'bg-[#ffffffeb] text-[#1f5fae]'
export const SNOW_SHADOW = 'drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.45)]'
// 평년 첫눈 전은 하늘색 점, 지난 곳은 회색 점
export const SNOW_DOT = { before: 'b-keep-bg rounded-full bg-[#5b9be0]/90', passed: 'b-keep-bg rounded-full bg-[#8f8a80]/60' }
+197
View File
@@ -0,0 +1,197 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router'
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { useCarousel } from './carousel'
import { firstSnowHeadline, firstSnowInSeason, SNOW_DOT, SNOW_LABEL_INK, SNOW_MAP_IMG, SNOW_PAPER, SNOW_SHADOW, snowNote, snowSoon, useFirstSnow } from './firstSnow'
import { ICON_R, LABEL, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, spread, useLabelSize } from './foliage'
import { PostFrame } from './Post'
import { useSheet } from './sheetContext'
import { FirstSnowSpotShare } from './shareCards'
import { CROP_IMG, cropXY } from './sunrise'
import { SendIcon } from './svg'
import { Ic } from './ui'
import { track } from '../lib/analytics'
const TAP_R = 24
const DOT_R = 4
const RANK_N = 7
/** 피드의 첫눈 지도 카드(단풍 지도가 끝나면 그 자리를 이어받고, 끝나면 해돋이 지도에 넘긴다): 1장은 눈 예보가 있는 곳과 대표 지점(누르면 카드 안에 정보), 2장은 눈 예보가 가까운 순위. '지도 크게 보기'로 첫눈 지도 페이지 */
export function FirstSnowCard({ post }: { post?: PostReaction | null }) {
const navigate = useNavigate()
const [season] = useState(() => firstSnowInSeason())
const { today, spots, forecast, inSeason } = useFirstSnow(season)
// 지도에는 눈 예보가 있는 곳과 대표 지점만: 카드에서는 차분하게
const shown = useMemo(() => spots.filter((m) => m.stage === 'soon' || m.top), [spots])
const mapRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(mapRef, shown)
const [W, setW] = useState(0)
const [picked, setPicked] = useState<string | null>(null)
const { open } = useSheet()
const spotShotRef = useRef<HTMLDivElement>(null)
const { ref: sliderRef, index } = useCarousel({ align: 'start' })
const ready = inSeason && spots.length > 0
useLayoutEffect(() => {
const el = mapRef.current
if (!el) return
const ro = new ResizeObserver(() => setW(el.clientWidth))
ro.observe(el)
return () => ro.disconnect()
}, [ready])
const pts = useMemo(
() =>
spread(
shown.map((m) => {
const at = cropXY(m.x, m.y)
return { m, x: at.x * W, y: at.y * W, r: m.stage === 'soon' ? ICON_R : DOT_R }
}),
),
[shown, W],
)
const labelAt = useMemo(() => {
// 눈 예보가 있는 곳의 이름을 먼저 놓는다
const order = [...pts].sort((a, b) => Number(b.m.stage === 'soon') - Number(a.m.stage === 'soon'))
return placeLabels(order, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true)
}, [pts, size, W])
const provs = useMemo(
() =>
placeProvinces(
PROVINCES.map((v) => {
const at = cropXY(v.x, v.y)
return { name: v.name, x: at.x * W, y: at.y * W }
}),
pts,
labelBoxes(labelAt, size),
),
[pts, W, labelAt, size],
)
useEffect(() => {
if (picked) track('first_snow_spot', { spot_name: picked, from: 'card' })
}, [picked])
if (!ready) return null
const go = (name?: string) => navigate(name ? `/first-snow?spot=${encodeURIComponent(name)}` : '/first-snow')
const toggle = (name: string) => setPicked(name === picked ? null : name)
// 표시가 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 지점을 고른다
const tapMap = (e: MouseEvent<HTMLDivElement>) => {
const r = e.currentTarget.getBoundingClientRect()
let best: string | null = null
let bestD = TAP_R
for (const p of pts) {
const d = Math.hypot(p.x - (e.clientX - r.left), p.y - (e.clientY - r.top))
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setPicked(best && best !== picked ? best : null)
}
const sel = shown.find((m) => m.name === picked)
const soon = snowSoon(spots)
// 2번째 장: 눈 예보가 가까운 순서. 눈 예보가 없으면 평년 첫눈이 가까운 순서(spots 는 평년 첫눈이 이른 순)
const ranked = (soon.length ? soon : spots.filter((m) => m.stage === 'before')).slice(0, RANK_N)
const caption = soon.length ? `눈 예보 ${soon.length}곳: ${soon.slice(0, 5).map((m) => m.name).join(' · ')}${soon.length > 5 ? ' 외' : ''}` : undefined
return (
<PostFrame title="첫눈 지도" account="첫눈 지도" avatar="snow" pinned={{ key: 'foliage_post', post }} caption={caption}>
<div className={cx('b-keep-bg relative px-4 pt-4 pb-3 text-[#28304a]', SNOW_PAPER)}>
<p className="m-0 text-[13px] font-extrabold opacity-75">첫눈 지도 · {md(today)}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">{firstSnowHeadline(spots, forecast)}</p>
<div className="relative mt-1">
<span data-noshot aria-hidden="true" className="absolute top-0 right-0 z-[4] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white">
{index + 1}/2
</span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full">
{/* 그림의 빈 가장자리는 잘라 쓴다(CROP_IMG) */}
<div ref={mapRef} onClick={tapMap} className={cx('b-keep-bg relative mx-auto aspect-square w-full overflow-hidden', SNOW_PAPER)}>
<img src={MAP_SRC} alt="" className={SNOW_MAP_IMG} style={CROP_IMG} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{pts.map((p) => (
<span key={p.m.name} className="pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center" style={{ left: p.x, top: p.y }}>
{p.m.name === picked && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
{p.m.stage === 'soon' ? <Ic name="snow" className={cx('relative size-5', SNOW_SHADOW)} /> : <i className={cx('relative size-[7px]', SNOW_DOT[p.m.stage])} />}
</span>
))}
{shown.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 정보 보기`}
onClick={(e) => {
e.stopPropagation()
toggle(m.name)
}}
className={cx(LABEL, m.stage === 'soon' ? SNOW_LABEL_INK : 'bg-[#ffffffeb] text-[#5b6075]', 'cursor-pointer border-0', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name} <span className="tabular-nums opacity-80">{md(m.snowDate ?? m.normal)}</span>
</button>
))}
</div>
{/* 고른 지점 정보는 지도 밖, 범례 자리에: 지도 위 표시를 가리지 않게 */}
{sel ? (
<div className="b-keep-bg mt-2 flex items-center gap-3 rounded-[16px] bg-[#ffffff] px-3 py-2.5 shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
<Ic name="snow" className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<b className="block truncate font-jua text-[18px] leading-tight font-normal">{sel.name}</b>
<span className="block truncate text-[12px] font-bold text-[#6b7189]">
평년 첫눈 {md(sel.normal)}
{sel.snowDate && ` · ${md(sel.snowDate)} 눈 예보`}
</span>
</div>
<button type="button" onClick={() => sel && open({ type: 'share', share: { title: `${sel.name} 첫눈`, slides: spotShotRef.current ? [spotShotRef.current] : [] } })} aria-label={`${sel.name} 보내기`} className="relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-[#28304a] [&_svg]:stroke-[1.9]">
<SendIcon />
</button>
<button type="button" onClick={() => go(sel.name)} className="b-keep-bg shrink-0 cursor-pointer rounded-full bg-[#28304a] px-3 py-1.5 text-[12.5px] font-extrabold text-[#ffffff]">
지도에서 보기 ›
</button>
</div>
) : (
<span className="mt-2 flex h-[52px] items-center gap-3 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="snow" className="size-4" />눈 예보 날짜
</span>
<span className="flex items-center gap-1">
<i className={cx(SNOW_DOT.before, 'size-[7px]')} />
평년 첫눈 날짜
</span>
</span>
)}
</div>
<div className="flex min-w-0 shrink-0 grow-0 basis-full flex-col pl-1">
<p className="m-0 font-jua text-[20px] leading-tight">{soon.length ? '눈 예보가 있는 곳' : '평년 첫눈이 가까운 곳'}</p>
<p className="m-0 mt-0.5 text-[12px] font-bold text-[#6b7189]">{soon.length ? '앞으로 7일, 눈 예보가 가까운 순서예요' : '평년 첫눈 날짜가 가까운 순서예요'}</p>
<ol className="m-0 mt-2 flex flex-1 list-none flex-col justify-between p-0">
{ranked.map((m, i) => (
<li key={m.name}>
<button type="button" onClick={() => go(m.name)} className="flex w-full cursor-pointer items-center gap-2.5 border-0 bg-transparent py-1.5 text-left">
<b className={cx('w-6 shrink-0 text-center font-jua text-[22px] font-normal', i < 3 ? 'text-[#2f7fd6]' : 'text-[#9aa3b5]')}>{i + 1}</b>
<Ic name="snow" className={cx('size-7 shrink-0', SNOW_SHADOW)} />
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-[#6b7189]">{m.region}</small>
</span>
<span className="shrink-0 text-[14px] font-extrabold tabular-nums">{snowNote(m)}</span>
</button>
</li>
))}
</ol>
</div>
</div>
</div>
</div>
<FirstSnowSpotShare spot={sel ?? null} soon={soon} ref={spotShotRef} />
<button type="button" onClick={() => go()} className="b-keep-bg mt-2 w-full cursor-pointer rounded-full bg-[#ffffff] py-2 text-[14px] font-extrabold text-[#28304a] shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
지도 크게 보기 ›
</button>
</div>
</PostFrame>
)
}
+242
View File
@@ -0,0 +1,242 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react'
import { LAND_CX } from './foliage'
export type View = { s: number; tx: number; ty: number }
type Place = { name: string; x: number; y: number }
const MAX_ZOOM = 5
const FIT_TOP = 30
const FIT_BOTTOM = 14
/**
* 전국 지도 그림의 확대·이동 (단풍 지도·해돋이 지도 페이지가 같이 쓴다).
* 두 손가락은 확대·이동, 한 손가락은 확대했을 때만 지도 이동(아니면 페이지 스크롤), 두 번 누르면 확대, 한 번 누르면 pickAt(누른 자리).
* places 는 처음 화면에 다 들어와야 하는 명소, linked 는 처음에 가운데로 데려갈 명소 이름(링크로 들어왔을 때)
*/
export function useMapView(vpRef: RefObject<HTMLDivElement | null>, places: Place[], linked: string | null, pickAt: (x: number, y: number) => void) {
const [box, setBox] = useState({ W: 0, H: 0 })
const [view, setView] = useState<View>({ s: 1, tx: 0, ty: 0 })
const viewRef = useRef(view)
useLayoutEffect(() => {
viewRef.current = view
}, [view])
const linkedRef = useRef(linked)
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<View>(() => {
const { W, H } = box
if (!W || !places.length) return { s: 1, tx: 0, ty: 0 }
const xs = places.map((m) => m.x)
const ys = places.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, places])
const clamp = useCallback(
(v: View): View => {
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: View) => {
cancelAnimationFrame(anim.current)
setView(v)
}, [])
const animateTo = useCallback(
(to: View) => {
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: { x: number; y: number }) => {
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],
)
useLayoutEffect(() => {
const el = vpRef.current
if (!el) return
const ro = new ResizeObserver(() => setBox({ W: el.clientWidth, H: el.clientHeight }))
ro.observe(el)
return () => ro.disconnect()
}, [vpRef])
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로
const started = useRef(false)
useEffect(() => {
// 명소를 API 로 받는 지도(첫눈)는 받을 때까지 기다린다
if (!box.W || !places.length) return
if (started.current) {
set(clamp(viewRef.current))
return
}
started.current = true
set(fit)
const m = places.find((s) => s.name === linkedRef.current)
if (m) focus(m)
}, [box, fit, places, set, clamp, focus])
useEffect(() => {
const el = vpRef.current
if (!el) return
let pinch: { d: number; x: number; y: number } | null = null
let one: { x: number; y: number; moved: boolean; scroll: boolean } | null = null
let lastTap = 0
const local = (t: { clientX: number; clientY: number }) => {
const r = el.getBoundingClientRect()
return { x: t.clientX - r.left, y: t.clientY - r.top }
}
const zoomed = () => viewRef.current.s > fit.s * 1.01
const onStart = (e: TouchEvent) => {
if ((e.target as HTMLElement).closest('button')) {
one = null
return
}
cancelAnimationFrame(anim.current)
if (e.touches.length === 2) {
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
one = null
} else if (e.touches.length === 1) {
one = { ...local(e.touches[0]), moved: false, scroll: false }
}
}
const onMove = (e: TouchEvent) => {
if (e.touches.length === 2 && pinch) {
e.preventDefault()
const [a, b] = [local(e.touches[0]), local(e.touches[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) / pinch.d))
const k = s / v.s
set(clamp({ s, tx: x - (pinch.x - v.tx) * k, ty: y - (pinch.y - v.ty) * k }))
pinch = { d, x, y }
return
}
if (e.touches.length !== 1 || !one) return
const p = local(e.touches[0])
const first = !one.moved
if (Math.hypot(p.x - one.x, p.y - one.y) > 6) one.moved = true
if (!zoomed() || one.scroll) return
const v = viewRef.current
const next = clamp({ s: v.s, tx: v.tx + p.x - one.x, ty: v.ty + p.y - one.y })
// 첫 움직임이 세로인데 지도가 그쪽 끝에 닿아 더 못 가면 이번 손짓은 페이지 스크롤로 넘긴다
if (first && Math.abs(p.y - one.y) > Math.abs(p.x - one.x) && next.ty === v.ty) {
one.scroll = true
return
}
e.preventDefault()
set(next)
one = { ...p, moved: one.moved, scroll: false }
}
const onEnd = (e: TouchEvent) => {
if (e.touches.length < 2) pinch = null
if (e.touches.length || !one || one.moved) {
if (!e.touches.length) one = null
return
}
e.preventDefault()
const now = Date.now()
if (now - lastTap < 300) {
lastTap = 0
zoomAt(2, one.x, one.y, true)
} else {
lastTap = now
pickAt(one.x, one.y)
}
one = null
}
// 마우스: 끌어서 이동, 누르면 고르기, 두 번 누르면 확대, 트랙패드 오므리기(ctrl+휠)로 확대
let drag: { x: number; y: number; moved: boolean } | null = null
const onDown = (e: PointerEvent) => {
if (e.pointerType !== 'mouse' || (e.target as HTMLElement).closest('button')) return
cancelAnimationFrame(anim.current)
drag = { ...local(e), moved: false }
}
const onPMove = (e: PointerEvent) => {
if (!drag) return
const p = local(e)
if (Math.hypot(p.x - drag.x, p.y - drag.y) > 3) drag.moved = true
const v = viewRef.current
set(clamp({ s: v.s, tx: v.tx + p.x - drag.x, ty: v.ty + p.y - drag.y }))
drag = { ...p, moved: drag.moved }
}
const onUp = () => {
if (drag && !drag.moved) pickAt(drag.x, drag.y)
drag = null
}
const onDbl = (e: MouseEvent) => {
// +/− 를 빨리 두 번 누른 건 확대로 치지 않는다
if ((e.target as HTMLElement).closest('button')) return
const p = local(e)
zoomAt(2, p.x, p.y, true)
}
const onWheel = (e: WheelEvent) => {
if (!e.ctrlKey) return
e.preventDefault()
const p = local(e)
zoomAt(Math.exp(-e.deltaY * 0.01), p.x, p.y)
}
el.addEventListener('touchstart', onStart, { passive: true })
el.addEventListener('touchmove', onMove, { passive: false })
el.addEventListener('touchend', onEnd, { passive: false })
el.addEventListener('pointerdown', onDown)
window.addEventListener('pointermove', onPMove)
window.addEventListener('pointerup', onUp)
el.addEventListener('dblclick', onDbl)
el.addEventListener('wheel', onWheel, { passive: false })
return () => {
el.removeEventListener('touchstart', onStart)
el.removeEventListener('touchmove', onMove)
el.removeEventListener('touchend', onEnd)
el.removeEventListener('pointerdown', onDown)
window.removeEventListener('pointermove', onPMove)
window.removeEventListener('pointerup', onUp)
el.removeEventListener('dblclick', onDbl)
el.removeEventListener('wheel', onWheel)
}
}, [vpRef, fit, clamp, set, zoomAt, pickAt])
return { box, view, fit, zoomAt, focus }
}
+163
View File
@@ -2,8 +2,10 @@ import type { Ref } from 'react'
import { createPortal } from 'react-dom'
import { cx } from '../lib/utils'
import type { TopIndex } from '@nalssigak/shared/api/client/types.gen'
import { SNOW_DOT, SNOW_MAP_IMG, SNOW_PAPER, SNOW_SHADOW, SNOW_STAGE, type SnowSpot } from './firstSnow'
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
import { MEDALS, type TimeKind } from '@nalssigak/shared/lib'
import { clock, COAST, CROP_IMG, cropXY, direction, SUN_MAP_IMG, SUN_SHADOW, type SunSpot } from './sunrise'
import { Ic } from './ui'
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
@@ -186,6 +188,167 @@ export function FoliageMapShare({ title, peak, ranked, ref }: { title: string; p
)
}
/** 해돋이 명소 하나 공유: 그 명소를 가운데 둔 지도 조각(둘레 시·도 이름과 다른 대표 명소) 위에 큰 해, 아래에 이름·지역·해 뜨는 시각 */
export function SunriseSpotShare({ spot, when, tops, ref }: { spot: SunSpot | null; when: string; tops: SunSpot[]; ref: Ref<HTMLDivElement> }) {
if (!spot) return null
const near = tops.filter((m) => m.name !== spot.name)
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] text-[#28304a]">
<div className="relative flex-1 overflow-hidden">
{/* 명소가 가운데 오게 지도 그림을 키워 옮긴다 */}
<div className="absolute top-1/2 left-1/2 aspect-square w-[220%] bg-[#fff6ea]" style={{ transform: `translate(-${spot.x * 100}%, -${spot.y * 100}%)` }}>
<img src={MAP_SRC} alt="" className={cx(SUN_MAP_IMG, 'inset-0 size-full')} />
{PROVINCES.map((v) => (
<span key={v.name} className={cx(PROVINCE, 'text-[15px]')} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{near.map((m) => (
<Ic key={m.name} name="sun" className={cx('absolute size-5 -translate-x-1/2 -translate-y-1/2', SUN_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<span className="absolute top-1/2 left-1/2 grid size-[92px] -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full border-[3px] border-[#28304a] bg-[#ffffff99]">
<Ic name="sun" className={cx('w-[60px]', SUN_SHADOW)} />
</span>
</div>
<div className="px-5 pt-3 pb-4">
<p className="m-0 flex items-center gap-2">
<b className="font-jua text-[34px] leading-tight font-normal">{spot.name}</b>
<span className="rounded-full bg-[#ffe8d2] px-2 py-0.5 text-[14px] font-extrabold text-[#a34f12]">{COAST[spot.coast]}</span>
</p>
<p className="m-0 mt-0.5 text-[15px] font-bold text-[#6b7189]">
{spot.region} · {clock(spot.dawn)}부터 밝아져요 · {direction(spot.az)}쪽
</p>
<p className="m-0 mt-2 font-jua text-[22px]">
{when} 해 뜨는 시각 <span className="text-[#e0621f]">{clock(spot.rise)}</span>
</p>
</div>
</div>
</Offscreen>
)
}
/** 해돋이 지도 전체 공유: 제목, 대표 명소에 해가 찍힌 지도, 해가 먼저 뜨는 곳 1~3위. ranked 는 이른 순 */
export function SunriseMapShare({ title, when, tops, ranked, ref }: { title: string; when: string; tops: SunSpot[]; ranked: SunSpot[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">해돋이 지도 · {when}</p>
<p className="m-0 font-jua text-[24px] leading-tight">{title}</p>
<div className="relative mx-auto mt-1 aspect-square w-[72%] overflow-hidden bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={SUN_MAP_IMG} style={CROP_IMG} />
{PROVINCES.map((v) => {
const at = cropXY(v.x, v.y)
return (
<span key={v.name} className={PROVINCE} style={{ left: `${at.x * 100}%`, top: `${at.y * 100}%` }}>
{v.name}
</span>
)
})}
{tops.map((m) => {
const at = cropXY(m.x, m.y)
return <Ic key={m.name} name="sun" className={cx('absolute size-4 -translate-x-1/2 -translate-y-1/2', SUN_SHADOW)} style={{ left: `${at.x * 100}%`, top: `${at.y * 100}%` }} />
})}
</div>
<ol className="m-0 mt-auto grid list-none gap-1.5 p-0">
{ranked.slice(0, 3).map((m, i) => (
<li key={m.name} className="flex items-center gap-2.5 rounded-[14px] bg-[#ffffff] px-3 py-1.5">
<Ic name={MEDALS[i]} className="w-[22px] shrink-0" />
<b className="min-w-0 flex-1 truncate font-jua text-[17px] font-normal">{m.name}</b>
<span className="shrink-0 text-[13px] font-bold text-[#6b7189]">{m.region}</span>
<span className="shrink-0 font-jua text-[16px] text-[#e0621f] tabular-nums">{clock(m.rise)}</span>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
/** 첫눈 지점 하나 공유: 그 지점을 가운데 둔 지도 조각(둘레 시·도 이름과 눈 예보가 있는 다른 곳) 위에 큰 눈송이, 아래에 이름·평년 첫눈 날짜·눈 예보 */
export function FirstSnowSpotShare({ spot, soon, ref }: { spot: SnowSpot | null; soon: SnowSpot[]; ref: Ref<HTMLDivElement> }) {
if (!spot) return null
const near = soon.filter((m) => m.name !== spot.name)
return (
<Offscreen>
<div ref={ref} className={cx('flex aspect-[4/5] flex-col text-[#28304a]', SNOW_PAPER)}>
<div className="relative flex-1 overflow-hidden">
{/* 지점이 가운데 오게 지도 그림을 키워 옮긴다 */}
<div className={cx('absolute top-1/2 left-1/2 aspect-square w-[220%]', SNOW_PAPER)} style={{ transform: `translate(-${spot.x * 100}%, -${spot.y * 100}%)` }}>
<img src={MAP_SRC} alt="" className={cx(SNOW_MAP_IMG, 'inset-0 size-full')} />
{PROVINCES.map((v) => (
<span key={v.name} className={cx(PROVINCE, 'text-[15px]')} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{near.map((m) => (
<Ic key={m.name} name="snow" className={cx('absolute size-5 -translate-x-1/2 -translate-y-1/2', SNOW_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<span className="absolute top-1/2 left-1/2 grid size-[92px] -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full border-[3px] border-[#28304a] bg-[#ffffff99]">
<Ic name="snow" className={cx('w-[60px]', SNOW_SHADOW)} />
</span>
</div>
<div className="px-5 pt-3 pb-4">
<p className="m-0 flex items-center gap-2">
<b className="font-jua text-[34px] leading-tight font-normal">{spot.name}</b>
<span className={cx('rounded-full px-2 py-0.5 text-[14px] font-extrabold', spot.stage === 'soon' ? 'bg-[#dcebff] text-[#1f5fae]' : 'bg-[#e6ebf3] text-[#5b6075]')}>{SNOW_STAGE[spot.stage]}</span>
</p>
<p className="m-0 mt-0.5 text-[15px] font-bold text-[#6b7189]">{spot.region}</p>
<p className="m-0 mt-2 font-jua text-[22px]">
평년 첫눈 {md(spot.normal)}
{spot.snowDate && <span className="text-[#2f7fd6]"> · {md(spot.snowDate)} 눈 예보</span>}
</p>
</div>
</div>
</Offscreen>
)
}
/** 첫눈 지도 전체 공유: 제목, 눈 예보가 있는 곳은 눈송이·나머지는 점이 찍힌 지도, 눈 예보가 가까운 곳(없으면 평년 첫눈이 가까운 곳) 1~3위. spots 는 평년 첫눈이 이른 순 */
export function FirstSnowMapShare({ title, today, soon, spots, ref }: { title: string; today: string; soon: SnowSpot[]; spots: SnowSpot[]; ref: Ref<HTMLDivElement> }) {
const rows = (soon.length ? soon : spots.filter((m) => m.stage === 'before')).slice(0, 3)
return (
<Offscreen>
<div ref={ref} className={cx('flex aspect-[4/5] flex-col px-4 pt-4 pb-3 text-[#28304a]', SNOW_PAPER)}>
<p className="m-0 text-[13px] font-extrabold opacity-75">첫눈 지도 · {md(today)}</p>
<p className="m-0 font-jua text-[24px] leading-tight">{title}</p>
<div className={cx('relative mx-auto mt-1 aspect-square w-[72%] overflow-hidden', SNOW_PAPER)}>
<img src={MAP_SRC} alt="" className={SNOW_MAP_IMG} style={CROP_IMG} />
{PROVINCES.map((v) => {
const at = cropXY(v.x, v.y)
return (
<span key={v.name} className={PROVINCE} style={{ left: `${at.x * 100}%`, top: `${at.y * 100}%` }}>
{v.name}
</span>
)
})}
{spots.map((m) => {
const at = cropXY(m.x, m.y)
const style = { left: `${at.x * 100}%`, top: `${at.y * 100}%` }
return m.stage === 'soon' ? (
<Ic key={m.name} name="snow" className={cx('absolute size-4 -translate-x-1/2 -translate-y-1/2', SNOW_SHADOW)} style={style} />
) : (
<i key={m.name} className={cx('absolute size-[5px] -translate-x-1/2 -translate-y-1/2', SNOW_DOT[m.stage])} style={style} />
)
})}
</div>
<ol className="m-0 mt-auto grid list-none gap-1.5 p-0">
{rows.map((m) => (
<li key={m.name} className="flex items-center gap-2.5 rounded-[14px] bg-[#ffffff] px-3 py-1.5">
<Ic name="snow" className="w-[22px] shrink-0" />
<b className="min-w-0 flex-1 truncate font-jua text-[17px] font-normal">{m.name}</b>
<span className="shrink-0 text-[13px] font-bold text-[#6b7189]">{m.snowDate ? '눈 예보' : '평년 첫눈'}</span>
<span className="shrink-0 font-jua text-[16px] text-[#2f7fd6] tabular-nums">{md(m.snowDate ?? m.normal)}</span>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
/** 내 각 공유: 아이콘·이름·점수, 조건마다 막대와 실제 값. 로고·지역·날짜는 공유 틀이 그린다 */
export function MyGakShareCard({ name, icon, score, slot, rows, ref }: { name: string; icon: string; score?: number | null; slot?: string; rows: { axis: string; label: string; value: number; note: string }[]; ref: Ref<HTMLDivElement> }) {
return (
+30
View File
@@ -0,0 +1,30 @@
import { useMemo, useState } from 'react'
import { sunriseDays, sunriseInSeason, sunriseOn, type SunDayKey } from '@nalssigak/shared/lib/sunrise'
// 데이터·시각 계산은 shared/lib/sunrise.ts. 지도 그림·이름표 배치는 단풍 지도 것을 같이 쓴다(foliage.ts). 여기는 웹 화면에 붙는 것만
export { clock, COAST, direction, dokdoRise, sunriseHeadline } from '@nalssigak/shared/lib/sunrise'
export type { Coast, SunDay, SunDayKey, SunSpot } from '@nalssigak/shared/lib/sunrise'
/** 고를 수 있는 날(새해 첫날·오늘/내일), 고른 날의 명소 50곳과 해 뜨는 시각(이른 순). 해돋이철이 아니면 inSeason 이 false */
export function useSunrise() {
const [now] = useState(() => new Date())
const days = useMemo(() => sunriseDays(now), [now])
const [key, setDay] = useState<SunDayKey>(days[0].key)
const day = days.find((d) => d.key === key) ?? days[0]
const spots = useMemo(() => sunriseOn(day.date), [day.date])
return { days, day, setDay, spots, inSeason: sunriseInSeason(now) }
}
// 지도 그림은 단풍 지도와 같은 것. 가을 색을 거의 다 빼고 옅게 해서 겨울 새벽 땅처럼 보이게, 양옆 귀퉁이의 단풍잎 장식은 잘라 낸다
export const SUN_MAP_IMG = 'pointer-events-none absolute max-w-none select-none mix-blend-multiply brightness-[1.22] saturate-[.2] opacity-80 [clip-path:inset(0_8%_0_14%)]'
export const SUN_LABEL_INK = 'bg-[#ffffffeb] text-[#b4501a]'
export const SUN_SHADOW = 'drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.45)]'
// 대표 명소가 아닌 곳은 주황 점
export const SUN_DOT = 'b-keep-bg rounded-full bg-[#f08a3c]/90'
// 피드 카드·공유 이미지는 그림 전체를 쓰지 않고 이 범위(그림 안 0~1)만 잘라 쓴다: 빈 가장자리를 덜어 땅을 크게 보이게 (맨 북쪽 명소부터 제주까지는 들어온다)
const CROP = { x0: 0.04, y0: 0.08, s: 0.85 }
/** 그림 안 위치(0~1) → 잘라 낸 칸 안 위치(0~1) */
export const cropXY = (x: number, y: number) => ({ x: (x - CROP.x0) / CROP.s, y: (y - CROP.y0) / CROP.s })
/** 잘라 낸 칸(정사각형, overflow-hidden) 안에 지도 그림을 놓는 자리 */
export const CROP_IMG = { width: `${100 / CROP.s}%`, height: `${100 / CROP.s}%`, left: `${(-CROP.x0 / CROP.s) * 100}%`, top: `${(-CROP.y0 / CROP.s) * 100}%` }
+182
View File
@@ -0,0 +1,182 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router'
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { useCarousel } from './carousel'
import { ICON_R, LABEL, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, spread, useLabelSize } from './foliage'
import { PostFrame } from './Post'
import { useSheet } from './sheetContext'
import { SunriseSpotShare } from './shareCards'
import { clock, COAST, CROP_IMG, cropXY, SUN_LABEL_INK, SUN_MAP_IMG, SUN_SHADOW, sunriseHeadline, useSunrise } from './sunrise'
import { SendIcon } from './svg'
import { Ic } from './ui'
import { track } from '../lib/analytics'
const TAP_R = 24
const RANK_N = 7
/** 피드의 해돋이 지도 카드(해돋이철에 단풍 지도 카드 자리를 이어받는다): 1장은 대표 명소와 해 뜨는 시각(누르면 카드 안에 정보), 2장은 해가 먼저 뜨는 순위. '지도 크게 보기'로 해돋이 지도 페이지 */
export function SunriseCard({ post }: { post?: PostReaction | null }) {
const navigate = useNavigate()
const { day, spots, inSeason } = useSunrise()
const tops = useMemo(() => spots.filter((m) => m.top), [spots])
const mapRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(mapRef, tops)
const [W, setW] = useState(0)
const [picked, setPicked] = useState<string | null>(null)
const { open } = useSheet()
const spotShotRef = useRef<HTMLDivElement>(null)
const { ref: sliderRef, index } = useCarousel({ align: 'start' })
useLayoutEffect(() => {
const el = mapRef.current
if (!el) return
const ro = new ResizeObserver(() => setW(el.clientWidth))
ro.observe(el)
return () => ro.disconnect()
}, [inSeason])
const pts = useMemo(
() =>
spread(
tops.map((m) => {
const at = cropXY(m.x, m.y)
return { m, x: at.x * W, y: at.y * W, r: ICON_R }
}),
),
[tops, W],
)
const labelAt = useMemo(() => placeLabels(pts, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true), [pts, size, W])
const provs = useMemo(
() =>
placeProvinces(
PROVINCES.map((v) => {
const at = cropXY(v.x, v.y)
return { name: v.name, x: at.x * W, y: at.y * W }
}),
pts,
labelBoxes(labelAt, size),
),
[pts, W, labelAt, size],
)
useEffect(() => {
if (picked) track('sunrise_spot', { spot_name: picked, from: 'card' })
}, [picked])
if (!inSeason) return null
const go = (name?: string) => navigate(name ? `/sunrise?spot=${encodeURIComponent(name)}` : '/sunrise')
const toggle = (name: string) => setPicked(name === picked ? null : name)
// 해 아이콘이 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 명소를 고른다
const tapMap = (e: MouseEvent<HTMLDivElement>) => {
const r = e.currentTarget.getBoundingClientRect()
let best: string | null = null
let bestD = TAP_R
for (const p of pts) {
const d = Math.hypot(p.x - (e.clientX - r.left), p.y - (e.clientY - r.top))
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setPicked(best && best !== picked ? best : null)
}
const sel = tops.find((m) => m.name === picked)
const when = `${day.label} ${md(day.date)}`
// 2번째 장: 해가 먼저 뜨는 순서(spots 는 이른 순)
const ranked = spots.slice(0, RANK_N)
return (
<PostFrame title="해돋이 지도" account="해돋이 지도" avatar="sun" pinned={{ key: 'foliage_post', post }} caption={`가장 이른 곳: ${spots.slice(0, 3).map((m) => `${m.name} ${clock(m.rise)}`).join(' · ')}`}>
<div className="b-keep-bg relative bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">해돋이 지도 · {when}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">{sunriseHeadline(day, spots)}</p>
<div className="relative mt-1">
<span data-noshot aria-hidden="true" className="absolute top-0 right-0 z-[4] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white">
{index + 1}/2
</span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full">
{/* 그림의 빈 가장자리는 잘라 쓴다(CROP_IMG) */}
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full overflow-hidden bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={SUN_MAP_IMG} style={CROP_IMG} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{pts.map((p) => (
<span key={p.m.name} className="pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center" style={{ left: p.x, top: p.y }}>
{p.m.name === picked && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<Ic name="sun" className={cx('relative size-5', SUN_SHADOW)} />
</span>
))}
{tops.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 정보 보기`}
onClick={(e) => {
e.stopPropagation()
toggle(m.name)
}}
className={cx(LABEL, SUN_LABEL_INK, 'cursor-pointer border-0', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name} <span className="tabular-nums opacity-80">{clock(m.rise)}</span>
</button>
))}
</div>
{/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 해를 가리지 않게 */}
{sel ? (
<div className="b-keep-bg mt-2 flex items-center gap-3 rounded-[16px] bg-[#ffffff] px-3 py-2.5 shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
<Ic name="sun" className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<b className="block truncate font-jua text-[18px] leading-tight font-normal">{sel.name}</b>
<span className="flex gap-1 text-[12px] font-bold text-[#6b7189]">
<span className="shrink-0">{COAST[sel.coast]}</span>
<span className="shrink-0">· 해 뜨는 시각 {clock(sel.rise)}</span>
</span>
</div>
<button type="button" onClick={() => sel && open({ type: 'share', share: { title: `${sel.name} 해돋이`, slides: spotShotRef.current ? [spotShotRef.current] : [] } })} aria-label={`${sel.name} 보내기`} className="relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-[#28304a] [&_svg]:stroke-[1.9]">
<SendIcon />
</button>
<button type="button" onClick={() => go(sel.name)} className="b-keep-bg shrink-0 cursor-pointer rounded-full bg-[#28304a] px-3 py-1.5 text-[12.5px] font-extrabold text-[#ffffff]">
지도에서 보기 ›
</button>
</div>
) : (
<span className="mt-2 flex h-[52px] items-center gap-1 text-[12.5px] font-bold">
<Ic name="sun" className="size-4" />
대표 명소의 해 뜨는 시각이에요
</span>
)}
</div>
<div className="flex min-w-0 shrink-0 grow-0 basis-full flex-col pl-1">
<p className="m-0 font-jua text-[20px] leading-tight">해가 먼저 뜨는 곳</p>
<p className="m-0 mt-0.5 text-[12px] font-bold text-[#6b7189]">{when} 해 뜨는 시각이 이른 순서예요</p>
<ol className="m-0 mt-2 flex flex-1 list-none flex-col justify-between p-0">
{ranked.map((m, i) => (
<li key={m.name}>
<button type="button" onClick={() => go(m.name)} className="flex w-full cursor-pointer items-center gap-2.5 border-0 bg-transparent py-1.5 text-left">
<b className={cx('w-6 shrink-0 text-center font-jua text-[22px] font-normal', i < 3 ? 'text-[#e0621f]' : 'text-[#9a8f80]')}>{i + 1}</b>
<Ic name="sun" className={cx('size-7 shrink-0', SUN_SHADOW)} />
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-[#6b7189]">{m.region}</small>
</span>
<span className="shrink-0 text-[14px] font-extrabold tabular-nums">{clock(m.rise)}</span>
</button>
</li>
))}
</ol>
</div>
</div>
</div>
</div>
<SunriseSpotShare spot={sel ?? null} when={when} tops={tops} ref={spotShotRef} />
<button type="button" onClick={() => go()} className="b-keep-bg mt-2 w-full cursor-pointer rounded-full bg-[#ffffff] py-2 text-[14px] font-extrabold text-[#28304a] shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
지도 크게 보기 ›
</button>
</div>
</PostFrame>
)
}
+8 -1
View File
@@ -1,10 +1,12 @@
import { type ReactNode } from 'react'
import { useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { track } from '../lib/analytics'
import { HIDDEN } from './features'
import { firstSnowInSeason } from './firstSnow'
import { useFoliage } from './foliage'
import { useTarotBadge } from './fortune'
import { sajuSeenToday } from './SajuPage'
import { useSunrise } from './sunrise'
import { useSheet } from './sheetContext'
import { Ic, Rail } from './ui'
@@ -20,6 +22,8 @@ export function TodayIcons() {
const { open } = useSheet()
const tarot = useTarotBadge()
const { inSeason } = useFoliage()
const [snowSeason] = useState(() => firstSnowInSeason())
const { inSeason: sunriseSeason } = useSunrise()
const items: Item[] = [
{
@@ -35,7 +39,10 @@ export function TodayIcons() {
},
{ key: 'saju', label: '날씨 사주', icon: 'yin_yang', badge: sajuSeenToday() ? null : <Dot />, to: '/saju' },
{ key: 'game', label: '날씨 게임', icon: 'game', to: '/game' },
// 계절 지도 칸: 단풍 지도 → 첫눈 지도 → 해돋이 지도 순으로 한 번에 하나만 나온다
...(inSeason ? [{ key: 'foliage', label: '단풍 지도', icon: 'maple', to: '/foliage' }] : []),
...(snowSeason ? [{ key: 'firstSnow', label: '첫눈 지도', icon: 'snow', to: '/first-snow' }] : []),
...(sunriseSeason ? [{ key: 'sunrise', label: '해돋이 지도', icon: 'sunset', to: '/sunrise' }] : []),
{ key: 'shorts', label: '쇼츠', icon: 'clapper', to: '/shorts' },
{ key: 'myGak', label: '내 각', icon: 'rabbit', onClick: () => document.getElementById(MY_GAK_ID)?.scrollIntoView({ behavior: 'smooth', block: 'start' }) },
{ key: 'talk', label: '동네 이야기', icon: 'speech', to: '/talk' },
+14
View File
@@ -70,6 +70,20 @@ const PAGES: { path: string; title: string; description: string; body: string; c
keywords: '단풍 지도, 단풍 절정, 단풍 시기, 단풍 명소, 은행나무 명소, 날씨각',
body: '<h1>날씨각 · 단풍 지도</h1><p>산림청 단풍 절정 예측으로 전국 단풍 명소의 절정 시기를 지도에서 보여 드려요. 잎 절반이 물든 때를 절정으로 보고, 지금 절정·곧 절정·아직·절정 지남으로 나눠 볼 수 있어요.</p><p>단풍과 은행을 따로 골라 볼 수 있어요.</p>',
},
{
path: 'first-snow',
title: '첫눈 지도 · 지역별 평년 첫눈 날짜와 눈 예보 | 날씨각',
description: '서울, 춘천, 대전, 광주, 대구, 부산, 제주 등 전국 42곳의 평년 첫눈 날짜와 앞으로 7일 눈 예보를 지도에서 확인하세요.',
keywords: '첫눈 지도, 첫눈 날짜, 첫눈 시기, 평년 첫눈, 눈 예보, 날씨각',
body: '<h1>날씨각 · 첫눈 지도</h1><p>전국 42곳의 평년 첫눈 날짜(기상청 1991~2020년 평균)를 지도에서 보여 드려요. 대관령은 11월 초, 서울·대전은 11월 20일쯤, 부산은 12월 하순이 평년 첫눈이에요.</p><p>앞으로 7일 안에 눈 예보가 있는 곳은 눈송이로 표시해 드려요. 실제 첫눈은 평년 날짜·예보와 다를 수 있어요.</p>',
},
{
path: 'sunrise',
title: '해돋이 지도 · 새해 일출 시간과 해돋이 명소 | 날씨각',
description: '정동진, 호미곶, 간절곶, 성산일출봉 같은 전국 해돋이 명소 50곳의 새해 첫날 해 뜨는 시각을 지도에서 확인하세요. 해가 먼저 뜨는 순서로 보여 드려요.',
keywords: '해돋이 지도, 새해 일출 시간, 해돋이 명소, 일출 명소, 해 뜨는 시각, 날씨각',
body: '<h1>날씨각 · 해돋이 지도</h1><p>전국 해돋이 명소 50곳의 해 뜨는 시각을 지도에서 보여 드려요. 12월에는 새해 첫날(1월 1일), 그 밖에는 오늘·내일 해 뜨는 시각을 해가 먼저 뜨는 순서로 볼 수 있어요.</p><p>동해, 남해·제주, 서해, 산·도심으로 나눠 볼 수 있고, 하늘이 밝아지기 시작하는 시각과 해 뜨는 방향도 알려 드려요.</p>',
},
{
path: 'talk',
title: '동네 이야기 · 지금 우리 동네 날씨 이야기 | 날씨각',
+20 -2
View File
@@ -3,8 +3,8 @@
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
import { client } from '../client.gen';
import { addComment, addMyGak, addTalk, addTalkComment, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteBirth, deleteComment, deleteMyGak, deleteTalk, drawFortune, gameRound, gameStart, getArticle, getBirth, getCardImage, getFeed, getFortuneToday, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, importFortune, likeComment, likePost, likeTalk, listArticles, listBlocked, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalkComments, listTalks, listUsers, login, logout, match, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, putBirth, reading, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkCommentData, AddTalkCommentError, AddTalkCommentResponse, AddTalkData, AddTalkError, AddTalkResponse, AgreeTermsData, AgreeTermsError, AgreeTermsResponse, AttendData, AttendError, AttendResponse, AuthConfigData, AuthConfigResponse, BlockAuthorData, BlockAuthorError, BlockAuthorResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, CreateReelData, CreateReelError, CreateReelResponse, DeleteBirthData, DeleteBirthError, DeleteBirthResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, DrawFortuneData, DrawFortuneError, DrawFortuneResponse, GameRoundData, GameRoundError, GameRoundResponse, GameStartData, GameStartError, GameStartResponse, GetArticleData, GetArticleError, GetArticleResponse, GetBirthData, GetBirthError, GetBirthResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetFortuneTodayData, GetFortuneTodayError, GetFortuneTodayResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetReelCoverData, GetReelCoverError, GetReelVideoData, GetReelVideoError, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, ImportFortuneData, ImportFortuneError, ImportFortuneResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListBlockedData, ListBlockedError, ListBlockedResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListReelsData, ListReelsError, ListReelsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListShortsData, ListShortsResponse, ListTalkCommentsData, ListTalkCommentsError, ListTalkCommentsResponse, ListTalksData, ListTalksError, ListTalksResponse, ListUsersData, ListUsersError, ListUsersResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MatchData, MatchError, MatchResponse, MeData, MeError, MeResponse, MyLevelData, MyLevelError, MyLevelResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, PublishInstagram2Data, PublishInstagram2Error, PublishInstagram2Response, PublishInstagramData, PublishInstagramError, PublishInstagramResponse, PutBirthData, PutBirthError, PutBirthResponse, ReadingData, ReadingError, ReadingResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportCommentData, ReportCommentError, ReportCommentResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SaveDayLogData, SaveDayLogError, SaveDayLogResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SearchFortunePlacesData, SearchFortunePlacesError, SearchFortunePlacesResponse, SharedData, SharedError, SharedResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, TossData, TossError, TossResponse, TossUnlinkData, TossUnlinkError, TossUnlinkResponse, UnblockData, UnblockError, UnblockResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse, WithdrawData, WithdrawError, WithdrawResponse } from '../types.gen';
import { addComment, addMyGak, addTalk, addTalkComment, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteBirth, deleteComment, deleteMyGak, deleteTalk, drawFortune, gameRound, gameStart, getArticle, getBirth, getCardImage, getFeed, getFirstSnow, getFortuneToday, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, importFortune, likeComment, likePost, likeTalk, listArticles, listBlocked, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalkComments, listTalks, listUsers, login, logout, match, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, putBirth, reading, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkCommentData, AddTalkCommentError, AddTalkCommentResponse, AddTalkData, AddTalkError, AddTalkResponse, AgreeTermsData, AgreeTermsError, AgreeTermsResponse, AttendData, AttendError, AttendResponse, AuthConfigData, AuthConfigResponse, BlockAuthorData, BlockAuthorError, BlockAuthorResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, CreateReelData, CreateReelError, CreateReelResponse, DeleteBirthData, DeleteBirthError, DeleteBirthResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, DrawFortuneData, DrawFortuneError, DrawFortuneResponse, GameRoundData, GameRoundError, GameRoundResponse, GameStartData, GameStartError, GameStartResponse, GetArticleData, GetArticleError, GetArticleResponse, GetBirthData, GetBirthError, GetBirthResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetFirstSnowData, GetFirstSnowResponse, GetFortuneTodayData, GetFortuneTodayError, GetFortuneTodayResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetReelCoverData, GetReelCoverError, GetReelVideoData, GetReelVideoError, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, ImportFortuneData, ImportFortuneError, ImportFortuneResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListBlockedData, ListBlockedError, ListBlockedResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListReelsData, ListReelsError, ListReelsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListShortsData, ListShortsResponse, ListTalkCommentsData, ListTalkCommentsError, ListTalkCommentsResponse, ListTalksData, ListTalksError, ListTalksResponse, ListUsersData, ListUsersError, ListUsersResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MatchData, MatchError, MatchResponse, MeData, MeError, MeResponse, MyLevelData, MyLevelError, MyLevelResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, PublishInstagram2Data, PublishInstagram2Error, PublishInstagram2Response, PublishInstagramData, PublishInstagramError, PublishInstagramResponse, PutBirthData, PutBirthError, PutBirthResponse, ReadingData, ReadingError, ReadingResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportCommentData, ReportCommentError, ReportCommentResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SaveDayLogData, SaveDayLogError, SaveDayLogResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SearchFortunePlacesData, SearchFortunePlacesError, SearchFortunePlacesResponse, SharedData, SharedError, SharedResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, TossData, TossError, TossResponse, TossUnlinkData, TossUnlinkError, TossUnlinkResponse, UnblockData, UnblockError, UnblockResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse, WithdrawData, WithdrawError, WithLine truncated
export type QueryKey<TOptions extends Options> = [
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
@@ -309,6 +309,24 @@ export const getArticleOptions = (options: Options<GetArticleData>) => queryOpti
queryKey: getArticleQueryKey(options)
});
export const getFirstSnowQueryKey = (options?: Options<GetFirstSnowData>) => createQueryKey('getFirstSnow', options);
/**
* 첫눈 지도: 지점별 평년 첫눈 날짜와 앞으로 7일 눈 예보
*/
export const getFirstSnowOptions = (options?: Options<GetFirstSnowData>) => queryOptions<GetFirstSnowResponse, DefaultError, GetFirstSnowResponse, ReturnType<typeof getFirstSnowQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getFirstSnow({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getFirstSnowQueryKey(options)
});
export const getFeedQueryKey = (options: Options<GetFeedData>) => createQueryKey('getFeed', options);
/**
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { addComment, addMyGak, addTalk, addTalkComment, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteBirth, deleteComment, deleteMyGak, deleteTalk, drawFortune, gameRound, gameStart, getArticle, getBirth, getCardImage, getFeed, getFortuneToday, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, importFortune, likeComment, likePost, likeTalk, listArticles, listBlocked, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalkComments, listTalks, listUsers, login, logout, match, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, putBirth, reading, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkCommentData, type AddTalkCommentError, type AddTalkCommentErrors, type AddTalkCommentResponse, type AddTalkCommentResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AdminUser, type AgreeTermsData, type AgreeTermsError, type AgreeTermsErrors, type AgreeTermsResponse, type AgreeTermsResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AttendData, type AttendError, type AttendErrors, type AttendResponse, type AttendResponses, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockAuthorData, type BlockAuthorError, type BlockAuthorErrors, type BlockAuthorResponse, type BlockAuthorResponses, type BlockedUser, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type CreateReelData, type CreateReelError, type CreateReelErrors, type CreateReelResponse, type CreateReelResponses, type Cut, type DayData, type DayLogData, type DeleteBirthData, type DeleteBirthError, type DeleteBirthErrors, type DeleteBirthResponse, type DeleteBirthResponses, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type DrawFortuneData, type DrawFortuneError, type DrawFortuneErrors, type DrawFortuneResponse, type DrawFortuneResponses, type ErrorInfo, type EventData, type Factor, type FortuneCard, type FortuneLuck, type FortunePlace, type GakSlide, type GameRoundData, type GameRoundError, type GameRoundErrors, type GameRoundResponse, type GameRoundResponses, type GameStartData, type GameStartError, type GameStartErrors, type GameStartResponse, type GameStartResponses, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetBirthData, type GetBirthError, type GetBirthErrors, type GetBirthResponse, type GetBirthResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetFortuneTodayData, type GetFortuneTodayError, type GetFortuneTodayErrors, type GetFortuneTodayResponse, type GetFortuneTodayResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetReelCoverData, type GetReelCoverError, type GetReelCoverErrors, type GetReelCoverResponses, type GetReelVideoData, type GetReelVideoError, type GetReelVideoErrors, type GetReelVideoResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeLine truncated
export { addComment, addMyGak, addTalk, addTalkComment, agreeTerms, attend, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteBirth, deleteComment, deleteMyGak, deleteTalk, drawFortune, gameRound, gameStart, getArticle, getBirth, getCardImage, getFeed, getFirstSnow, getFortuneToday, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, importFortune, likeComment, likePost, likeTalk, listArticles, listBlocked, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalkComments, listTalks, listUsers, login, logout, match, me, myLevel, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, putBirth, reading, refresh, rejectCard, reportComment, reportTalk, saveDayLog, savePost, scoreMyGak, searchFortunePlaces, shared, signup, talkGroups, toss, tossUnlink, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkCommentData, type AddTalkCommentError, type AddTalkCommentErrors, type AddTalkCommentResponse, type AddTalkCommentResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AdminUser, type AgreeTermsData, type AgreeTermsError, type AgreeTermsErrors, type AgreeTermsResponse, type AgreeTermsResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AttendData, type AttendError, type AttendErrors, type AttendResponse, type AttendResponses, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockAuthorData, type BlockAuthorError, type BlockAuthorErrors, type BlockAuthorResponse, type BlockAuthorResponses, type BlockedUser, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type CreateReelData, type CreateReelError, type CreateReelErrors, type CreateReelResponse, type CreateReelResponses, type Cut, type DayData, type DayLogData, type DeleteBirthData, type DeleteBirthError, type DeleteBirthErrors, type DeleteBirthResponse, type DeleteBirthResponses, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type DrawFortuneData, type DrawFortuneError, type DrawFortuneErrors, type DrawFortuneResponse, type DrawFortuneResponses, type ErrorInfo, type EventData, type Factor, type FirstSnowSpot, type FortuneCard, type FortuneLuck, type FortunePlace, type GakSlide, type GameRoundData, type GameRoundError, type GameRoundErrors, type GameRoundResponse, type GameRoundResponses, type GameStartData, type GameStartError, type GameStartErrors, type GameStartResponse, type GameStartResponses, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetBirthData, type GetBirthError, type GetBirthErrors, type GetBirthResponse, type GetBirthResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetFirstSnowData, type GetFirstSnowResponse, type GetFirstSnowResponses, type GetFortuneTodayData, type GetFortuneTodayError, type GetFortuneTodayErrors, type GetFortuneTodayResponse, type GetFortuneTodayResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetReelCoverData, type GetReelCoverError, type GetReelCoverErrors, type GetReelCoverResponses, type GetReelVideoData, type GetReelVideoError, type GetReelVideoErrors, type GetReelVideoResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeLine truncated
+6 -1
View File
@@ -2,7 +2,7 @@
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
import { client } from './client.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkCommentData, AddTalkCommentErrors, AddTalkCommentResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AgreeTermsData, AgreeTermsErrors, AgreeTermsResponses, AttendData, AttendErrors, AttendResponses, AuthConfigData, AuthConfigResponses, BlockAuthorData, BlockAuthorErrors, BlockAuthorResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, CreateReelData, CreateReelErrors, CreateReelResponses, DeleteBirthData, DeleteBirthErrors, DeleteBirthResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, DrawFortuneData, DrawFortuneErrors, DrawFortuneResponses, GameRoundData, GameRoundErrors, GameRoundResponses, GameStartData, GameStartErrors, GameStartResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetBirthData, GetBirthErrors, GetBirthResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetFortuneTodayData, GetFortuneTodayErrors, GetFortuneTodayResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetReelCoverData, GetReelCoverErrors, GetReelCoverResponses, GetReelVideoData, GetReelVideoErrors, GetReelVideoResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, ImportFortuneData, ImportFortuneErrors, ImportFortuneResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListBlockedData, ListBlockedErrors, ListBlockedResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListReelsData, ListReelsErrors, ListReelsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListShortsData, ListShortsResponses, ListTalkCommentsData, ListTalkCommentsErrors, ListTalkCommentsResponses, ListTalksData, ListTalksErrors, ListTalksResponses, ListUsersData, ListUsersErrors, ListUsersResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MatchData, MatchErrors, MatchResponses, MeData, MeErrors, MeResponses, MyLevelData, MyLevelErrors, MyLevelResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, PublishInstagram2Data, PublishInstagram2Errors, PublishInstagram2Responses, PublishInstagramData, PublishInstagramErrors, PublishInstagramResponses, PutBirthData, PutBirthErrors, PutBirthResponses, ReadingData, ReadingErrors, ReadingResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportCommentData, ReportCommentErrors, ReportCommentResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SaveDayLogData, SaveDayLogErrors, SaveDayLogResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SearchFortunePlacesData, SearchFortunePlacesErrors, SearchFortunePlacesResponses, SharedData, SharedErrors, SharedResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, TossData, TossErrors, TossResponses, TossUnlinkData, TossUnlinkErrors, TossUnlinkResponses, UnblockData, UnblockErrors, UnblockResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkDatLine truncated
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkCommentData, AddTalkCommentErrors, AddTalkCommentResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AgreeTermsData, AgreeTermsErrors, AgreeTermsResponses, AttendData, AttendErrors, AttendResponses, AuthConfigData, AuthConfigResponses, BlockAuthorData, BlockAuthorErrors, BlockAuthorResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, CreateReelData, CreateReelErrors, CreateReelResponses, DeleteBirthData, DeleteBirthErrors, DeleteBirthResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, DrawFortuneData, DrawFortuneErrors, DrawFortuneResponses, GameRoundData, GameRoundErrors, GameRoundResponses, GameStartData, GameStartErrors, GameStartResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetBirthData, GetBirthErrors, GetBirthResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetFirstSnowData, GetFirstSnowResponses, GetFortuneTodayData, GetFortuneTodayErrors, GetFortuneTodayResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetReelCoverData, GetReelCoverErrors, GetReelCoverResponses, GetReelVideoData, GetReelVideoErrors, GetReelVideoResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, ImportFortuneData, ImportFortuneErrors, ImportFortuneResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListBlockedData, ListBlockedErrors, ListBlockedResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListReelsData, ListReelsErrors, ListReelsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListShortsData, ListShortsResponses, ListTalkCommentsData, ListTalkCommentsErrors, ListTalkCommentsResponses, ListTalksData, ListTalksErrors, ListTalksResponses, ListUsersData, ListUsersErrors, ListUsersResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MatchData, MatchErrors, MatchResponses, MeData, MeErrors, MeResponses, MyLevelData, MyLevelErrors, MyLevelResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, PublishInstagram2Data, PublishInstagram2Errors, PublishInstagram2Responses, PublishInstagramData, PublishInstagramErrors, PublishInstagramResponses, PutBirthData, PutBirthErrors, PutBirthResponses, ReadingData, ReadingErrors, ReadingResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportCommentData, ReportCommentErrors, ReportCommentResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SaveDayLogData, SaveDayLogErrors, SaveDayLogResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SearchFortunePlacesData, SearchFortunePlacesErrors, SearchFortunePlacesResponses, SharedData, SharedErrors, SharedResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, TossData, TossErrors, TossResponses, TossUnlinkData, TossUnlinkErrors, TossUnlinkResponses, UnblockData, UnblockErrors, UnblockResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostELine truncated
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -93,6 +93,11 @@ export const listArticles = <ThrowOnError extends boolean = true>(options?: Opti
*/
export const getArticle = <ThrowOnError extends boolean = true>(options: Options<GetArticleData, ThrowOnError>): RequestResult<GetArticleResponses, GetArticleErrors, ThrowOnError> => (options.client ?? client).get<GetArticleResponses, GetArticleErrors, ThrowOnError>({ url: '/v1/season/article/{article_id}', ...options });
/**
* 첫눈 지도: 지점별 평년 첫눈 날짜와 앞으로 7일 눈 예보
*/
export const getFirstSnow = <ThrowOnError extends boolean = true>(options?: Options<GetFirstSnowData, ThrowOnError>): RequestResult<GetFirstSnowResponses, unknown, ThrowOnError> => (options?.client ?? client).get<GetFirstSnowResponses, unknown, ThrowOnError>({ url: '/v1/season/first-snow', ...options });
/**
* 메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠
*/
+73
View File
@@ -685,6 +685,44 @@ export type Factor = {
note: string;
};
/**
* FirstSnowSpot
*/
export type FirstSnowSpot = {
/**
* Name
*/
name: string;
/**
* Region
*/
region: string;
/**
* Lat
*/
lat: number;
/**
* Lon
*/
lon: number;
/**
* Normal
*/
normal: string;
/**
* Top
*/
top?: boolean;
/**
* Snow Date
*/
snow_date?: string | null;
/**
* Snow Cm
*/
snow_cm?: number | null;
};
/**
* FortuneCard
*/
@@ -2623,6 +2661,25 @@ export type ResFeed = {
bands?: Bands | null;
};
/**
* Res_FirstSnow
*/
export type ResFirstSnow = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Forecast
*/
forecast?: boolean;
/**
* Spots
*/
spots?: Array<FirstSnowSpot>;
};
/**
* Res_FortunePlaces
*/
@@ -5686,6 +5743,22 @@ export type GetArticleResponses = {
export type GetArticleResponse = GetArticleResponses[keyof GetArticleResponses];
export type GetFirstSnowData = {
body?: never;
path?: never;
query?: never;
url: '/v1/season/first-snow';
};
export type GetFirstSnowResponses = {
/**
* Successful Response
*/
200: ResFirstSnow;
};
export type GetFirstSnowResponse = GetFirstSnowResponses[keyof GetFirstSnowResponses];
export type GetFeedData = {
body?: never;
headers?: {
+10
View File
@@ -41,6 +41,11 @@ export type Events<Sheet extends string = string> = {
shorts_preview: { video_id: string; trigger: 'hover' | 'auto' }
foliage_open: Record<string, never>
foliage_spot: { spot_name: string; from: 'page' | 'card' }
first_snow_open: Record<string, never>
first_snow_spot: { spot_name: string; from: 'page' | 'card' }
sunrise_open: Record<string, never>
sunrise_spot: { spot_name: string; from: 'page' | 'card' }
sunrise_day: { day: 'next' | 'newyear' }
my_gak_save: { gak_name: string }
fortune_draw: { card: string }
day_log: { mood: number; went_out: boolean; card_hit: boolean | null }
@@ -90,6 +95,11 @@ export const GA_NAME: Record<keyof Events, string> = {
shorts_preview: '쇼츠_미리보기',
foliage_open: '단풍지도_열기',
foliage_spot: '단풍명소_보기',
first_snow_open: '첫눈지도_열기',
first_snow_spot: '첫눈지점_보기',
sunrise_open: '해돋이지도_열기',
sunrise_spot: '해돋이명소_보기',
sunrise_day: '해돋이날짜_전환',
my_gak_save: '내각_저장',
fortune_draw: '타로_뽑기',
day_log: '하루_기록',
+56
View File
@@ -0,0 +1,56 @@
// 첫눈 지도 계산 (웹 frontend/src/b/firstSnow.ts 가 쓴다). 지점·평년 날짜·눈 예보는 API(/v1/season/first-snow, backend/services/first_snow.json)에서 받는다.
// 지도 그림·배치 계산은 단풍 지도(shared/lib/foliage.ts)와 같이 쓴다
import type { FirstSnowSpot } from '../api/client/types.gen'
import { foliageInSeason, foliageToday, md, toXY } from './foliage'
/** soon: 앞으로 7일 안에 눈 예보가 있음, before: 평년 첫눈 날짜가 아직 안 옴, passed: 평년 첫눈 날짜가 지남(눈 예보 없음) */
export type SnowStage = 'soon' | 'before' | 'passed'
/** x·y 는 지도 그림 안 위치(0~1), normal 은 평년 첫눈 날짜('YYYY-MM-DD', 이번 겨울 기준), d 는 오늘부터 그날까지 남은 날 수, snowDate 는 눈 예보가 있는 첫 날 */
export type SnowSpot = { name: string; region: string; top: boolean; x: number; y: number; normal: string; d: number; stage: SnowStage; snowDate: string | null; snowCm: number | null }
export const SNOW_STAGE: Record<SnowStage, string> = { soon: '눈 예보', before: '평년 첫눈 전', passed: '평년 첫눈 지남' }
// 첫눈 지도는 단풍 지도가 끝난 다음 날부터(단풍철이 아니면 SEASON_START 부터) SEASON_END 까지 보인다. 그다음 날부터 해돋이 지도(shared/lib/sunrise.ts)
// 평년 첫눈이 가장 이른 대관령이 11/5, 가장 늦은 창원·통영이 12/27 이지만, 해돋이 지도가 새해 전에 충분히 보이도록 12/20 에 끝낸다
const SEASON_START = '11-01'
const SEASON_END = '12-20'
const DAY = 86_400_000
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
/** 오늘이 첫눈 지도철인지 (오늘 아이콘 줄의 첫눈 지도 칸·피드 첫눈 카드를 보일지) */
export function firstSnowInSeason(today: string = foliageToday()) {
const monthDay = today.slice(5)
return monthDay >= SEASON_START && monthDay <= SEASON_END && !foliageInSeason(today)
}
/** today 기준 지점별 단계, 평년 첫눈이 이른 순(같으면 이름 순). 1~6월에 보면 지난겨울 날짜로 본다 */
export function firstSnowOn(today: string, raw: FirstSnowSpot[]): SnowSpot[] {
const year = Number(today.slice(0, 4)) - (Number(today.slice(5, 7)) <= 6 ? 1 : 0)
return raw
.map((s) => {
const normal = `${year}-${s.normal}`
const d = days(today, normal)
const snowDate = s.snow_date ?? null
const stage: SnowStage = snowDate ? 'soon' : d >= 0 ? 'before' : 'passed'
return { name: s.name, region: s.region, top: !!s.top, ...toXY(s.lat, s.lon), normal, d, stage, snowDate, snowCm: s.snow_cm ?? null }
})
.sort((a, b) => a.normal.localeCompare(b.normal) || a.name.localeCompare(b.name))
}
/** 눈 예보가 있는 곳: 예보 날짜가 가까운 순, 같으면 눈이 많이 오는 순 */
export const snowSoon = (spots: SnowSpot[]) =>
spots.filter((m) => m.stage === 'soon').sort((a, b) => (a.snowDate ?? '').localeCompare(b.snowDate ?? '') || (b.snowCm ?? 0) - (a.snowCm ?? 0) || a.name.localeCompare(b.name))
/** '눈 예보: 전북·충남·강원'(눈 예보가 있는 지점이 많은 시·도 3곳). 없으면 아직 없다고, 예보를 못 받았으면 평년 날짜라고 */
export function firstSnowHeadline(spots: SnowSpot[], forecast: boolean) {
if (!forecast) return '지역별 평년 첫눈 날짜예요'
const soon = spots.filter((m) => m.stage === 'soon')
if (!soon.length) return '이번 주 눈 예보는 아직 없어요'
const count = new Map<string, number>()
for (const m of soon) count.set(m.region, (count.get(m.region) ?? 0) + 1)
return `눈 예보: ${[...count].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([p]) => p).join('·')}`
}
/** 지점 옆에 적는 한 줄: 눈 예보가 있으면 '11/27 눈 예보', 없으면 '평년 11/29' */
export const snowNote = (m: SnowSpot) => (m.snowDate ? `${md(m.snowDate)} 눈 예보` : `평년 ${md(m.normal)}`)
+7 -6
View File
@@ -30,7 +30,8 @@ function stage(peak: string, today: string): Stage {
return d <= FIRST_DAYS ? 'first' : 'before'
}
const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size })
/** 위경도 → 지도 그림 안 위치(0~1). 해돋이 지도(shared/lib/sunrise.ts)도 같은 그림을 쓴다 */
export const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size })
// 처음 화면 가로 가운데: 명소 가운데(127.9°)로 잡으면 서해 섬까지 든 땅이 왼쪽으로 쏠려 보여 서쪽으로 당김
export const LAND_CX = toXY(36, 127.65).x
@@ -94,14 +95,14 @@ export function headline(spots: Spot[]) {
export const rankNow = (spots: Spot[]) =>
spots.filter((m) => m.stage === 'peak').sort((a, b) => Math.abs(a.d) - Math.abs(b.d) || Number(b.own) - Number(a.own) || a.name.localeCompare(b.name))
export type Pt = { m: Spot; x: number; y: number; r: number }
export type Pt<M extends { name: string } = Spot> = { m: M; x: number; y: number; r: number }
export type Box = { l: number; t: number; r: number; b: number }
export type LabelSize = Record<string, { w: number; h: number }>
const LABEL_GAP = 4
const overlaps = (a: Box, b: Box) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b
/** 시·도 이름 자리(명소 이름표를 먼저 놓은 뒤): 원래 자리가 잎·점·이름표에 덮이면 둘레를 돌며 가장 가까운 빈자리로 옮긴다(최대 반경 R, 바다 쪽도 됨) */
export function placeProvinces(provs: { name: string; x: number; y: number }[], pts: Pt[], labels: Box[] = [], R = 90) {
export function placeProvinces(provs: { name: string; x: number; y: number }[], pts: { x: number; y: number; r: number }[], labels: Box[] = [], R = 90) {
// 앞에서 놓은 시·도 이름도 피한다(서울·경기처럼 붙은 곳)
const placed: Box[] = []
const free = (x: number, y: number) =>
@@ -131,7 +132,7 @@ export const labelBoxes = (at: Record<string, { left: number; top: number }>, si
Object.entries(at).map(([n, a]) => ({ l: a.left, t: a.top, r: a.left + (size[n]?.w ?? 0), b: a.top + (size[n]?.h ?? 0) }))
/** 화면 위 점끼리 겹치면 서로 밀어 떼어 놓는다 (pts 를 고쳐서 돌려줌) */
export function spread(pts: Pt[], gap = 1.5) {
export function spread<P extends { x: number; y: number; r: number }>(pts: P[], gap = 1.5) {
for (let it = 0; it < 60; it++) {
let moved = false
for (let i = 0; i < pts.length; i++)
@@ -157,7 +158,7 @@ export function spread(pts: Pt[], gap = 1.5) {
}
/** 이름표를 점 오른쪽·왼쪽 순으로 놓아 보고(잎과 짝이 헷갈리지 않게 옆 먼저), 점·다른 이름표·막힌 칸과 겹치거나 영역 밖이면 그 이름은 뺀다. 앞 순서가 먼저 자리를 잡는다 */
export function placeLabels(order: Pt[], all: Pt[], size: LabelSize, area: Box, blocked: Box[] = [], vertical: (p: Pt) => boolean = () => false) {
export function placeLabels<M extends { name: string }>(order: Pt<M>[], all: Pt<M>[], size: LabelSize, area: Box, blocked: Box[] = [], vertical: (p: Pt<M>) => boolean = () => false) {
const dots = all.map((p) => ({ name: p.m.name, box: { l: p.x - p.r, t: p.y - p.r, r: p.x + p.r, b: p.y + p.r } }))
const taken = [...blocked.map((box) => ({ name: '', box })), ...dots]
const out: Record<string, { left: number; top: number }> = {}
@@ -190,7 +191,7 @@ export function placeLabels(order: Pt[], all: Pt[], size: LabelSize, area: Box,
}
/** 누른 자리에서 가장 가까운 명소 (잎이 작아 손가락으로 겨냥하기 어려워서). 반경 r 안에 없으면 null */
export function nearest(pts: Pt[], x: number, y: number, r = 24) {
export function nearest(pts: Pt<{ name: string }>[], x: number, y: number, r = 24) {
let best: string | null = null
let bestD = r
for (const p of pts) {
+90
View File
@@ -0,0 +1,90 @@
// 해돋이 지도 데이터·계산 (웹 frontend/src/b/sunrise.ts 가 쓴다). 지도 그림·배치 계산은 단풍 지도(shared/lib/foliage.ts)와 같이 쓴다
import data from '../../frontend/seo/sunrise_spots.json'
import { kst } from '.'
import { firstSnowInSeason } from './firstSnow'
import { foliageToday, toXY } from './foliage'
export type Coast = 'east' | 'south' | 'west' | 'inland'
type Raw = { name: string; coast: Coast; region: string; lat: number; lon: number; top?: boolean }
/** x·y 는 지도 그림 안 위치(0~1), rise·dawn 은 그날 0시부터 센 분(한국 시각), az 는 해 뜨는 방향(북 0° 시계 방향), top 은 대표 명소 */
export type SunSpot = { name: string; coast: Coast; region: string; top: boolean; x: number; y: number; rise: number; dawn: number; az: number }
/** next 는 다가오는 해돋이(아침 9시 전이면 오늘, 지나면 내일), newyear 는 1월 1일 */
export type SunDayKey = 'next' | 'newyear'
export type SunDay = { key: SunDayKey; date: string; label: string }
export const COAST: Record<Coast, string> = { east: '동해', south: '남해·제주', west: '서해', inland: '산·도심' }
// 해 뜨는 시각: 해 윗부분이 수평선에 닿는 때(대기 굴절 포함 -0.833°). 여명: 해 고도 -6°(시민박명), 이때부터 하늘이 밝아진다
const SUN_ALTITUDE = -0.833
const CIVIL_ALTITUDE = -6
const KST_MIN = 540
// 이 시각이 지나면 오늘 해돋이는 끝난 것으로 보고 내일 것을 보여 준다
const NEXT_FROM_HOUR = 9
const SEASON_MONTHS = [12, 1, 2]
const DOKDO = { lat: 37.2426, lon: 131.8672 }
const DIRS = ['북', '북동', '동', '남동', '남', '남서', '서', '북서']
const DAY = 86_400_000
const rad = (d: number) => (d * Math.PI) / 180
const deg = (r: number) => (r * 180) / Math.PI
/** NOAA 근사식(backend/services/calc/sun.py 와 같은 식). 태양 적위(라디안)와 남중 시각(UTC 분) */
function solar(iso: string, lon: number) {
const [y, m, d] = iso.split('-').map(Number)
const g = ((2 * Math.PI) / 365) * Math.round((Date.UTC(y, m - 1, d) - Date.UTC(y, 0, 1)) / DAY)
const eqtime = 229.18 * (0.000075 + 0.001868 * Math.cos(g) - 0.032077 * Math.sin(g) - 0.014615 * Math.cos(2 * g) - 0.040849 * Math.sin(2 * g))
const decl =
0.006918 - 0.399912 * Math.cos(g) + 0.070257 * Math.sin(g) - 0.006758 * Math.cos(2 * g) + 0.000907 * Math.sin(2 * g) - 0.002697 * Math.cos(3 * g) + 0.00148 * Math.sin(3 * g)
return { decl, noon: 720 - 4 * lon - eqtime }
}
/** 해가 그 고도에 있을 때부터 남중까지 걸리는 분 */
function untilNoon(lat: number, decl: number, altitude: number) {
const cosH = (Math.sin(rad(altitude)) - Math.sin(rad(lat)) * Math.sin(decl)) / (Math.cos(rad(lat)) * Math.cos(decl))
return deg(Math.acos(Math.max(-1, Math.min(1, cosH)))) * 4
}
/** 그날 그 자리의 해 뜨는 시각·여명 시작(0시부터 센 분, 한국 시각)과 해 뜨는 방향. 해발 0m 기준 */
export function sunriseAt(iso: string, lat: number, lon: number) {
const { decl, noon } = solar(iso, lon)
return {
rise: noon - untilNoon(lat, decl, SUN_ALTITUDE) + KST_MIN,
dawn: noon - untilNoon(lat, decl, CIVIL_ALTITUDE) + KST_MIN,
az: Math.round(deg(Math.acos(Math.max(-1, Math.min(1, Math.sin(decl) / Math.cos(rad(lat))))))),
}
}
/** 0시부터 센 분 → '7:31' */
export function clock(min: number) {
const m = Math.round(min)
return `${Math.floor(m / 60)}:${String(m % 60).padStart(2, '0')}`
}
/** 118° → '남동' */
export const direction = (az: number) => DIRS[Math.round(az / 45) % 8]
/** 고를 수 있는 날: 12월엔 새해 첫날이 먼저, 그다음 다가오는 해돋이. 다가오는 해돋이가 1월 1일이면 새해 첫날 하나만 */
export function sunriseDays(now: Date = new Date()): SunDay[] {
const t = kst(now)
const today = t.h < NEXT_FROM_HOUR
const date = new Date(Date.UTC(t.y, t.mo - 1, t.d + (today ? 0 : 1))).toISOString().slice(0, 10)
if (date.endsWith('-01-01')) return [{ key: 'newyear', date, label: '새해 첫날' }]
const next: SunDay = { key: 'next', date, label: today ? '오늘' : '내일' }
return t.mo === 12 ? [{ key: 'newyear', date: `${t.y + 1}-01-01`, label: '새해 첫날' }, next] : [next]
}
/** 지금이 해돋이철인지 (오늘 아이콘 줄의 해돋이 지도 칸·피드 해돋이 카드를 보일지). 12~2월 가운데 첫눈 지도가 끝난 다음 날부터: 같은 자리를 첫눈 지도가 먼저 쓴다 */
export const sunriseInSeason = (now: Date = new Date()) => SEASON_MONTHS.includes(kst(now).mo) && !firstSnowInSeason(foliageToday(now))
/** 그날 명소별 해 뜨는 시각, 이른 순(같으면 이름 순) */
export function sunriseOn(date: string): SunSpot[] {
return (data.spots as Raw[])
.map(({ name, coast, region, lat, lon, top }) => ({ name, coast, region, top: !!top, ...toXY(lat, lon), ...sunriseAt(date, lat, lon) }))
.sort((a, b) => Math.round(a.rise) - Math.round(b.rise) || a.name.localeCompare(b.name))
}
/** 우리나라에서 해가 가장 먼저 뜨는 독도의 그날 해 뜨는 시각 (지도 그림 밖이라 명소 목록에는 없다) */
export const dokdoRise = (date: string) => sunriseAt(date, DOKDO.lat, DOKDO.lon).rise
/** '새해 첫 해는 간절곶 7:31부터' — spots 는 이른 순 */
export const sunriseHeadline = (day: SunDay, spots: SunSpot[]) => `${day.key === 'newyear' ? '새해' : day.label} 첫 해는 ${spots[0].name} ${clock(spots[0].rise)}부터`