From d7dfc1ba825a4cef50809476893b88940eeae3a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Fri, 20 Nov 2026 11:18:54 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EA=B3=84=EC=A0=88=20=EC=A7=80=EB=8F=84?= =?UTF-8?q?=20=EC=9E=90=EB=A6=AC=EC=97=90=20=EC=B2=AB=EB=88=88=20=EC=A7=80?= =?UTF-8?q?=EB=8F=84=C2=B7=ED=95=B4=EB=8F=8B=EC=9D=B4=20=EC=A7=80=EB=8F=84?= =?UTF-8?q?=20=E2=80=94=20=EB=8B=A8=ED=92=8D=20=EC=A7=80=EB=8F=84=EA=B0=80?= =?UTF-8?q?=20=EB=81=9D=EB=82=98=EB=A9=B4=20=EC=B2=AB=EB=88=88=20=EC=A7=80?= =?UTF-8?q?=EB=8F=84(~12/20,=20=EC=A7=80=EC=A0=90=2042=EA=B3=B3=20?= =?UTF-8?q?=ED=8F=89=EB=85=84=20=EC=B2=AB=EB=88=88=20=EB=82=A0=EC=A7=9C=20?= =?UTF-8?q?+=20=EC=95=9E=EC=9C=BC=EB=A1=9C=207=EC=9D=BC=20=EB=88=88=20?= =?UTF-8?q?=EC=98=88=EB=B3=B4,=20GET=20/v1/season/first-snow),=2012/21?= =?UTF-8?q?=EB=B6=80=ED=84=B0=20=ED=95=B4=EB=8F=8B=EC=9D=B4=20=EC=A7=80?= =?UTF-8?q?=EB=8F=84(~2=EC=9B=94,=20=EB=AA=85=EC=86=8C=2050=EA=B3=B3=20?= =?UTF-8?q?=ED=95=B4=20=EB=9C=A8=EB=8A=94=20=EC=8B=9C=EA=B0=81,=2012?= =?UTF-8?q?=EC=9B=94=EC=97=94=20=EC=83=88=ED=95=B4=20=EC=B2=AB=EB=82=A0=20?= =?UTF-8?q?=EA=B8=B0=EC=A4=80).=20=EC=98=A4=EB=8A=98=20=ED=83=AD=20?= =?UTF-8?q?=EC=95=84=EC=9D=B4=EC=BD=98=C2=B7=ED=94=BC=EB=93=9C=20=EB=A7=A8?= =?UTF-8?q?=20=EC=95=9E=20=EC=B9=B4=EB=93=9C(foliage=5Fpost=20=EC=A2=8B?= =?UTF-8?q?=EC=95=84=EC=9A=94=C2=B7=EB=8C=93=EA=B8=80=20=EC=9E=90=EB=A6=AC?= =?UTF-8?q?=EB=A5=BC=20=EC=9D=B4=EC=96=B4=EB=B0=9B=EC=9D=8C)=C2=B7/first-s?= =?UTF-8?q?now=C2=B7/sunrise=20=ED=8E=98=EC=9D=B4=EC=A7=80=C2=B7=EA=B3=B5?= =?UTF-8?q?=EC=9C=A0=20=EC=9D=B4=EB=AF=B8=EC=A7=80.=20=EC=A7=80=EB=8F=84?= =?UTF-8?q?=20=ED=99=95=EB=8C=80=C2=B7=EC=9D=B4=EB=8F=99=EC=9D=80=20mapVie?= =?UTF-8?q?w.ts=20=EB=A1=9C=20=EA=BA=BC=EB=82=B4=20=EB=8B=A8=ED=92=8D=20?= =?UTF-8?q?=EC=A7=80=EB=8F=84=EC=99=80=20=EA=B0=99=EC=9D=B4=20=EC=94=80=20?= =?UTF-8?q?(GA=20first=5Fsnow=5Fopen=C2=B7first=5Fsnow=5Fspot=C2=B7sunrise?= =?UTF-8?q?=5Fopen=C2=B7sunrise=5Fspot=C2=B7sunrise=5Fday)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/router/v1/season/protocol.py | 16 ++ backend/router/v1/season/season.py | 10 +- backend/services/external/open_meteo.py | 28 +- backend/services/first_snow.json | 48 ++++ backend/services/first_snow_service.py | 76 +++++ backend/tests/test_first_snow.py | 70 +++++ docs/이벤트_추적.md | 9 +- frontend/index.html | 4 + frontend/seo/sunrise_spots.json | 55 ++++ frontend/src/App.tsx | 4 + frontend/src/b/FirstSnowPage.tsx | 260 ++++++++++++++++++ frontend/src/b/FoliagePage.tsx | 251 +---------------- frontend/src/b/SunrisePage.tsx | 248 +++++++++++++++++ frontend/src/b/TodayPage.tsx | 6 +- frontend/src/b/firstSnow.ts | 31 +++ frontend/src/b/firstSnowMap.tsx | 197 +++++++++++++ frontend/src/b/mapView.ts | 242 ++++++++++++++++ frontend/src/b/shareCards.tsx | 163 +++++++++++ frontend/src/b/sunrise.ts | 30 ++ frontend/src/b/sunriseMap.tsx | 182 ++++++++++++ frontend/src/b/todayIcons.tsx | 9 +- frontend/vite.config.ts | 14 + .../api/client/@tanstack/react-query.gen.ts | 22 +- shared/api/client/index.ts | 4 +- shared/api/client/sdk.gen.ts | 7 +- shared/api/client/types.gen.ts | 73 +++++ shared/lib/analytics.ts | 10 + shared/lib/firstSnow.ts | 56 ++++ shared/lib/foliage.ts | 13 +- shared/lib/sunrise.ts | 90 ++++++ 30 files changed, 1973 insertions(+), 255 deletions(-) create mode 100644 backend/services/first_snow.json create mode 100644 backend/services/first_snow_service.py create mode 100644 backend/tests/test_first_snow.py create mode 100644 frontend/seo/sunrise_spots.json create mode 100644 frontend/src/b/FirstSnowPage.tsx create mode 100644 frontend/src/b/SunrisePage.tsx create mode 100644 frontend/src/b/firstSnow.ts create mode 100644 frontend/src/b/firstSnowMap.tsx create mode 100644 frontend/src/b/mapView.ts create mode 100644 frontend/src/b/sunrise.ts create mode 100644 frontend/src/b/sunriseMap.tsx create mode 100644 shared/lib/firstSnow.ts create mode 100644 shared/lib/sunrise.ts diff --git a/backend/router/v1/season/protocol.py b/backend/router/v1/season/protocol.py index 240b824..1499c9f 100644 --- a/backend/router/v1/season/protocol.py +++ b/backend/router/v1/season/protocol.py @@ -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] = [] diff --git a/backend/router/v1/season/season.py b/backend/router/v1/season/season.py index 6d7dd36..b26fc87 100644 --- a/backend/router/v1/season/season.py +++ b/backend/router/v1/season/season.py @@ -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]) diff --git a/backend/services/external/open_meteo.py b/backend/services/external/open_meteo.py index 708ba39..945d284 100644 --- a/backend/services/external/open_meteo.py +++ b/backend/services/external/open_meteo.py @@ -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"] diff --git a/backend/services/first_snow.json b/backend/services/first_snow.json new file mode 100644 index 0000000..640dd88 --- /dev/null +++ b/backend/services/first_snow.json @@ -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" } + ] +} diff --git a/backend/services/first_snow_service.py b/backend/services/first_snow_service.py new file mode 100644 index 0000000..e542f41 --- /dev/null +++ b/backend/services/first_snow_service.py @@ -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 diff --git a/backend/tests/test_first_snow.py b/backend/tests/test_first_snow.py new file mode 100644 index 0000000..36b78e7 --- /dev/null +++ b/backend/tests/test_first_snow.py @@ -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"]) diff --git a/docs/이벤트_추적.md b/docs/이벤트_추적.md index b8f9025..6eb4406 100644 --- a/docs/이벤트_추적.md +++ b/docs/이벤트_추적.md @@ -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` | diff --git a/frontend/index.html b/frontend/index.html index db8fe56..9ceb877 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -205,6 +205,10 @@

같은 날씨끼리 합쳐 해를 만드는 구름 합치기 게임이에요. 우리 동네 지금 바람만큼 구름이 옆으로 밀려 떨어져요.

단풍 지도

산림청 단풍 절정 예측으로 전국 단풍 명소의 절정 시기를 지도에서 확인하세요.

+

첫눈 지도

+

서울, 춘천, 대전, 광주, 대구, 부산, 제주 등 전국 지역별 평년 첫눈 날짜와 앞으로 7일 눈 예보를 지도에서 확인하세요.

+

해돋이 지도

+

정동진, 호미곶, 간절곶, 성산일출봉 같은 전국 해돋이 명소의 새해 첫날 해 뜨는 시각을 지도에서 확인하세요.

동네 이야기

지금 우리 동네 하늘과 노을, 비·눈, 단풍·꽃, 오늘 옷차림 이야기를 동네 사람들과 나눠요.

날씨 쇼츠

diff --git a/frontend/seo/sunrise_spots.json b/frontend/seo/sunrise_spots.json new file mode 100644 index 0000000..b392814 --- /dev/null +++ b/frontend/seo/sunrise_spots.json @@ -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" } + ] +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 9f3fd4f..5b88b10 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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() { } /> } /> } /> + } /> + } /> } /> } /> } /> diff --git a/frontend/src/b/FirstSnowPage.tsx b/frontend/src/b/FirstSnowPage.tsx new file mode 100644 index 0000000..c6e4ecc --- /dev/null +++ b/frontend/src/b/FirstSnowPage.tsx @@ -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 = { 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 + return +} + +function Marker({ p, sel }: { p: Pt; sel: boolean }) { + return ( + + {/* 고른 지점은 속이 빈 고리만: 옆 지점을 가리지 않게 */} + {sel && } + + + ) +} + +/** 첫눈 지도 페이지: 지점 42곳의 평년 첫눈 날짜와 앞으로 7일 눈 예보를 지도에서 확대해 보고 목록으로 고른다. 확대·이동은 mapView.ts */ +export function FirstSnowPage() { + const navigate = useNavigate() + const [params] = useSearchParams() + const { today, spots, forecast, load, refetch } = useFirstSnow() + const [sel, setSel] = useState(params.get('spot')) + const { open } = useSheet() + const [shareSpot, setShareSpot] = useState(null) + const [shareReq, setShareReq] = useState(0) + const spotShotRef = useRef(null) + const mapShotRef = useRef(null) + useEffect(() => track('first_snow_open', {}), []) + useEffect(() => { + if (sel) track('first_snow_spot', { spot_name: sel, from: 'page' }) + }, [sel]) + + const vpRef = useRef(null) + const size = useLabelSize(vpRef, spots) + const ptsRef = useRef[]>([]) + 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 ( +
+
+ +
+

+ + 첫눈 지도 · {md(today)} +

+

{title}

+
+ {spots.length > 0 && ( + + )} +
+ +
+ {spots.length > 0 && 첫눈 지도} + {spots.length > 0 && + provs.map((v) => ( + + ))} + {[...pts].sort((a, b) => Number(a.m.stage === 'soon') - Number(b.m.stage === 'soon')).map((p) => ( + + ))} + {spots.map((m) => ( + + ))} + {spots.length > 0 && ( +
+ {( + [ + ['+', '확대', 1.6], + ['−', '축소', 1 / 1.6], + ] as const + ).map(([t, label, f]) => ( + + ))} +
+ )} + {!spots.length && refetch()} empty="첫눈 정보가 아직 없어요." className="absolute inset-x-3 top-1/2 -translate-y-1/2" />} +
+ + {/* 고른 지점은 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */} + {chosen ? ( +
+ + + +
+

+ {chosen.name} + {SNOW_STAGE[chosen.stage]} +

+

+ 평년 첫눈 {md(chosen.normal)} + {chosen.snowDate && ` · ${md(chosen.snowDate)} 눈 예보(${amount(chosen.snowCm)})`} +

+
+ +
+ ) : ( +
+ + 눈 예보 날짜 + + + + 평년 첫눈 날짜 + + + + 평년 첫눈 지남 + +
+ )} + +
+ {GROUPS.map(([g, heading]) => { + const rows = g === 'soon' ? soon : spots.filter((m) => m.stage === g) + if (!rows.length) return null + return ( +
+

+ {heading} + {rows.length}곳 +

+
    + {rows.map((m) => ( +
  • + + +
  • + ))} +
+
+ ) + })} + + +

+ 평년 첫눈은 기상청 1991~2020년 평균이에요(춘천·강릉은 북춘천·북강릉 관측소). 눈 예보는 앞으로 7일을 보고, 실제 첫눈은 평년 날짜·예보와 다를 수 있어요 + {!forecast && load === 'ready' ? ' · 지금은 눈 예보를 받지 못해 평년 날짜만 보여 드려요' : ''} +

+
+
+ ) +} diff --git a/frontend/src/b/FoliagePage.tsx b/frontend/src/b/FoliagePage.tsx index 0461ae1..f693408 100644 --- a/frontend/src/b/FoliagePage.tsx +++ b/frontend/src/b/FoliagePage.tsx @@ -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 = { 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('all') const [sel, setSel] = useState(params.get('spot')) - const linked = useRef(params.get('spot')) const { open } = useSheet() const [shareSpot, setShareSpot] = useState(null) const [shareReq, setShareReq] = useState(0) @@ -73,111 +69,24 @@ export function FoliagePage() { }, [sel]) const vpRef = useRef(null) - const [box, setBox] = useState({ W: 0, H: 0 }) - const [view, setView] = useState({ s: 1, tx: 0, ty: 0 }) - const viewRef = useRef(view) - useLayoutEffect(() => { - viewRef.current = view - }, [view]) const size = useLabelSize(vpRef, spots) - - // 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데 - const fit = useMemo(() => { - 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([]) + 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) diff --git a/frontend/src/b/SunrisePage.tsx b/frontend/src/b/SunrisePage.tsx new file mode 100644 index 0000000..04f16dc --- /dev/null +++ b/frontend/src/b/SunrisePage.tsx @@ -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 + return +} + +function Marker({ p, sel }: { p: Pt; sel: boolean }) { + return ( + + {/* 고른 명소는 속이 빈 고리만: 옆 명소를 가리지 않게 */} + {sel && } + + + ) +} + +/** 해돋이 지도 페이지: 명소 50곳의 해 뜨는 시각을 지도에서 확대해 보고 이른 순 목록으로 고른다. 확대·이동은 mapView.ts */ +export function SunrisePage() { + const navigate = useNavigate() + const [params] = useSearchParams() + const { days, day, setDay, spots } = useSunrise() + const [filter, setFilter] = useState('all') + const [sel, setSel] = useState(params.get('spot')) + const { open } = useSheet() + const [shareSpot, setShareSpot] = useState(null) + const [shareReq, setShareReq] = useState(0) + const spotShotRef = useRef(null) + const mapShotRef = useRef(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(null) + const size = useLabelSize(vpRef, spots) + const ptsRef = useRef[]>([]) + 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 ( +
+
+ +
+

+ + 해돋이 지도 · {when} +

+

{sunriseHeadline(day, spots)}

+
+ +
+ + {days.length > 1 && [d.key, `${d.label} ${md(d.date)}`] as const)} value={day.key} onChange={pickDay} />} + +
+ 해돋이 지도 + {provs.map((v) => ( + + ))} + {[...pts].sort((a, b) => Number(a.m.top) - Number(b.m.top)).map((p) => ( + + ))} + {spots.map((m) => ( + + ))} +
+ {( + [ + ['+', '확대', 1.6], + ['−', '축소', 1 / 1.6], + ] as const + ).map(([t, label, f]) => ( + + ))} +
+
+ + {/* 고른 명소는 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */} + {chosen ? ( +
+ + + +
+

+ {chosen.name} + {COAST[chosen.coast]} +

+

+ {chosen.region} + + · {clock(chosen.dawn)}부터 밝아져요 · {direction(chosen.az)}쪽 + +

+
+ {clock(chosen.rise)} + +
+ ) : ( +
+ + + 대표 명소 + + + 그 밖의 명소 + + 숫자는 해 뜨는 시각 +
+ )} + + +
+
+

+ 해가 먼저 뜨는 순서 + {shown.length}곳 +

+
    + {shown.map((m) => ( +
  1. + + +
  2. + ))} +
+
+ + +

+ 해 뜨는 시각은 명소 위치로 계산한 값이에요(바다 높이 기준, 1분쯤 다를 수 있어요). 높은 산 위에서는 몇 분 더 일찍 보여요 · 우리나라에서 가장 먼저 뜨는 독도는 {clock(dokdoRise(day.date))} +

+
+
+ ) +} diff --git a/frontend/src/b/TodayPage.tsx b/frontend/src/b/TodayPage.tsx index 7d755e5..c287258 100644 --- a/frontend/src/b/TodayPage.tsx +++ b/frontend/src/b/TodayPage.tsx @@ -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 && ( } className="inset-x-3 top-3.5 bottom-auto" /> )} - {/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */} + {/* 계절 지도 카드를 포스트 맨 앞에: 단풍 지도 → 첫눈 지도 → 해돋이 지도 순으로 한 번에 하나만. 좋아요·댓글 자리(foliage_post)는 같이 쓴다 */} {load !== 'loading' && posts.length > 0 && } + {load !== 'loading' && posts.length > 0 && } + {load !== 'loading' && posts.length > 0 && } {posts.map((p, i) => { const t = talkAt(i) const ev = eventNo.get(p.post_id) diff --git a/frontend/src/b/firstSnow.ts b/frontend/src/b/firstSnow.ts new file mode 100644 index 0000000..dd6c49a --- /dev/null +++ b/frontend/src/b/firstSnow.ts @@ -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' } diff --git a/frontend/src/b/firstSnowMap.tsx b/frontend/src/b/firstSnowMap.tsx new file mode 100644 index 0000000..4ba6b38 --- /dev/null +++ b/frontend/src/b/firstSnowMap.tsx @@ -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(null) + const size = useLabelSize(mapRef, shown) + const [W, setW] = useState(0) + const [picked, setPicked] = useState(null) + const { open } = useSheet() + const spotShotRef = useRef(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) => { + 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 ( + +
+

첫눈 지도 · {md(today)}

+

{firstSnowHeadline(spots, forecast)}

+
+ +
+
+
+ {/* 그림의 빈 가장자리는 잘라 쓴다(CROP_IMG) */} +
+ + {provs.map((v) => ( + + ))} + {pts.map((p) => ( + + {p.m.name === picked && } + {p.m.stage === 'soon' ? : } + + ))} + {shown.map((m) => ( + + ))} +
+ {/* 고른 지점 정보는 지도 밖, 범례 자리에: 지도 위 표시를 가리지 않게 */} + {sel ? ( +
+ +
+ {sel.name} + + 평년 첫눈 {md(sel.normal)} + {sel.snowDate && ` · ${md(sel.snowDate)} 눈 예보`} + +
+ + +
+ ) : ( + + + 눈 예보 날짜 + + + + 평년 첫눈 날짜 + + + )} +
+
+

{soon.length ? '눈 예보가 있는 곳' : '평년 첫눈이 가까운 곳'}

+

{soon.length ? '앞으로 7일, 눈 예보가 가까운 순서예요' : '평년 첫눈 날짜가 가까운 순서예요'}

+
    + {ranked.map((m, i) => ( +
  1. + +
  2. + ))} +
+
+
+
+
+ + +
+
+ ) +} diff --git a/frontend/src/b/mapView.ts b/frontend/src/b/mapView.ts new file mode 100644 index 0000000..83795e7 --- /dev/null +++ b/frontend/src/b/mapView.ts @@ -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, places: Place[], linked: string | null, pickAt: (x: number, y: number) => void) { + const [box, setBox] = useState({ W: 0, H: 0 }) + const [view, setView] = useState({ s: 1, tx: 0, ty: 0 }) + const viewRef = useRef(view) + useLayoutEffect(() => { + viewRef.current = view + }, [view]) + const linkedRef = useRef(linked) + + // 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데 + const fit = useMemo(() => { + 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 } +} diff --git a/frontend/src/b/shareCards.tsx b/frontend/src/b/shareCards.tsx index d7e275f..3cf717d 100644 --- a/frontend/src/b/shareCards.tsx +++ b/frontend/src/b/shareCards.tsx @@ -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 }) { + if (!spot) return null + const near = tops.filter((m) => m.name !== spot.name) + return ( + +
+
+ {/* 명소가 가운데 오게 지도 그림을 키워 옮긴다 */} +
+ + {PROVINCES.map((v) => ( + + {v.name} + + ))} + {near.map((m) => ( + + ))} +
+ + + +
+
+

+ {spot.name} + {COAST[spot.coast]} +

+

+ {spot.region} · {clock(spot.dawn)}부터 밝아져요 · {direction(spot.az)}쪽 +

+

+ {when} 해 뜨는 시각 {clock(spot.rise)} +

+
+
+
+ ) +} + +/** 해돋이 지도 전체 공유: 제목, 대표 명소에 해가 찍힌 지도, 해가 먼저 뜨는 곳 1~3위. ranked 는 이른 순 */ +export function SunriseMapShare({ title, when, tops, ranked, ref }: { title: string; when: string; tops: SunSpot[]; ranked: SunSpot[]; ref: Ref }) { + return ( + +
+

해돋이 지도 · {when}

+

{title}

+
+ + {PROVINCES.map((v) => { + const at = cropXY(v.x, v.y) + return ( + + {v.name} + + ) + })} + {tops.map((m) => { + const at = cropXY(m.x, m.y) + return + })} +
+
    + {ranked.slice(0, 3).map((m, i) => ( +
  1. + + {m.name} + {m.region} + {clock(m.rise)} +
  2. + ))} +
+
+
+ ) +} + +/** 첫눈 지점 하나 공유: 그 지점을 가운데 둔 지도 조각(둘레 시·도 이름과 눈 예보가 있는 다른 곳) 위에 큰 눈송이, 아래에 이름·평년 첫눈 날짜·눈 예보 */ +export function FirstSnowSpotShare({ spot, soon, ref }: { spot: SnowSpot | null; soon: SnowSpot[]; ref: Ref }) { + if (!spot) return null + const near = soon.filter((m) => m.name !== spot.name) + return ( + +
+
+ {/* 지점이 가운데 오게 지도 그림을 키워 옮긴다 */} +
+ + {PROVINCES.map((v) => ( + + {v.name} + + ))} + {near.map((m) => ( + + ))} +
+ + + +
+
+

+ {spot.name} + {SNOW_STAGE[spot.stage]} +

+

{spot.region}

+

+ 평년 첫눈 {md(spot.normal)} + {spot.snowDate && · {md(spot.snowDate)} 눈 예보} +

+
+
+
+ ) +} + +/** 첫눈 지도 전체 공유: 제목, 눈 예보가 있는 곳은 눈송이·나머지는 점이 찍힌 지도, 눈 예보가 가까운 곳(없으면 평년 첫눈이 가까운 곳) 1~3위. spots 는 평년 첫눈이 이른 순 */ +export function FirstSnowMapShare({ title, today, soon, spots, ref }: { title: string; today: string; soon: SnowSpot[]; spots: SnowSpot[]; ref: Ref }) { + const rows = (soon.length ? soon : spots.filter((m) => m.stage === 'before')).slice(0, 3) + return ( + +
+

첫눈 지도 · {md(today)}

+

{title}

+
+ + {PROVINCES.map((v) => { + const at = cropXY(v.x, v.y) + return ( + + {v.name} + + ) + })} + {spots.map((m) => { + const at = cropXY(m.x, m.y) + const style = { left: `${at.x * 100}%`, top: `${at.y * 100}%` } + return m.stage === 'soon' ? ( + + ) : ( + + ) + })} +
+
    + {rows.map((m) => ( +
  1. + + {m.name} + {m.snowDate ? '눈 예보' : '평년 첫눈'} + {md(m.snowDate ?? m.normal)} +
  2. + ))} +
+
+
+ ) +} + /** 내 각 공유: 아이콘·이름·점수, 조건마다 막대와 실제 값. 로고·지역·날짜는 공유 틀이 그린다 */ 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 }) { return ( diff --git a/frontend/src/b/sunrise.ts b/frontend/src/b/sunrise.ts new file mode 100644 index 0000000..1747309 --- /dev/null +++ b/frontend/src/b/sunrise.ts @@ -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(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}%` } diff --git a/frontend/src/b/sunriseMap.tsx b/frontend/src/b/sunriseMap.tsx new file mode 100644 index 0000000..1a1c601 --- /dev/null +++ b/frontend/src/b/sunriseMap.tsx @@ -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(null) + const size = useLabelSize(mapRef, tops) + const [W, setW] = useState(0) + const [picked, setPicked] = useState(null) + const { open } = useSheet() + const spotShotRef = useRef(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) => { + 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 ( + `${m.name} ${clock(m.rise)}`).join(' · ')}`}> +
+

해돋이 지도 · {when}

+

{sunriseHeadline(day, spots)}

+
+ +
+
+
+ {/* 그림의 빈 가장자리는 잘라 쓴다(CROP_IMG) */} +
+ + {provs.map((v) => ( + + ))} + {pts.map((p) => ( + + {p.m.name === picked && } + + + ))} + {tops.map((m) => ( + + ))} +
+ {/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 해를 가리지 않게 */} + {sel ? ( +
+ +
+ {sel.name} + + {COAST[sel.coast]} + · 해 뜨는 시각 {clock(sel.rise)} + +
+ + +
+ ) : ( + + + 대표 명소의 해 뜨는 시각이에요 + + )} +
+
+

해가 먼저 뜨는 곳

+

{when} 해 뜨는 시각이 이른 순서예요

+
    + {ranked.map((m, i) => ( +
  1. + +
  2. + ))} +
+
+
+
+
+ + +
+
+ ) +} diff --git a/frontend/src/b/todayIcons.tsx b/frontend/src/b/todayIcons.tsx index 11c8f90..01f985b 100644 --- a/frontend/src/b/todayIcons.tsx +++ b/frontend/src/b/todayIcons.tsx @@ -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 : , 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' }, diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index d808b29..0ae1cbb 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -70,6 +70,20 @@ const PAGES: { path: string; title: string; description: string; body: string; c keywords: '단풍 지도, 단풍 절정, 단풍 시기, 단풍 명소, 은행나무 명소, 날씨각', body: '

날씨각 · 단풍 지도

산림청 단풍 절정 예측으로 전국 단풍 명소의 절정 시기를 지도에서 보여 드려요. 잎 절반이 물든 때를 절정으로 보고, 지금 절정·곧 절정·아직·절정 지남으로 나눠 볼 수 있어요.

단풍과 은행을 따로 골라 볼 수 있어요.

', }, + { + path: 'first-snow', + title: '첫눈 지도 · 지역별 평년 첫눈 날짜와 눈 예보 | 날씨각', + description: '서울, 춘천, 대전, 광주, 대구, 부산, 제주 등 전국 42곳의 평년 첫눈 날짜와 앞으로 7일 눈 예보를 지도에서 확인하세요.', + keywords: '첫눈 지도, 첫눈 날짜, 첫눈 시기, 평년 첫눈, 눈 예보, 날씨각', + body: '

날씨각 · 첫눈 지도

전국 42곳의 평년 첫눈 날짜(기상청 1991~2020년 평균)를 지도에서 보여 드려요. 대관령은 11월 초, 서울·대전은 11월 20일쯤, 부산은 12월 하순이 평년 첫눈이에요.

앞으로 7일 안에 눈 예보가 있는 곳은 눈송이로 표시해 드려요. 실제 첫눈은 평년 날짜·예보와 다를 수 있어요.

', + }, + { + path: 'sunrise', + title: '해돋이 지도 · 새해 일출 시간과 해돋이 명소 | 날씨각', + description: '정동진, 호미곶, 간절곶, 성산일출봉 같은 전국 해돋이 명소 50곳의 새해 첫날 해 뜨는 시각을 지도에서 확인하세요. 해가 먼저 뜨는 순서로 보여 드려요.', + keywords: '해돋이 지도, 새해 일출 시간, 해돋이 명소, 일출 명소, 해 뜨는 시각, 날씨각', + body: '

날씨각 · 해돋이 지도

전국 해돋이 명소 50곳의 해 뜨는 시각을 지도에서 보여 드려요. 12월에는 새해 첫날(1월 1일), 그 밖에는 오늘·내일 해 뜨는 시각을 해가 먼저 뜨는 순서로 볼 수 있어요.

동해, 남해·제주, 서해, 산·도심으로 나눠 볼 수 있고, 하늘이 밝아지기 시작하는 시각과 해 뜨는 방향도 알려 드려요.

', + }, { path: 'talk', title: '동네 이야기 · 지금 우리 동네 날씨 이야기 | 날씨각', diff --git a/shared/api/client/@tanstack/react-query.gen.ts b/shared/api/client/@tanstack/react-query.gen.ts index b66c6b1..84ed23c 100644 --- a/shared/api/client/@tanstack/react-query.gen.ts +++ b/shared/api/client/@tanstack/react-query.gen.ts @@ -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, WithdrawResponse } from '../types.gen'; export type QueryKey = [ Pick & { @@ -309,6 +309,24 @@ export const getArticleOptions = (options: Options) => queryOpti queryKey: getArticleQueryKey(options) }); +export const getFirstSnowQueryKey = (options?: Options) => createQueryKey('getFirstSnow', options); + +/** + * 첫눈 지도: 지점별 평년 첫눈 날짜와 앞으로 7일 눈 예보 + */ +export const getFirstSnowOptions = (options?: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await getFirstSnow({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: getFirstSnowQueryKey(options) +}); + export const getFeedQueryKey = (options: Options) => createQueryKey('getFeed', options); /** diff --git a/shared/api/client/index.ts b/shared/api/client/index.ts index a3854e1..6608af7 100644 --- a/shared/api/client/index.ts +++ b/shared/api/client/index.ts @@ -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 GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, type ImportFortuneData, type ImportFortuneError, type ImportFortuneErrors, type ImportFortuneResponse, type ImportFortuneResponses, IndexCategory, type IndexSummary, type LevelAction, type LevelStep, type LevelUnlock, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListBlockedData, type ListBlockedError, type ListBlockedErrors, type ListBlockedResponse, type ListBlockedResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type ListMyTalksErrors, type ListMyTalksResponse, type ListMyTalksResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListPresetsData, type ListPresetsResponse, type ListPresetsResponses, type ListReelsData, type ListReelsError, type ListReelsErrors, type ListReelsResponse, type ListReelsResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type ListShortsData, type ListShortsResponse, type ListShortsResponses, type ListTalkCommentsData, type ListTalkCommentsError, type ListTalkCommentsErrors, type ListTalkCommentsResponse, type ListTalkCommentsResponses, type ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type ListUsersData, type ListUsersError, type ListUsersErrors, type ListUsersResponse, type ListUsersResponses, type LocalDraw, type LocalLog, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type MatchData, type MatchError, type MatchErrors, type MatchResponse, type MatchResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type MyGakPreset, type MyGakRule, type MyGakScore, type MyLevelData, type MyLevelError, type MyLevelErrors, type MyLevelResponse, type MyLevelResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, type PostReaction, PostType, type PublishCardData, type PublishCardError, type PublishCardErrors, type PublishCardResponse, type PublishCardResponses, type PublishInstagram2Data, type PublishInstagram2Error, type PublishInstagram2Errors, type PublishInstagram2Response, type PublishInstagram2Responses, type PublishInstagramData, type PublishInstagramError, type PublishInstagramErrors, type PublishInstagramResponse, type PublishInstagramResponses, type PutBirthData, type PutBirthError, type PutBirthErrors, type PutBirthResponse, type PutBirthResponses, type Rain2h, type RainHourData, RainType, type RankData, type ReadingData, type ReadingError, type ReadingErrors, type ReadingResponse, type ReadingResponses, type ReelItem, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type RejectCardData, type RejectCardError, type RejectCardErrors, type RejectCardResponse, type RejectCardResponses, type ReportCommentData, type ReportCommentError, type ReportCommentErrors, type ReportCommentResponse, type ReportCommentResponses, ReportReason, type ReportTalkData, type ReportTalkError, type ReportTalkErrors, type ReportTalkResponse, type ReportTalkResponses, type ReqCardCreate, type ReqComment, type ReqDayLog, type ReqFortuneDraw, type ReqFortuneImport, type ReqGameRound, type ReqGoogle, type ReqLogin, type ReqMyGak, type ReqMyGakScore, type ReqReelCreate, type ReqRefresh, type ReqReport, type ReqSaju, type ReqSajuBirth, type ReqSajuMatch, type ReqSignup, type ReqTalk, type ReqTalkReport, type ReqTossLogin, type ReqTossUnlink, type ReqUpdateMe, type ResAdminUsers, type ResArticle, type ResArticleList, type ResAuth, type ResAuthConfig, type ResBlockedList, type ResCard, type ResCardList, type ResComment, type ResCommentLike, type ResCommentList, type ResDayLog, type ResEventList, type ResFeed, type ResFortunePlaces, type ResFortuneToday, type ResGameStart, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLevel, type ResLogout, type ResMe, type ResMyGak, type ResMyGakList, type ResMyGakPresets, type ResMyGakScore, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResReel, type ResReelList, type ResRegion, type ResRegionList, type ResSaju, type ResSajuBirth, type ResSajuMatch, type ResSavedList, type ResSeasonWeek, type ResShortList, type ResSky, type ResSkyRanking, type ResTalk, type ResTalkGroups, type ResTalkImage, type ResTalkLike, type ResTalkList, type ResTossUnlink, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type ResWithdraw, type Row, type RowsSlide, type SajuBirth, type SajuCard, type SajuDay, type SajuLock, type SajuLove, type SajuLoveDay, type SajuMe, type SajuPeriod, type SajuPillar, type SajuSavedBirth, type SajuToday, type SaveDayLogData, type SaveDayLogError, type SaveDayLogErrors, type SaveDayLogResponse, type SaveDayLogResponses, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type ScoreMyGakData, type ScoreMyGakError, type ScoreMyGakErrors, type ScoreMyGakResponse, type ScoreMyGakResponses, type SearchFortunePlacesData, type SearchFortunePlacesError, type SearchFortunePlacesErrors, type SearchFortunePlacesResponse, type SearchFortunePlacesResponses, type SharedData, type SharedError, type SharedErrors, type SharedResponse, type SharedResponses, type ShortItem, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TalkData, type TalkGroup, type TalkGroupsData, type TalkGroupsError, type TalkGroupsErrors, type TalkGroupsResponse, type TalkGroupsResponses, TalkReport, TalkTopic, type TermData, type Tomorrow, type TomorrowEvent, type TopIndex, type TossData, type TossError, type TossErrors, type TossResponse, type TossResponses, type TossUnlinkData, type TossUnlinkError, type TossUnlinkErrors, type TossUnlinkResponse, type TossUnlinkResponses, type TrendPoint, type UnblockData, type UnblockError, type UnblockErrors, type UnblockResponse, type UnblockResponses, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnlikeTalkData, type UnlikeTalkError, type UnlikeTalkErrors, type UnlikeTalkResponse, type UnlikeTalkResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type UploadTalkImageData, type UploadTalkImageError, type UploadTalkImageErrors, type UploadTalkImageResponse, type UploadTalkImageResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeatherWhy, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide, type WithdrawData, type WithdrawError, type WithdrawErrors, type WithdrawResponse, type WithdrawResponses } from './types.gen'; +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 GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, type ImportFortuneData, type ImportFortuneError, type ImportFortuneErrors, type ImportFortuneResponse, type ImportFortuneResponses, IndexCategory, type IndexSummary, type LevelAction, type LevelStep, type LevelUnlock, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListBlockedData, type ListBlockedError, type ListBlockedErrors, type ListBlockedResponse, type ListBlockedResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type ListMyTalksErrors, type ListMyTalksResponse, type ListMyTalksResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListPresetsData, type ListPresetsResponse, type ListPresetsResponses, type ListReelsData, type ListReelsError, type ListReelsErrors, type ListReelsResponse, type ListReelsResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type ListShortsData, type ListShortsResponse, type ListShortsResponses, type ListTalkCommentsData, type ListTalkCommentsError, type ListTalkCommentsErrors, type ListTalkCommentsResponse, type ListTalkCommentsResponses, type ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type ListUsersData, type ListUsersError, type ListUsersErrors, type ListUsersResponse, type ListUsersResponses, type LocalDraw, type LocalLog, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type MatchData, type MatchError, type MatchErrors, type MatchResponse, type MatchResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type MyGakPreset, type MyGakRule, type MyGakScore, type MyLevelData, type MyLevelError, type MyLevelErrors, type MyLevelResponse, type MyLevelResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, type PostReaction, PostType, type PublishCardData, type PublishCardError, type PublishCardErrors, type PublishCardResponse, type PublishCardResponses, type PublishInstagram2Data, type PublishInstagram2Error, type PublishInstagram2Errors, type PublishInstagram2Response, type PublishInstagram2Responses, type PublishInstagramData, type PublishInstagramError, type PublishInstagramErrors, type PublishInstagramResponse, type PublishInstagramResponses, type PutBirthData, type PutBirthError, type PutBirthErrors, type PutBirthResponse, type PutBirthResponses, type Rain2h, type RainHourData, RainType, type RankData, type ReadingData, type ReadingError, type ReadingErrors, type ReadingResponse, type ReadingResponses, type ReelItem, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type RejectCardData, type RejectCardError, type RejectCardErrors, type RejectCardResponse, type RejectCardResponses, type ReportCommentData, type ReportCommentError, type ReportCommentErrors, type ReportCommentResponse, type ReportCommentResponses, ReportReason, type ReportTalkData, type ReportTalkError, type ReportTalkErrors, type ReportTalkResponse, type ReportTalkResponses, type ReqCardCreate, type ReqComment, type ReqDayLog, type ReqFortuneDraw, type ReqFortuneImport, type ReqGameRound, type ReqGoogle, type ReqLogin, type ReqMyGak, type ReqMyGakScore, type ReqReelCreate, type ReqRefresh, type ReqReport, type ReqSaju, type ReqSajuBirth, type ReqSajuMatch, type ReqSignup, type ReqTalk, type ReqTalkReport, type ReqTossLogin, type ReqTossUnlink, type ReqUpdateMe, type ResAdminUsers, type ResArticle, type ResArticleList, type ResAuth, type ResAuthConfig, type ResBlockedList, type ResCard, type ResCardList, type ResComment, type ResCommentLike, type ResCommentList, type ResDayLog, type ResEventList, type ResFeed, type ResFirstSnow, type ResFortunePlaces, type ResFortuneToday, type ResGameStart, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLevel, type ResLogout, type ResMe, type ResMyGak, type ResMyGakList, type ResMyGakPresets, type ResMyGakScore, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResReel, type ResReelList, type ResRegion, type ResRegionList, type ResSaju, type ResSajuBirth, type ResSajuMatch, type ResSavedList, type ResSeasonWeek, type ResShortList, type ResSky, type ResSkyRanking, type ResTalk, type ResTalkGroups, type ResTalkImage, type ResTalkLike, type ResTalkList, type ResTossUnlink, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type ResWithdraw, type Row, type RowsSlide, type SajuBirth, type SajuCard, type SajuDay, type SajuLock, type SajuLove, type SajuLoveDay, type SajuMe, type SajuPeriod, type SajuPillar, type SajuSavedBirth, type SajuToday, type SaveDayLogData, type SaveDayLogError, type SaveDayLogErrors, type SaveDayLogResponse, type SaveDayLogResponses, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type ScoreMyGakData, type ScoreMyGakError, type ScoreMyGakErrors, type ScoreMyGakResponse, type ScoreMyGakResponses, type SearchFortunePlacesData, type SearchFortunePlacesError, type SearchFortunePlacesErrors, type SearchFortunePlacesResponse, type SearchFortunePlacesResponses, type SharedData, type SharedError, type SharedErrors, type SharedResponse, type SharedResponses, type ShortItem, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TalkData, type TalkGroup, type TalkGroupsData, type TalkGroupsError, type TalkGroupsErrors, type TalkGroupsResponse, type TalkGroupsResponses, TalkReport, TalkTopic, type TermData, type Tomorrow, type TomorrowEvent, type TopIndex, type TossData, type TossError, type TossErrors, type TossResponse, type TossResponses, type TossUnlinkData, type TossUnlinkError, type TossUnlinkErrors, type TossUnlinkResponse, type TossUnlinkResponses, type TrendPoint, type UnblockData, type UnblockError, type UnblockErrors, type UnblockResponse, type UnblockResponses, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnlikeTalkData, type UnlikeTalkError, type UnlikeTalkErrors, type UnlikeTalkResponse, type UnlikeTalkResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type UploadTalkImageData, type UploadTalkImageError, type UploadTalkImageErrors, type UploadTalkImageResponse, type UploadTalkImageResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeatherWhy, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide, type WithdrawData, type WithdrawError, type WithdrawErrors, type WithdrawResponse, type WithdrawResponses } from './types.gen'; diff --git a/shared/api/client/sdk.gen.ts b/shared/api/client/sdk.gen.ts index 4da09d7..acbb6b3 100644 --- a/shared/api/client/sdk.gen.ts +++ b/shared/api/client/sdk.gen.ts @@ -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, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses, WithdrawData, WithdrawErrors, WithdrawResponses } from './types.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, 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, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses, WithdrawData, WithdrawErrors, WithdrawResponses } from './types.gen'; export type Options = Options2 & { /** @@ -93,6 +93,11 @@ export const listArticles = (options?: Opti */ export const getArticle = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/season/article/{article_id}', ...options }); +/** + * 첫눈 지도: 지점별 평년 첫눈 날짜와 앞으로 7일 눈 예보 + */ +export const getFirstSnow = (options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/season/first-snow', ...options }); + /** * 메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠 */ diff --git a/shared/api/client/types.gen.ts b/shared/api/client/types.gen.ts index 3dcada5..10d198c 100644 --- a/shared/api/client/types.gen.ts +++ b/shared/api/client/types.gen.ts @@ -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; +}; + /** * 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?: { diff --git a/shared/lib/analytics.ts b/shared/lib/analytics.ts index 03d2362..1319c8b 100644 --- a/shared/lib/analytics.ts +++ b/shared/lib/analytics.ts @@ -41,6 +41,11 @@ export type Events = { shorts_preview: { video_id: string; trigger: 'hover' | 'auto' } foliage_open: Record foliage_spot: { spot_name: string; from: 'page' | 'card' } + first_snow_open: Record + first_snow_spot: { spot_name: string; from: 'page' | 'card' } + sunrise_open: Record + 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 = { 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: '하루_기록', diff --git a/shared/lib/firstSnow.ts b/shared/lib/firstSnow.ts new file mode 100644 index 0000000..ee7fbcd --- /dev/null +++ b/shared/lib/firstSnow.ts @@ -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 = { 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() + 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)}`) diff --git a/shared/lib/foliage.ts b/shared/lib/foliage.ts index 1545647..e7675a6 100644 --- a/shared/lib/foliage.ts +++ b/shared/lib/foliage.ts @@ -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: M; x: number; y: number; r: number } export type Box = { l: number; t: number; r: number; b: number } export type LabelSize = Record 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, 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

(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(order: Pt[], all: Pt[], size: LabelSize, area: Box, blocked: Box[] = [], vertical: (p: Pt) => 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 = {} @@ -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) { diff --git a/shared/lib/sunrise.ts b/shared/lib/sunrise.ts new file mode 100644 index 0000000..96dd4fe --- /dev/null +++ b/shared/lib/sunrise.ts @@ -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 = { 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)}부터`