Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ab2271d61 | ||
|
|
0d6ab29552 | ||
|
|
ba94a381a9 | ||
|
|
882932a51b | ||
|
|
a68268234d | ||
|
|
2ca060b626 | ||
|
|
3975e41f56 | ||
|
|
646a45c88e | ||
|
|
e0d2ad2c9b | ||
|
|
422e354f61 | ||
|
|
0aeceac257 | ||
|
|
b586db0de7 | ||
|
|
599ef05dcf |
No files matched your search
@@ -0,0 +1,11 @@
|
|||||||
|
# 저장소 루트를 빌드 대상으로 쓰는 건 frontend 이미지뿐이라 frontend·shared·루트 package 파일만 넘긴다
|
||||||
|
*
|
||||||
|
!package.json
|
||||||
|
!package-lock.json
|
||||||
|
!frontend
|
||||||
|
!shared
|
||||||
|
!mobile/package.json
|
||||||
|
**/node_modules
|
||||||
|
**/dist
|
||||||
|
**/*.log
|
||||||
|
**/.DS_Store
|
||||||
@@ -4,6 +4,9 @@
|
|||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
|
||||||
|
# npm workspaces 의존성 (frontend·mobile·shared 가 루트 하나를 같이 쓴다)
|
||||||
|
node_modules/
|
||||||
|
|
||||||
# Python 바이트코드/캐시
|
# Python 바이트코드/캐시
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ class Settings(BaseSettings):
|
|||||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
|
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
|
||||||
|
|
||||||
|
# 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안)
|
||||||
|
frontend_internal_url: str = "http://frontend"
|
||||||
|
|
||||||
jwt_access_secret: str = ""
|
jwt_access_secret: str = ""
|
||||||
jwt_refresh_secret: str = ""
|
jwt_refresh_secret: str = ""
|
||||||
jwt_access_minutes: int = 60
|
jwt_access_minutes: int = 60
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from router.v1.index.index import router as index_router
|
|||||||
from router.v1.reaction.reaction import router as reaction_router
|
from router.v1.reaction.reaction import router as reaction_router
|
||||||
from router.v1.region.region import router as region_router
|
from router.v1.region.region import router as region_router
|
||||||
from router.v1.season.season import router as season_router
|
from router.v1.season.season import router as season_router
|
||||||
|
from router.v1.seo.seo import router as seo_router
|
||||||
from router.v1.sky.sky import router as sky_router
|
from router.v1.sky.sky import router as sky_router
|
||||||
from router.v1.watch.watch import router as watch_router
|
from router.v1.watch.watch import router as watch_router
|
||||||
from router.v1.weather.weather import router as weather_router
|
from router.v1.weather.weather import router as weather_router
|
||||||
@@ -43,6 +44,7 @@ app.include_router(auth_router)
|
|||||||
app.include_router(reaction_router)
|
app.include_router(reaction_router)
|
||||||
app.include_router(watch_router)
|
app.include_router(watch_router)
|
||||||
app.include_router(image_router)
|
app.include_router(image_router)
|
||||||
|
app.include_router(seo_router)
|
||||||
|
|
||||||
|
|
||||||
class Res_Health(Res_WebPacketProtocol):
|
class Res_Health(Res_WebPacketProtocol):
|
||||||
|
|||||||
Whitespace-only changes.
@@ -0,0 +1,17 @@
|
|||||||
|
from fastapi import APIRouter, Depends, Path
|
||||||
|
from fastapi.responses import HTMLResponse
|
||||||
|
|
||||||
|
from common.enums import ErrorType
|
||||||
|
from services.seo_service import SeoService
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/v1/seo", tags=["seo"])
|
||||||
|
|
||||||
|
_SLUG = r"^[a-z]+$"
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/today/{sido}/{place}", response_class=HTMLResponse, summary="지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)")
|
||||||
|
async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||||
|
err, html = await service.page(f"today/{sido}/{place}")
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
return HTMLResponse("not found", status_code=404)
|
||||||
|
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""프론트 지역 검색 페이지 목록(frontend/seo/region.json)을 seed/region.csv 로 다시 만든다.
|
||||||
|
|
||||||
|
region.csv 가 바뀌면 실행: python backend/scripts/gen_region_pages.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
SRC = os.path.join(ROOT, "backend", "seed", "region.csv")
|
||||||
|
OUT = os.path.join(ROOT, "frontend", "seo", "region.json")
|
||||||
|
|
||||||
|
SIDO = dict(서울='seoul', 부산='busan', 대구='daegu', 인천='incheon', 광주='gwangju', 대전='daejeon', 울산='ulsan', 세종='sejong', 경기='gyeonggi', 강원='gangwon', 충북='chungbuk', 충남='chungnam', 전북='jeonbuk', 전남='jeonnam', 경북='gyeongbuk', 경남='gyeongnam', 제주='jeju')
|
||||||
|
R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin 동대문 dongdaemun 중랑 jungnang 성북 seongbuk 강북 gangbuk 도봉 dobong 노원 nowon 은평 eunpyeong 서대문 seodaemun 마포 mapo 양천 yangcheon 강서 gangseo 구로 guro 금천 geumcheon 영등포 yeongdeungpo 동작 dongjak 관악 gwanak 서초 seocho 강남 gangnam 송파 songpa 강동 gangdong
|
||||||
|
목포 mokpo 여수 yeosu 순천 suncheon 나주 naju 광양 gwangyang 동 dong 서 seo 남 nam 북 buk 광산 gwangsan 담양 damyang 곡성 gokseong 구례 gurye 고흥 goheung 보성 boseong 화순 hwasun 장흥 jangheung 강진 gangjin 해남 haenam 영암 yeongam 무안 muan 함평 hampyeong 영광 yeonggwang 장성 jangseong 완도 wando 진도 jindo 신안 sinan
|
||||||
|
영도 yeongdo 부산진 busanjin 동래 dongnae 해운대 haeundae 사하 saha 금정 geumjeong 연제 yeonje 수영 suyeong 사상 sasang 기장 gijang 수성 suseong 달서 dalseo 달성 dalseong 군위 gunwi
|
||||||
|
제물포 jemulpo 영종 yeongjong 미추홀 michuhol 연수 yeonsu 남동 namdong 부평 bupyeong 계양 gyeyang 서해 seohae 검단 geomdan 강화 ganghwa 옹진 ongjin 유성 yuseong 대덕 daedeok 울주 ulju 세종특별자치 sejong
|
||||||
|
수원 suwon 성남 seongnam 의정부 uijeongbu 안양 anyang 부천 bucheon 광명 gwangmyeong 평택 pyeongtaek 동두천 dongducheon 안산 ansan 고양 goyang 과천 gwacheon 구리 guri 남양주 namyangju 오산 osan 시흥 siheung 군포 gunpo 의왕 uiwang 하남 hanam 용인 yongin 파주 paju 이천 icheon 안성 anseong 김포 gimpo 화성 hwaseong 광주 gwangju 양주 yangju 포천 pocheon 여주 yeoju 연천 yeoncheon 가평 gapyeong 양평 yangpyeong
|
||||||
|
청주 cheongju 충주 chungju 제천 jecheon 보은 boeun 옥천 okcheon 영동 yeongdong 증평 jeungpyeong 진천 jincheon 괴산 goesan 음성 eumseong 단양 danyang
|
||||||
|
천안 cheonan 공주 gongju 보령 boryeong 아산 asan 서산 seosan 논산 nonsan 계룡 gyeryong 당진 dangjin 금산 geumsan 부여 buyeo 서천 seocheon 청양 cheongyang 홍성 hongseong 예산 yesan 태안 taean
|
||||||
|
포항 pohang 경주 gyeongju 김천 gimcheon 안동 andong 구미 gumi 영주 yeongju 영천 yeongcheon 상주 sangju 문경 mungyeong 경산 gyeongsan 의성 uiseong 청송 cheongsong 영양 yeongyang 영덕 yeongdeok 청도 cheongdo 고령 goryeong 성주 seongju 칠곡 chilgok 예천 yecheon 봉화 bonghwa 울진 uljin 울릉 ulleung
|
||||||
|
창원 changwon 진주 jinju 통영 tongyeong 사천 sacheon 김해 gimhae 밀양 miryang 거제 geoje 양산 yangsan 의령 uiryeong 함안 haman 창녕 changnyeong 고성 goseong 남해 namhae 하동 hadong 산청 sancheong 함양 hamyang 거창 geochang 합천 hapcheon 제주 jeju 서귀포 seogwipo
|
||||||
|
춘천 chuncheon 원주 wonju 강릉 gangneung 동해 donghae 태백 taebaek 속초 sokcho 삼척 samcheok 홍천 hongcheon 횡성 hoengseong 영월 yeongwol 평창 pyeongchang 정선 jeongseon 철원 cheorwon 화천 hwacheon 양구 yanggu 인제 inje 양양 yangyang
|
||||||
|
전주 jeonju 군산 gunsan 익산 iksan 정읍 jeongeup 남원 namwon 김제 gimje 완주 wanju 진안 jinan 무주 muju 장수 jangsu 임실 imsil 순창 sunchang 고창 gochang 부안 buan'''.split()
|
||||||
|
ROMAN = dict(zip(R[::2], R[1::2]))
|
||||||
|
# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다
|
||||||
|
CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'}
|
||||||
|
pages = {}
|
||||||
|
for row in csv.DictReader(open(SRC, encoding='utf-8')):
|
||||||
|
sido, *rest = row['name'].split()
|
||||||
|
place = rest[0]
|
||||||
|
r = dict(code=row['code'], name=row['name'], short_name=row['short_name'], lat=float(row['lat']), lon=float(row['lon']))
|
||||||
|
path = f"{SIDO[sido]}/{ROMAN[place[:-1]]}"
|
||||||
|
p = pages.setdefault(path, dict(path=path, name='세종시' if sido == '세종' else f'{sido} {place}', main=None, regions=[]))
|
||||||
|
p['regions'].append(r)
|
||||||
|
if len(rest) == 1 or CITY_MAIN[place] == rest[1]:
|
||||||
|
p['main'] = r['code']
|
||||||
|
out = list(pages.values())
|
||||||
|
assert all(p['main'] for p in out), [p['path'] for p in out if not p['main']]
|
||||||
|
assert sum(len(p['regions']) for p in out) == 256
|
||||||
|
json.dump(out, open(OUT, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
|
||||||
|
print(len(out), 'pages', sum(len(p['regions']) > 1 for p in out), 'cities')
|
||||||
@@ -3730,5 +3730,159 @@
|
|||||||
"sort_order": 51,
|
"sort_order": 51,
|
||||||
"priority": 3,
|
"priority": 3,
|
||||||
"months": []
|
"months": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "umbrella_lost",
|
||||||
|
"name": "우산분실각",
|
||||||
|
"icon": "umbrella",
|
||||||
|
"category": 4,
|
||||||
|
"is_fun": false,
|
||||||
|
"is_core": false,
|
||||||
|
"has_detail": true,
|
||||||
|
"description": "오전 9시~밤 10시, 비가 그쳐서 우산을 두고 오기 쉬운 정도",
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"from": 9,
|
||||||
|
"to": 11
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 11,
|
||||||
|
"to": 13
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 13,
|
||||||
|
"to": 15
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 15,
|
||||||
|
"to": 17
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 17,
|
||||||
|
"to": 19
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 19,
|
||||||
|
"to": 22
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"weight_temp": 0,
|
||||||
|
"weight_rain": 80,
|
||||||
|
"weight_wind": 0,
|
||||||
|
"weight_humidity": 0,
|
||||||
|
"weight_air": 0,
|
||||||
|
"weight_uv": 0,
|
||||||
|
"weight_sun": 0,
|
||||||
|
"weight_view": 0,
|
||||||
|
"weight_time": 20,
|
||||||
|
"factor_rules": {
|
||||||
|
"temp": {
|
||||||
|
"type": "range",
|
||||||
|
"lo": 0,
|
||||||
|
"hi": 40
|
||||||
|
},
|
||||||
|
"rain": {
|
||||||
|
"dir": "dry"
|
||||||
|
},
|
||||||
|
"wind": {
|
||||||
|
"type": "ignore"
|
||||||
|
},
|
||||||
|
"humidity": {
|
||||||
|
"type": "ignore"
|
||||||
|
},
|
||||||
|
"time": {
|
||||||
|
"type": "fixed",
|
||||||
|
"value": 100
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zero_rules": [
|
||||||
|
{
|
||||||
|
"field": "rain_before",
|
||||||
|
"op": "==",
|
||||||
|
"value": "no"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "rain",
|
||||||
|
"op": "==",
|
||||||
|
"value": "yes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"limit_description": "비가 언제 그칠지는 예보만큼만 맞아요",
|
||||||
|
"sentences": {
|
||||||
|
"0": "우산 두고 올 일 없는 날이에요.",
|
||||||
|
"30": "비가 오락가락해요. 우산 손에 꼭 쥐어요.",
|
||||||
|
"60": "비가 그쳤어요. 카페·버스에 우산 두고 오기 딱 좋아요.",
|
||||||
|
"80": "비 끝, 하늘 맑음! 일어날 때 우산부터 챙겨요 ☂️"
|
||||||
|
},
|
||||||
|
"sort_order": 52,
|
||||||
|
"priority": 2,
|
||||||
|
"months": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "traffic",
|
||||||
|
"name": "교통체증각",
|
||||||
|
"icon": "drive",
|
||||||
|
"category": 4,
|
||||||
|
"is_fun": false,
|
||||||
|
"is_core": false,
|
||||||
|
"has_detail": true,
|
||||||
|
"description": "출퇴근길 비·눈·추위로 차가 막히는 정도",
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"from": 7,
|
||||||
|
"to": 10
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 17,
|
||||||
|
"to": 20
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"weight_temp": 10,
|
||||||
|
"weight_rain": 70,
|
||||||
|
"weight_wind": 0,
|
||||||
|
"weight_humidity": 0,
|
||||||
|
"weight_air": 0,
|
||||||
|
"weight_uv": 0,
|
||||||
|
"weight_sun": 0,
|
||||||
|
"weight_view": 0,
|
||||||
|
"weight_time": 20,
|
||||||
|
"factor_rules": {
|
||||||
|
"temp": {
|
||||||
|
"type": "lower",
|
||||||
|
"zero": 10,
|
||||||
|
"full": -5
|
||||||
|
},
|
||||||
|
"rain": {
|
||||||
|
"dir": "wet"
|
||||||
|
},
|
||||||
|
"wind": {
|
||||||
|
"type": "ignore"
|
||||||
|
},
|
||||||
|
"humidity": {
|
||||||
|
"type": "ignore"
|
||||||
|
},
|
||||||
|
"time": {
|
||||||
|
"type": "weekday",
|
||||||
|
"mon": 100,
|
||||||
|
"tue": 100,
|
||||||
|
"wed": 100,
|
||||||
|
"thu": 100,
|
||||||
|
"fri": 100,
|
||||||
|
"sat": 40,
|
||||||
|
"sun": 40,
|
||||||
|
"holiday": 30
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zero_rules": [],
|
||||||
|
"limit_description": "사고·공사·행사로 막히는 건 반영하지 못해요",
|
||||||
|
"sentences": {
|
||||||
|
"0": "길이 수월해요. 평소처럼 나가요.",
|
||||||
|
"30": "조금 더뎌 수 있어요. 10분 일찍!",
|
||||||
|
"60": "빗길에 차가 막혀요. 대중교통이 나아요.",
|
||||||
|
"80": "출퇴근길 주차장 예상! 30분 일찍 나서요 🚗"
|
||||||
|
},
|
||||||
|
"sort_order": 53,
|
||||||
|
"priority": 2,
|
||||||
|
"months": []
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -56,6 +56,7 @@ class Context:
|
|||||||
lookahead_rain_prob: int
|
lookahead_rain_prob: int
|
||||||
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
|
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
|
||||||
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
|
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
|
||||||
|
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -262,6 +263,8 @@ def _cond(r: dict) -> tuple[str, str, str]:
|
|||||||
return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면"
|
return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면"
|
||||||
if r["field"] == "rain":
|
if r["field"] == "rain":
|
||||||
return "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면"
|
return "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면"
|
||||||
|
if r["field"] == "rain_before":
|
||||||
|
return "앞서 내린 비가 없어", "앞서 내린 비가 없거나", "앞서 내린 비가 없으면"
|
||||||
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
|
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
|
||||||
return f"{base}이라", f"{base}이거나", f"{base}이면"
|
return f"{base}이라", f"{base}이거나", f"{base}이면"
|
||||||
|
|
||||||
@@ -344,6 +347,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
|||||||
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
|
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
|
||||||
"snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no",
|
"snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no",
|
||||||
"rain": "yes" if raining else "no", "humidity": round(mean(h.humidity for h in hours)),
|
"rain": "yes" if raining else "no", "humidity": round(mean(h.humidity for h in hours)),
|
||||||
|
"rain_before": "yes" if any(h < hours[0].hour for h in ctx.rain_hours) else "no",
|
||||||
}
|
}
|
||||||
reason, cap = _zero(definition.zero_rules, agg)
|
reason, cap = _zero(definition.zero_rules, agg)
|
||||||
if reason is not None:
|
if reason is not None:
|
||||||
@@ -393,7 +397,8 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
|
|||||||
notes = {a: n for a, (_, n) in scored.items()}
|
notes = {a: n for a, (_, n) in scored.items()}
|
||||||
score = _weighted(factors, weights)
|
score = _weighted(factors, weights)
|
||||||
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
|
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
|
||||||
known = {"rain_prob": max_prob, "snow": "no"}
|
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
|
||||||
|
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
|
||||||
reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known)
|
reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known)
|
||||||
if reason is not None:
|
if reason is not None:
|
||||||
score = min(score, cap)
|
score = min(score, cap)
|
||||||
|
|||||||
@@ -323,6 +323,9 @@ class FeedService:
|
|||||||
async with redis_lock("lock:feed:build", ttl_sec=20):
|
async with redis_lock("lock:feed:build", ttl_sec=20):
|
||||||
await build_feed_day(day, self.crud, self.season_crud, self.regions)
|
await build_feed_day(day, self.crud, self.season_crud, self.regions)
|
||||||
res, partial = await self._assemble(region, now, day, slot, sunset_at)
|
res, partial = await self._assemble(region, now, day, slot, sunset_at)
|
||||||
|
# 각을 못 낸 피드는 저장하지 않는다. 처음 온 지역은 예보를 받는 중이라 다음 요청에서 바로 채운다
|
||||||
|
if not res.bands.top5:
|
||||||
|
return ErrorType.SUCCESS, res
|
||||||
try:
|
try:
|
||||||
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
|
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
|
||||||
except RedisError as e:
|
except RedisError as e:
|
||||||
|
|||||||
@@ -193,6 +193,12 @@ def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
|
|||||||
return {k: shown[k] for k in SLOTS if k in shown}
|
return {k: shown[k] for k in SLOTS if k in shown}
|
||||||
|
|
||||||
|
|
||||||
|
def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]:
|
||||||
|
"""그날 비·눈 오는 시각(0~23)."""
|
||||||
|
start = kst_midnight(day)
|
||||||
|
return frozenset(h for h in range(24) if (r := by_at.get(start + timedelta(hours=h))) is not None and r.rain_type != RainType.NONE.value)
|
||||||
|
|
||||||
|
|
||||||
def slot_results(
|
def slot_results(
|
||||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
||||||
now: Optional[datetime] = None,
|
now: Optional[datetime] = None,
|
||||||
@@ -388,7 +394,7 @@ class IndexService:
|
|||||||
air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
|
air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
|
||||||
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
|
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
|
||||||
)
|
)
|
||||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx)
|
||||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||||
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()}
|
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()}
|
||||||
|
|
||||||
@@ -419,7 +425,7 @@ class IndexService:
|
|||||||
m = night(day, float(region.lat), float(region.lon))
|
m = night(day, float(region.lat), float(region.lon))
|
||||||
ctx = Context(
|
ctx = Context(
|
||||||
day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}",
|
day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}",
|
||||||
sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, **base_ctx,
|
sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, rain_hours=rain_hours(by_at, day), **base_ctx,
|
||||||
)
|
)
|
||||||
for d in defs:
|
for d in defs:
|
||||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import re
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from html import escape
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import Depends
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.database.model.models import WeatherHourly
|
||||||
|
from common.enums import ErrorType, RainType, Sky
|
||||||
|
from common.logger import LOG
|
||||||
|
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||||
|
from config.settings import settings
|
||||||
|
from crud.region_crud import RegionCRUD
|
||||||
|
from crud.weather_crud import WeatherCRUD
|
||||||
|
from router.v1.feed.protocol import Res_Feed
|
||||||
|
from services.calc.day_slot import SLOT_LABEL
|
||||||
|
from services.calc.sun import sun_times
|
||||||
|
from services.feed_service import FeedService
|
||||||
|
|
||||||
|
_CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
|
||||||
|
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
|
||||||
|
_NAME = re.compile(r"<h1>(.+?) 오늘 날씨")
|
||||||
|
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
|
||||||
|
|
||||||
|
|
||||||
|
def _clock(at: datetime) -> str:
|
||||||
|
at = at.astimezone(KST)
|
||||||
|
h = at.hour % 12 or 12
|
||||||
|
return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "")
|
||||||
|
|
||||||
|
|
||||||
|
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||||
|
_RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
|
||||||
|
|
||||||
|
|
||||||
|
def day_summary(rows: list[WeatherHourly]) -> str:
|
||||||
|
"""오늘 하루 예보 요약: 최저·최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
|
||||||
|
if not rows:
|
||||||
|
return ""
|
||||||
|
temps = [float(r.temp_c) for r in rows]
|
||||||
|
wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None)
|
||||||
|
day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows
|
||||||
|
sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))]
|
||||||
|
return f"최저 {round(min(temps))}°·최고 {round(max(temps))}°, 강수확률 {max(r.rain_prob for r in rows)}%, {sky}."
|
||||||
|
|
||||||
|
|
||||||
|
def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
|
||||||
|
"""검색 결과 요약에 보일 오늘 한 줄: 하루 예보, 지금 기온·상태, 구간별 1위 각, 해 지는 시각."""
|
||||||
|
parts = [day_summary(rows)] if rows else []
|
||||||
|
h = feed.hero
|
||||||
|
if h and h.temp_c is not None:
|
||||||
|
status = "·".join(f"{s.label} {s.value}" for s in h.status)
|
||||||
|
parts.append(f"지금 {round(h.temp_c)}°" + (f", {status}" if status else "") + ".")
|
||||||
|
firsts = [f"{label}은 {s.name}" for slot, label in SLOT_LABEL.items() for s in feed.stories if s.slot_ranks.get(slot) == 1]
|
||||||
|
if firsts:
|
||||||
|
parts.append(", ".join(firsts) + ".")
|
||||||
|
if sunset_at:
|
||||||
|
parts.append(f"해 지는 시각 {_clock(sunset_at)}.")
|
||||||
|
return " ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
|
||||||
|
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||||
|
line = today_line(feed, rows, sunset_at)
|
||||||
|
if not line:
|
||||||
|
return template
|
||||||
|
top = feed.bands.top5 if feed.bands else []
|
||||||
|
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||||
|
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
|
||||||
|
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{ranks}", html, count=1)
|
||||||
|
|
||||||
|
|
||||||
|
class SeoService:
|
||||||
|
def __init__(
|
||||||
|
self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)
|
||||||
|
) -> None:
|
||||||
|
self.feed, self.regions, self.weather = feed, regions, weather
|
||||||
|
|
||||||
|
async def template(self, path: str) -> Optional[str]:
|
||||||
|
"""프론트가 빌드한 정적 지역 페이지 (today/gyeonggi/seongnam.html)."""
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=5) as client:
|
||||||
|
r = await client.get(f"{settings.frontend_internal_url}/{path}.html")
|
||||||
|
except httpx.HTTPError as e:
|
||||||
|
LOG.error(f"[seo] template {path}: {e}")
|
||||||
|
return None
|
||||||
|
return r.text if r.status_code == 200 and _CODE.search(r.text) else None
|
||||||
|
|
||||||
|
async def page(self, path: str) -> tuple[ErrorType, Optional[str]]:
|
||||||
|
template = await self.template(path)
|
||||||
|
if template is None:
|
||||||
|
return ErrorType.NOT_FOUND, None
|
||||||
|
code = _CODE.search(template).group(1)
|
||||||
|
err, feed = await self.feed.feed(code)
|
||||||
|
if err is not ErrorType.SUCCESS or feed is None:
|
||||||
|
LOG.error(f"[seo] feed {code}: {err}")
|
||||||
|
return ErrorType.SUCCESS, template
|
||||||
|
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
|
||||||
|
today = now_kst().date()
|
||||||
|
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at if region else None
|
||||||
|
start = kst_midnight(today)
|
||||||
|
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
|
||||||
|
name = _NAME.search(template)
|
||||||
|
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
|
||||||
@@ -25,7 +25,7 @@ from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestF
|
|||||||
from services.external.kma import day_start_base, fetch_mid, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage
|
from services.external.kma import day_start_base, fetch_mid, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage
|
||||||
|
|
||||||
SLOT_HOURS = range(0, 24, 3)
|
SLOT_HOURS = range(0, 24, 3)
|
||||||
_WAIT_STEPS, _WAIT_SEC = 15, 0.2
|
_WAIT_STEPS, _WAIT_SEC = 75, 0.2 # 처음 온 지역은 다른 요청이 예보를 받아 오는 동안 최대 15초 기다린다
|
||||||
# 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게).
|
# 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게).
|
||||||
_MIN_DAY_HOURS = 8
|
_MIN_DAY_HOURS = 8
|
||||||
MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
|
MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
|
||||||
|
|||||||
@@ -204,7 +204,7 @@ def test_gak_key_handles_sunset_window():
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
async def test_feed_missing_gak_is_not_cached(offline, monkeypatch):
|
||||||
from common.cache.redis_client import REDIS
|
from common.cache.redis_client import REDIS
|
||||||
from common.enums import ErrorType
|
from common.enums import ErrorType
|
||||||
from services.index_service import IndexService
|
from services.index_service import IndexService
|
||||||
@@ -216,8 +216,7 @@ async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
|||||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||||
assert PostType.GAK.value not in [p["post_type"] for p in body["posts"]]
|
assert PostType.GAK.value not in [p["post_type"] for p in body["posts"]]
|
||||||
keys = [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")]
|
assert [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")] == []
|
||||||
assert keys and 0 < await REDIS.conn.ttl(keys[0]) <= 60
|
|
||||||
|
|
||||||
|
|
||||||
def _alert_ctx(warnings=(), rain_prob=0):
|
def _alert_ctx(warnings=(), rain_prob=0):
|
||||||
|
|||||||
@@ -308,3 +308,13 @@ def test_humidity_cap():
|
|||||||
|
|
||||||
def test_axis_label_can_be_overridden():
|
def test_axis_label_can_be_overridden():
|
||||||
assert axis_label("temp", {"temp": {"type": "higher", "label": "덜 추움"}}) == "덜 추움"
|
assert axis_label("temp", {"temp": {"type": "higher", "label": "덜 추움"}}) == "덜 추움"
|
||||||
|
|
||||||
|
|
||||||
|
def test_umbrella_lost_needs_rain_that_stopped():
|
||||||
|
"""우산분실각: 앞서 비가 왔다가 그친 시간대만 점수가 난다. 비가 안 온 날, 아직 비가 오는 시간대는 0점."""
|
||||||
|
defn = _defn(weight_temp=0, weight_rain=80, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=20,
|
||||||
|
zero_rules=[{"field": "rain_before", "op": "==", "value": "no"}, {"field": "rain", "op": "==", "value": "yes"}])
|
||||||
|
after_rain = replace(CTX, rain_hours=frozenset({9, 10}))
|
||||||
|
assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80
|
||||||
|
assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점"
|
||||||
|
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
|
||||||
|
from common.utils.kma_time import KST
|
||||||
|
from common.database.model.models import WeatherHourly
|
||||||
|
from router.router import app
|
||||||
|
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
|
||||||
|
from services.seo_service import SeoService, day_summary, fill, today_line
|
||||||
|
|
||||||
|
REGION = "1114000000"
|
||||||
|
TEMPLATE = (
|
||||||
|
'<html><head><meta name="description" content="소개" /><meta property="og:description" content="소개" />'
|
||||||
|
f'<meta name="region-code" content="{REGION}" />\n </head><body><main><h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>소개 글</p></main></body></html>'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _top(name: str, score: int, ranks: dict[str, int]) -> TopIndex:
|
||||||
|
return TopIndex(index_id=1, code="x", name=name, icon="x", score=score, rank=1, slot_ranks=ranks)
|
||||||
|
|
||||||
|
|
||||||
|
def _feed() -> Res_Feed:
|
||||||
|
stories = [_top("러닝각", 80, {"morning": 1, "day": 2}), _top("빨래각", 77, {"day": 1}), _top("별보기각", 70, {"night": 1})]
|
||||||
|
hero = Hero(now_at=datetime(2026, 10, 14, 9), sky_mode="morning", temp_c=13.4,
|
||||||
|
status=[HeroStat(icon="m", label="습도", value="보통", tone="normal"), HeroStat(icon="m", label="미세먼지", value="좋음", tone="normal")])
|
||||||
|
return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2]))
|
||||||
|
|
||||||
|
|
||||||
|
def _hour(h: int, temp: float, sky: int = 1, rain: int = 1, prob: int = 0) -> WeatherHourly:
|
||||||
|
return WeatherHourly(forecast_at=datetime(2026, 10, 14, h, tzinfo=KST), temp_c=temp, sky=sky, rain_type=rain, rain_prob=prob)
|
||||||
|
|
||||||
|
|
||||||
|
def test_day_summary_min_max_prob_and_daytime_sky():
|
||||||
|
rows = [_hour(3, 8.6, sky=4), _hour(9, 12, sky=3), _hour(12, 19.5, sky=1, prob=10), _hour(15, 20.2, sky=1), _hour(21, 14)]
|
||||||
|
assert day_summary(rows) == "최저 9°·최고 20°, 강수확률 10%, 맑음."
|
||||||
|
assert day_summary([_hour(12, 15, rain=2, prob=70)]) == "최저 15°·최고 15°, 강수확률 70%, 비."
|
||||||
|
|
||||||
|
|
||||||
|
def test_today_line_has_day_now_slot_firsts_and_sunset():
|
||||||
|
line = today_line(_feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST))
|
||||||
|
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분."
|
||||||
|
|
||||||
|
|
||||||
|
def test_fill_puts_today_into_description_and_body():
|
||||||
|
html = fill(TEMPLATE, _feed(), [], "서울 중구", None)
|
||||||
|
assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2
|
||||||
|
assert "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>지금 13°" in html
|
||||||
|
assert "<li>러닝각 80점</li><li>빨래각 77점</li>" in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_fill_keeps_template_when_no_weather():
|
||||||
|
assert fill(TEMPLATE, Res_Feed(), [], "서울 중구", None) == TEMPLATE
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_today_page_fills_real_feed(offline, monkeypatch):
|
||||||
|
async def template(self, path):
|
||||||
|
return TEMPLATE if path == "today/seoul/jung" else None
|
||||||
|
|
||||||
|
monkeypatch.setattr(SeoService, "template", template)
|
||||||
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||||
|
page = await client.get("/v1/seo/today/seoul/jung")
|
||||||
|
missing = await client.get("/v1/seo/today/seoul/nowhere")
|
||||||
|
assert page.status_code == 200 and "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text and "지금 20°" in page.text
|
||||||
|
assert "해 지는 시각 오후" in page.text and "<ol><li>" in page.text
|
||||||
|
assert missing.status_code == 404
|
||||||
+7
-3
@@ -4,7 +4,8 @@ services:
|
|||||||
# 운영형: docker compose up --build → http://localhost:8080
|
# 운영형: docker compose up --build → http://localhost:8080
|
||||||
frontend:
|
frontend:
|
||||||
build:
|
build:
|
||||||
context: ./frontend
|
context: .
|
||||||
|
dockerfile: frontend/Dockerfile
|
||||||
target: prod
|
target: prod
|
||||||
args:
|
args:
|
||||||
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
|
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
|
||||||
@@ -19,13 +20,16 @@ services:
|
|||||||
frontend-dev:
|
frontend-dev:
|
||||||
profiles: ["dev"]
|
profiles: ["dev"]
|
||||||
build:
|
build:
|
||||||
context: ./frontend
|
context: .
|
||||||
|
dockerfile: frontend/Dockerfile
|
||||||
target: dev
|
target: dev
|
||||||
ports:
|
ports:
|
||||||
- "5173:5173"
|
- "5173:5173"
|
||||||
volumes:
|
volumes:
|
||||||
- ./frontend:/app
|
- ./frontend:/app/frontend
|
||||||
|
- ./shared:/app/shared
|
||||||
- /app/node_modules
|
- /app/node_modules
|
||||||
|
- /app/frontend/node_modules
|
||||||
environment:
|
environment:
|
||||||
- CHOKIDAR_USEPOLLING=true
|
- CHOKIDAR_USEPOLLING=true
|
||||||
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
|
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
node_modules
|
|
||||||
dist
|
|
||||||
.git
|
|
||||||
*.log
|
|
||||||
.DS_Store
|
|
||||||
Dockerfile
|
|
||||||
.dockerignore
|
|
||||||
+13
-5
@@ -2,13 +2,19 @@
|
|||||||
|
|
||||||
# ---- deps: package.json이 바뀔 때만 다시 설치 ----
|
# ---- deps: package.json이 바뀔 때만 다시 설치 ----
|
||||||
FROM node:24-alpine AS deps
|
FROM node:24-alpine AS deps
|
||||||
|
# 빌드 대상은 저장소 루트(npm workspaces). 웹에 필요한 frontend·shared 만 설치한다
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm ci
|
COPY frontend/package.json frontend/
|
||||||
|
COPY shared/package.json shared/
|
||||||
|
COPY mobile/package.json mobile/
|
||||||
|
RUN npm ci -w frontend -w shared
|
||||||
|
|
||||||
# ---- dev: 코드 수정이 바로 반영되는 개발 서버 ----
|
# ---- dev: 코드 수정이 바로 반영되는 개발 서버 ----
|
||||||
FROM deps AS dev
|
FROM deps AS dev
|
||||||
COPY . .
|
COPY shared shared
|
||||||
|
COPY frontend frontend
|
||||||
|
WORKDIR /app/frontend
|
||||||
EXPOSE 5173
|
EXPOSE 5173
|
||||||
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
|
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
|
||||||
|
|
||||||
@@ -18,12 +24,14 @@ ARG VITE_API_BASE_URL=""
|
|||||||
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
||||||
ARG VITE_SITE_URL=""
|
ARG VITE_SITE_URL=""
|
||||||
ENV VITE_SITE_URL=$VITE_SITE_URL
|
ENV VITE_SITE_URL=$VITE_SITE_URL
|
||||||
COPY . .
|
COPY shared shared
|
||||||
|
COPY frontend frontend
|
||||||
|
WORKDIR /app/frontend
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# ---- prod: nginx로 정적 파일 제공 ----
|
# ---- prod: nginx로 정적 파일 제공 ----
|
||||||
FROM nginx:1.29-alpine AS prod
|
FROM nginx:1.29-alpine AS prod
|
||||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
COPY --from=build /app/dist /usr/share/nginx/html
|
COPY --from=build /app/frontend/dist /usr/share/nginx/html
|
||||||
EXPOSE 80
|
EXPOSE 80
|
||||||
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
|
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
|
||||||
+7
-6
@@ -15,14 +15,14 @@
|
|||||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||||
<meta name="theme-color" content="#d6ebff" />
|
<meta name="theme-color" content="#d6ebff" />
|
||||||
<meta name="description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
<meta name="description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
|
||||||
<meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달" />
|
<meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달" />
|
||||||
<title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title>
|
<title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title>
|
||||||
<link rel="manifest" href="/manifest.webmanifest" />
|
<link rel="manifest" href="/manifest.webmanifest" />
|
||||||
<meta property="og:type" content="website" />
|
<meta property="og:type" content="website" />
|
||||||
<meta property="og:site_name" content="날씨각" />
|
<meta property="og:site_name" content="날씨각" />
|
||||||
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
||||||
<meta property="og:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
<meta property="og:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
|
||||||
<meta property="og:url" content="%VITE_SITE_URL%/" />
|
<meta property="og:url" content="%VITE_SITE_URL%/" />
|
||||||
<link rel="canonical" href="%VITE_SITE_URL%/" />
|
<link rel="canonical" href="%VITE_SITE_URL%/" />
|
||||||
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
|
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
|
||||||
@@ -31,7 +31,7 @@
|
|||||||
<meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" />
|
<meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" />
|
||||||
<meta name="twitter:card" content="summary_large_image" />
|
<meta name="twitter:card" content="summary_large_image" />
|
||||||
<meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
<meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
||||||
<meta name="twitter:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
<meta name="twitter:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
|
||||||
<meta name="twitter:image" content="%VITE_SITE_URL%/og.png" />
|
<meta name="twitter:image" content="%VITE_SITE_URL%/og.png" />
|
||||||
<meta property="og:locale" content="ko_KR" />
|
<meta property="og:locale" content="ko_KR" />
|
||||||
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
|
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
|
||||||
@@ -60,7 +60,7 @@
|
|||||||
"@type": "WebApplication",
|
"@type": "WebApplication",
|
||||||
"name": "날씨각",
|
"name": "날씨각",
|
||||||
"url": "%VITE_SITE_URL%/",
|
"url": "%VITE_SITE_URL%/",
|
||||||
"description": "세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요.",
|
"description": "날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요.",
|
||||||
"applicationCategory": "WeatherApplication",
|
"applicationCategory": "WeatherApplication",
|
||||||
"operatingSystem": "All",
|
"operatingSystem": "All",
|
||||||
"inLanguage": "ko-KR",
|
"inLanguage": "ko-KR",
|
||||||
@@ -98,11 +98,12 @@
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<!-- 앱이 뜨기 전 첫 화면: 정적 소개 글이 잠깐 보이지 않게 덮는다. 앱이 뜨면 지운다 -->
|
<!-- 앱이 뜨기 전 첫 화면: 정적 소개 글이 잠깐 보이지 않게 덮는다. 앱이 뜨면 지운다 -->
|
||||||
<div id="boot" role="status" style="position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:#d6ebff;color:#28304a;font:19px Jua,sans-serif">
|
<div id="boot" data-nosnippet role="status" style="position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:#d6ebff;color:#28304a;font:19px Jua,sans-serif">
|
||||||
<img src="/icons/rabbit.png" alt="" width="88" height="88" />
|
<img src="/icons/rabbit.png" alt="" width="88" height="88" />
|
||||||
<p style="margin:0">날씨 불러오는 중…</p>
|
<p style="margin:0">날씨 불러오는 중…</p>
|
||||||
</div>
|
</div>
|
||||||
<div id="root">
|
<!-- 검색 결과 요약은 화면 글 대신 description 을 쓰게 한다 (지역 페이지는 서버가 오늘 날씨로 채움) -->
|
||||||
|
<div id="root" data-nosnippet>
|
||||||
<main>
|
<main>
|
||||||
<h1>날씨각</h1>
|
<h1>날씨각</h1>
|
||||||
<p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.</p>
|
<p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.</p>
|
||||||
|
|||||||
@@ -31,6 +31,23 @@ server {
|
|||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
|
||||||
|
location ~ ^/today/[a-z]+/[a-z]+$ {
|
||||||
|
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||||
|
set $api http://backend:9800;
|
||||||
|
proxy_pass $api/v1/seo$uri;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_connect_timeout 3s;
|
||||||
|
proxy_read_timeout 20s;
|
||||||
|
proxy_intercept_errors on;
|
||||||
|
error_page 404 500 502 503 504 = @static;
|
||||||
|
}
|
||||||
|
|
||||||
|
location @static {
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
try_files $uri.html /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
# SPA: /gak 처럼 빌드 때 만든 페이지별 HTML(gak.html)이 있으면 그것을, 없으면 index.html. 폴더는 안 찾는다 (/season 이 이미지 폴더 public/season 과 겹쳐 403)
|
# SPA: /gak 처럼 빌드 때 만든 페이지별 HTML(gak.html)이 있으면 그것을, 없으면 index.html. 폴더는 안 찾는다 (/season 이 이미지 폴더 public/season 과 겹쳐 403)
|
||||||
location / {
|
location / {
|
||||||
add_header Cache-Control "no-cache";
|
add_header Cache-Control "no-cache";
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { defineConfig } from '@hey-api/openapi-ts'
|
|||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
|
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
|
||||||
output: 'src/api/client',
|
output: '../shared/api/client',
|
||||||
parser: {
|
parser: {
|
||||||
patch: {
|
patch: {
|
||||||
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
|
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
|
||||||
|
|||||||
Generated
-2691
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,7 @@
|
|||||||
"api": "openapi-ts"
|
"api": "openapi-ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@nalssigak/shared": "*",
|
||||||
"@tailwindcss/vite": "^4.3.3",
|
"@tailwindcss/vite": "^4.3.3",
|
||||||
"@tanstack/react-query": "^5.104.0",
|
"@tanstack/react-query": "^5.104.0",
|
||||||
"embla-carousel-react": "^8.6.0",
|
"embla-carousel-react": "^8.6.0",
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
||||||
<url><loc>https://weather.o2o.kr/</loc><lastmod>2026-10-13</lastmod></url>
|
|
||||||
<url><loc>https://weather.o2o.kr/gak</loc><lastmod>2026-10-13</lastmod></url>
|
|
||||||
<url><loc>https://weather.o2o.kr/sky</loc><lastmod>2026-10-13</lastmod></url>
|
|
||||||
<url><loc>https://weather.o2o.kr/week</loc><lastmod>2026-10-13</lastmod></url>
|
|
||||||
<url><loc>https://weather.o2o.kr/season</loc><lastmod>2026-10-13</lastmod></url>
|
|
||||||
</urlset>
|
|
||||||
@@ -202,5 +202,13 @@
|
|||||||
{
|
{
|
||||||
"name": "싱잉인더레인각",
|
"name": "싱잉인더레인각",
|
||||||
"description": "비 오는 날 우산 쓰고 노래하며 걷기 좋은 정도"
|
"description": "비 오는 날 우산 쓰고 노래하며 걷기 좋은 정도"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "우산분실각",
|
||||||
|
"description": "오전 9시~밤 10시, 비가 그쳐서 우산을 두고 오기 쉬운 정도"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "교통체증각",
|
||||||
|
"description": "출퇴근길 비·눈·추위로 차가 막히는 정도"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -12,6 +12,7 @@ export default function App() {
|
|||||||
<Routes>
|
<Routes>
|
||||||
<Route element={<BLayout />}>
|
<Route element={<BLayout />}>
|
||||||
<Route index element={<TodayPage />} />
|
<Route index element={<TodayPage />} />
|
||||||
|
<Route path="today/:sido/:place" element={<TodayPage />} />
|
||||||
<Route path="gak" element={<GakPage />} />
|
<Route path="gak" element={<GakPage />} />
|
||||||
<Route path="sky" element={<SkyPage />} />
|
<Route path="sky" element={<SkyPage />} />
|
||||||
<Route path="week" element={<WeekPage />} />
|
<Route path="week" element={<WeekPage />} />
|
||||||
|
|||||||
@@ -1,72 +1,14 @@
|
|||||||
import { client } from './client/client.gen'
|
import { configureApi } from '@nalssigak/shared/api/setup'
|
||||||
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth'
|
|
||||||
|
|
||||||
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
||||||
export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '')
|
export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '')
|
||||||
|
|
||||||
type Refresh = 'ok' | 'rejected' | 'unreachable'
|
// 사파리 프라이빗 모드 등에서는 localStorage 를 읽는 것만으로 에러가 나서 쓸 때마다 꺼낸다
|
||||||
|
configureApi({
|
||||||
// 401이 한꺼번에 와도 갱신은 한 번만
|
baseUrl: API_BASE_URL,
|
||||||
let refreshing: Promise<Refresh> | null = null
|
storage: {
|
||||||
|
getItem: (key) => localStorage.getItem(key),
|
||||||
/** 서버가 거절하면 'rejected', 네트워크 오류·5xx 면 'unreachable' (이때는 토큰을 지우지 않는다) */
|
setItem: (key, value) => localStorage.setItem(key, value),
|
||||||
function refreshTokens(): Promise<Refresh> {
|
removeItem: (key) => localStorage.removeItem(key),
|
||||||
refreshing ??= (async (): Promise<Refresh> => {
|
},
|
||||||
const token = getRefreshToken()
|
|
||||||
if (!token) return 'rejected'
|
|
||||||
const res = await fetch(`${API_BASE_URL}/v1/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: token }) })
|
|
||||||
if (res.status >= 500) return 'unreachable'
|
|
||||||
const body = res.ok ? await res.json() : null
|
|
||||||
if (!body?.result?.success || !body.access_token) return 'rejected'
|
|
||||||
setTokens(body.access_token, body.refresh_token ?? token)
|
|
||||||
return 'ok'
|
|
||||||
})()
|
|
||||||
.catch((): Refresh => 'unreachable')
|
|
||||||
.finally(() => {
|
|
||||||
refreshing = null
|
|
||||||
})
|
|
||||||
return refreshing
|
|
||||||
}
|
|
||||||
|
|
||||||
const NO_REFRESH = ['/v1/auth/login', '/v1/auth/signup', '/v1/auth/refresh']
|
|
||||||
|
|
||||||
/** 같은 요청을 토큰만 바꿔(null 이면 빼고) 다시 보낼 수 있게 복사한다 */
|
|
||||||
function withToken(request: Request, token: string | null) {
|
|
||||||
const copy = request.clone()
|
|
||||||
if (token) copy.headers.set('Authorization', `Bearer ${token}`)
|
|
||||||
else copy.headers.delete('Authorization')
|
|
||||||
return copy
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 401이면 토큰을 한 번 갱신해 같은 요청을 다시 보낸다.
|
|
||||||
* 갱신이 거절되면 토큰을 지우고, 로그인 없이 되는 요청은 그냥 다시 보내고, 로그인이 꼭 필요한 요청만 로그인 창을 띄운다.
|
|
||||||
*/
|
|
||||||
async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
|
||||||
const request = input instanceof Request && !init ? input : new Request(input, init)
|
|
||||||
const retry = request.clone()
|
|
||||||
const response = await fetch(request)
|
|
||||||
if (response.status !== 401 || NO_REFRESH.includes(new URL(request.url).pathname)) return response
|
|
||||||
if (request.headers.has('Authorization')) {
|
|
||||||
const result = await refreshTokens()
|
|
||||||
if (result === 'unreachable') return response
|
|
||||||
if (result === 'ok') {
|
|
||||||
const again = await fetch(withToken(retry, getAccessToken()))
|
|
||||||
if (again.status !== 401) return again
|
|
||||||
}
|
|
||||||
if (getAccessToken()) clearTokens()
|
|
||||||
const anonymous = await fetch(withToken(retry, null))
|
|
||||||
if (anonymous.status !== 401) return anonymous
|
|
||||||
}
|
|
||||||
// 로그아웃하다 만료된 거면 로그인 창을 띄우지 않는다
|
|
||||||
if (new URL(request.url).pathname !== '/v1/auth/logout') emitAuthRequired()
|
|
||||||
return response
|
|
||||||
}
|
|
||||||
|
|
||||||
client.setConfig({ baseUrl: API_BASE_URL, throwOnError: true, fetch: authFetch })
|
|
||||||
|
|
||||||
client.interceptors.request.use((request) => {
|
|
||||||
const token = getAccessToken()
|
|
||||||
if (token) request.headers.set('Authorization', `Bearer ${token}`)
|
|
||||||
return request
|
|
||||||
})
|
})
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||||
import { NavLink, Outlet, useLocation } from 'react-router'
|
import { NavLink, Outlet, useLocation } from 'react-router'
|
||||||
import { useIsFetching, useQuery } from '@tanstack/react-query'
|
import { useIsFetching, useQuery } from '@tanstack/react-query'
|
||||||
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { kindOfHour, kst, seasonOf, type TimeKind } from './lib'
|
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
|
||||||
import './b.css'
|
import './b.css'
|
||||||
import { AuthProvider } from './auth'
|
import { AuthProvider } from './auth'
|
||||||
import { RegionProvider } from './region'
|
import { RegionProvider } from './region'
|
||||||
@@ -48,17 +48,17 @@ function TopBar() {
|
|||||||
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2.5 px-4 pt-[env(safe-area-inset-top,0px)]">
|
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
|
||||||
{tab?.title ? <h1 className="shrink-0 font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="shrink-0 font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
{tab?.title ? <h1 className="shrink-0 font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="shrink-0 font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
||||||
<SeasonChip />
|
<SeasonChip />
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => open({ type: 'region' })}
|
onClick={() => open({ type: 'region' })}
|
||||||
aria-label={`위치 바꾸기, 지금 ${region.name}`}
|
aria-label={`위치 바꾸기, 지금 ${region.name}`}
|
||||||
className="ml-auto flex cursor-pointer items-center gap-1 rounded-full bg-white px-3 pt-1 pb-2 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
|
className="ml-auto flex shrink-0 cursor-pointer items-center gap-1 rounded-full bg-white px-3 pt-1 pb-2 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
|
||||||
>
|
>
|
||||||
<PinIcon className="size-3.5" />
|
<PinIcon className="size-3.5 shrink-0" />
|
||||||
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : region.name}
|
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : <span className="truncate whitespace-nowrap"><span className="max-[399px]:hidden">{region.name}</span><span className="min-[400px]:hidden">{region.name.split(' ').at(-1)}</span></span>}
|
||||||
</button>
|
</button>
|
||||||
{mePending ? (
|
{mePending ? (
|
||||||
<Skel shape className="size-9 shrink-0 rounded-full" />
|
<Skel shape className="size-9 shrink-0 rounded-full" />
|
||||||
@@ -208,6 +208,10 @@ function Shell() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
window.scrollTo({ top: 0 })
|
window.scrollTo({ top: 0 })
|
||||||
}, [pathname])
|
}, [pathname])
|
||||||
|
// 지금 보고 있는 탭을 다시 누르면 맨 위로
|
||||||
|
const toTopIfHere = (to: string) => () => {
|
||||||
|
if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||||
|
}
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', NOTCH_BG[kind])
|
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', NOTCH_BG[kind])
|
||||||
}, [kind])
|
}, [kind])
|
||||||
@@ -228,14 +232,14 @@ function Shell() {
|
|||||||
{TABS.map((t) =>
|
{TABS.map((t) =>
|
||||||
t.key === 'today' ? (
|
t.key === 'today' ? (
|
||||||
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
|
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
|
||||||
<NavLink key={t.key} to={t.to} end className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive ? 'text-(--orange)' : 'text-(--ink3)')}>
|
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') ? 'text-(--orange)' : 'text-(--ink3)')}>
|
||||||
<span className="b-keep-bg grid size-[60px] place-items-center rounded-full bg-[linear-gradient(160deg,#ffb067,var(--orange)_55%,var(--orange-deep))] text-white shadow-[0_8px_18px_rgb(255_122_69/0.45),inset_0_-4px_0_rgb(0_0_0/0.12)] ring-4 ring-white/85 [&_svg]:stroke-[2.6]">
|
<span className="b-keep-bg grid size-[60px] place-items-center rounded-full bg-[linear-gradient(160deg,#ffb067,var(--orange)_55%,var(--orange-deep))] text-white shadow-[0_8px_18px_rgb(255_122_69/0.45),inset_0_-4px_0_rgb(0_0_0/0.12)] ring-4 ring-white/85 [&_svg]:stroke-[2.6]">
|
||||||
<TabIcon name={t.key} className="size-[30px]" />
|
<TabIcon name={t.key} className="size-[30px]" />
|
||||||
</span>
|
</span>
|
||||||
{t.label}
|
{t.label}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
) : (
|
) : (
|
||||||
<NavLink key={t.key} to={t.to} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
|
<NavLink key={t.key} to={t.to} onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
|
||||||
<TabIcon name={t.key} className="size-[25px]" />
|
<TabIcon name={t.key} className="size-[25px]" />
|
||||||
{t.label}
|
{t.label}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
|
import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
|
import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { kst, loadOf, MEDALS, seasonOf } from './lib'
|
import { kst, loadOf, MEDALS, seasonOf } from '@nalssigak/shared/lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
|
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
|
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
|
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, clockShort, fall } from './lib'
|
import { cardBg, clockShort } from '@nalssigak/shared/lib'
|
||||||
import type { SlideBg } from './types'
|
import { fall } from './lib'
|
||||||
import { deg } from './weatherText'
|
import type { SlideBg } from '@nalssigak/shared/lib/types'
|
||||||
|
import { deg } from '@nalssigak/shared/lib/weatherText'
|
||||||
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
||||||
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
|
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { useAuth } from './authContext'
|
import { useAuth } from './authContext'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getSeasonWeekOptions, listArticlesOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { ArticleCategory } from '../api/client/types.gen'
|
import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib'
|
import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
|
||||||
|
import { ARTICLE_CAT, fall } from './lib'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
|
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
||||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||||
import { setTokens, subscribeAuth } from '../api/auth'
|
import { setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
|
||||||
import { SITE_URL } from '../api/setup'
|
import { SITE_URL } from '../api/setup'
|
||||||
import {
|
import {
|
||||||
addCommentMutation,
|
addCommentMutation,
|
||||||
@@ -18,12 +18,13 @@ import {
|
|||||||
signupMutation,
|
signupMutation,
|
||||||
unlikeCommentMutation,
|
unlikeCommentMutation,
|
||||||
updateMeMutation,
|
updateMeMutation,
|
||||||
} from '../api/client/@tanstack/react-query.gen'
|
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
|
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { track } from '../lib/analytics'
|
import { track } from '../lib/analytics'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { useAuth } from './authContext'
|
import { useAuth } from './authContext'
|
||||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
|
||||||
|
import { ARTICLE_CAT } from './lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSky } from './skyContext'
|
import { useSky } from './skyContext'
|
||||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { useState, type ReactNode } from 'react'
|
import { useState, type ReactNode } from 'react'
|
||||||
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import type { BestTime, SkyPlanData } from '../api/client/types.gen'
|
import type { BestTime, SkyPlanData } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { clockShort, loadOf } from './lib'
|
import { clockShort, loadOf } from '@nalssigak/shared/lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { MapLink, Sec, Skel, StateBox } from './ui'
|
import { MapLink, Sec, Skel, StateBox } from './ui'
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +1,21 @@
|
|||||||
import { Fragment, useEffect, useState, type ReactNode } from 'react'
|
import { Fragment, useEffect, useState, type ReactNode } from 'react'
|
||||||
import { Link } from 'react-router'
|
import { Link } from 'react-router'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
|
import type { BandArticle, BandEvent, Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
|
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
|
||||||
|
import { fall } from './lib'
|
||||||
import { PostCard, PostCardSkel } from './Post'
|
import { PostCard, PostCardSkel } from './Post'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { useSky } from './skyContext'
|
import { useSky } from './skyContext'
|
||||||
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||||
import { deg, slotAt } from './weatherText'
|
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'
|
||||||
|
import { atSlot, KINDS, moonPath, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today'
|
||||||
|
|
||||||
type Mode = 'now' | TimeKind
|
type Mode = 'now' | TimeKind
|
||||||
|
|
||||||
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
|
|
||||||
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
|
|
||||||
const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
|
|
||||||
morning: { label: '아침', hour: 7 },
|
|
||||||
day: { label: '낮', hour: 13 },
|
|
||||||
sunset: { label: '저녁', hour: 18 },
|
|
||||||
night: { label: '밤', hour: 22 },
|
|
||||||
}
|
|
||||||
|
|
||||||
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
|
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
|
||||||
const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, '--top': `${(i * 29) % 90}%`, '--dl': `${((i * 37) % 100) / 100}s`, '--dur': `${0.55 + ((i * 13) % 5) / 10}s` }))
|
const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, '--top': `${(i * 29) % 90}%`, '--dl': `${((i * 37) % 100) / 100}s`, '--dur': `${0.55 + ((i * 13) % 5) / 10}s` }))
|
||||||
const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, '--top': `${(i * 31) % 90}%`, '--dl': `${((i * 53) % 100) / 25}s`, '--dur': `${3.2 + ((i * 7) % 5) / 2}s` }))
|
const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, '--top': `${(i * 31) % 90}%`, '--dl': `${((i * 53) % 100) / 25}s`, '--dur': `${3.2 + ((i * 7) % 5) / 2}s` }))
|
||||||
@@ -64,34 +57,8 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
|
|||||||
|
|
||||||
const failed = (load: Load) => load === 'error' || load === 'retrying'
|
const failed = (load: Load) => load === 'error' || load === 'retrying'
|
||||||
|
|
||||||
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간
|
|
||||||
const SLOT_KEY: Record<TimeKind, string> = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' }
|
|
||||||
|
|
||||||
/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */
|
|
||||||
function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
|
|
||||||
const k = kind && SLOT_KEY[kind]
|
|
||||||
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items
|
|
||||||
const on = items.filter((g) => g.slot_ranks?.[k] != null && g.slots?.[k] != null)
|
|
||||||
return [
|
|
||||||
...on.map((g) => ({ ...g, score: g.slots![k], rank: g.slot_ranks![k], active: true })).sort((a, b) => a.rank - b.rank),
|
|
||||||
...items.filter((g) => !on.includes(g)).map((g) => ({ ...g, active: false })),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load }
|
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load }
|
||||||
|
|
||||||
type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
|
|
||||||
|
|
||||||
/** 예보 칸 하나의 하늘: 비·눈이 오면 그걸, 아니면 구름 양 */
|
|
||||||
function weatherOf(slot?: WeatherSlot): Weather {
|
|
||||||
const r = slot?.rain_type
|
|
||||||
if (r === RainType.RAIN || r === RainType.SHOWER) return 'rain'
|
|
||||||
if (r === RainType.SNOW) return 'snow'
|
|
||||||
if (r === RainType.SLEET) return 'sleet'
|
|
||||||
return slot?.sky === Sky.CLOUDY ? 'cloudy' : slot?.sky === Sky.PARTLY ? 'partly' : 'clear'
|
|
||||||
}
|
|
||||||
|
|
||||||
const WEATHER_ICON: Record<Weather, string> = { clear: 'sun', partly: 'sun_cloud', cloudy: 'cloud', rain: 'rain', snow: 'snow', sleet: 'snow' }
|
|
||||||
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋
|
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋
|
||||||
const CLOUDS = [
|
const CLOUDS = [
|
||||||
{ cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' },
|
{ cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' },
|
||||||
@@ -215,18 +182,6 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const WANING = ['기우는 달', '하현달', '그믐달']
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 반지름 r 인 달에서 밝은 쪽(lit) 또는 어두운 쪽 경로. 차오르는 달 기준(오른쪽이 밝음), 기우는 달은 좌우를 뒤집어 쓴다.
|
|
||||||
* 바깥 반원과 명암 경계(가로 반지름 r·|1-2k| 인 타원 호)로 이루어진다.
|
|
||||||
*/
|
|
||||||
function moonPath(pct: number, r: number, lit: boolean) {
|
|
||||||
const k = pct / 100
|
|
||||||
const edge = `A${r * Math.abs(1 - 2 * k)},${r} 0 0 ${k < 0.5 ? 0 : 1} 0,${-r}`
|
|
||||||
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function Stories({ items }: { items: TopIndex[] }) {
|
function Stories({ items }: { items: TopIndex[] }) {
|
||||||
const { open } = useSheet()
|
const { open } = useSheet()
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { useRef, useState, type ReactNode } from 'react'
|
import { useRef, useState, type ReactNode } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, dateRange, loadOf, shortDay } from './lib'
|
import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
|
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
|
||||||
import { clearTokens, getAccessToken, subscribeAuth } from '../api/auth'
|
import { clearTokens, getAccessToken, subscribeAuth } from '@nalssigak/shared/api/auth'
|
||||||
import { meOptions } from '../api/client/@tanstack/react-query.gen'
|
import { meOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { logout as logoutOnServer } from '../api/client/sdk.gen'
|
import { logout as logoutOnServer } from '@nalssigak/shared/api/client/sdk.gen'
|
||||||
import { AuthContext } from './authContext'
|
import { AuthContext } from './authContext'
|
||||||
|
|
||||||
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
|
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createContext, use } from 'react'
|
import { createContext, use } from 'react'
|
||||||
import type { Me } from '../api/client/types.gen'
|
import type { Me } from '@nalssigak/shared/api/client/types.gen'
|
||||||
|
|
||||||
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
|
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
|
||||||
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void }
|
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void }
|
||||||
|
|||||||
+2
-131
@@ -1,4 +1,5 @@
|
|||||||
import type { CSSProperties } from 'react'
|
import type { CSSProperties } from 'react'
|
||||||
|
import { ARTICLE_LABEL } from '@nalssigak/shared/lib'
|
||||||
|
|
||||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain'])
|
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain'])
|
||||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
||||||
@@ -10,136 +11,6 @@ export function iconSrc(name: string) {
|
|||||||
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
|
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MEDALS = ['gold', 'silver', 'bronze'] as const
|
|
||||||
|
|
||||||
/** 고를 수 있는 프로필 캐릭터 (백엔드 CHARACTERS 와 같아야 한다) */
|
|
||||||
export const CHARACTERS = [
|
|
||||||
['rabbit', '토끼'],
|
|
||||||
['bear', '곰'],
|
|
||||||
['dog', '강아지'],
|
|
||||||
['sun', '해님'],
|
|
||||||
['moon', '달님'],
|
|
||||||
['cloud', '구름'],
|
|
||||||
] as const
|
|
||||||
|
|
||||||
/** 프로필 배경색 (백엔드 COLORS 와 같아야 한다) */
|
|
||||||
export const AVATAR_COLORS: Record<string, string> = { orange: '#ff8e4e', blue: '#4f97e3', green: '#1f9d62', purple: '#7a5cd6', pink: '#d6457a', brown: '#a8643a' }
|
|
||||||
|
|
||||||
/** 오늘 기분 (백엔드 MOODS 와 같아야 한다) */
|
|
||||||
export const MOODS = [
|
|
||||||
['clear', '☀️', '맑음'],
|
|
||||||
['partly', '⛅', '구름 조금'],
|
|
||||||
['cloudy', '☁️', '흐림'],
|
|
||||||
['rain', '🌧️', '비'],
|
|
||||||
['thunder', '⚡', '번개'],
|
|
||||||
['snow', '❄️', '눈'],
|
|
||||||
['fog', '🌫️', '안개'],
|
|
||||||
['rainbow', '🌈', '무지개'],
|
|
||||||
] as const
|
|
||||||
|
|
||||||
export const moodEmoji = (mood?: string | null) => MOODS.find(([k]) => k === mood)?.[1]
|
|
||||||
|
|
||||||
export const fall = (d: string, f = '4.8s', amp?: string) => ({ '--d': d, '--f': f, ...(amp ? { '--amp': amp } : {}) }) as CSSProperties
|
export const fall = (d: string, f = '4.8s', amp?: string) => ({ '--d': d, '--f': f, ...(amp ? { '--amp': amp } : {}) }) as CSSProperties
|
||||||
|
|
||||||
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
|
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: [ARTICLE_LABEL[1], 'text-[#1f9d62]'], 2: [ARTICLE_LABEL[2], 'text-[#7a5cd6]'], 3: [ARTICLE_LABEL[3], 'text-(--orange)'] }
|
||||||
|
|
||||||
// 달(1~12) → 계절 이름과 아이콘. 봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2 (서버 각 제철 기준과 같다)
|
|
||||||
const SEASONS: [string, string][] = [['겨울', 'snow'], ['봄', 'garden'], ['여름', 'sun'], ['가을', 'maple']]
|
|
||||||
export const seasonOf = (month: number) => SEASONS[Math.floor((month % 12) / 3)]
|
|
||||||
|
|
||||||
const KST = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Seoul', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23', weekday: 'short' })
|
|
||||||
const WD_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
|
||||||
|
|
||||||
/** 한국 시각으로 쪼개기 (브라우저 시간대와 상관없이) */
|
|
||||||
export function kst(input: string | Date) {
|
|
||||||
const parts = Object.fromEntries(KST.formatToParts(typeof input === 'string' ? new Date(input) : input).map((p) => [p.type, p.value]))
|
|
||||||
return { y: +parts.year, mo: +parts.month, d: +parts.day, h: +parts.hour, mi: +parts.minute, wd: WD_EN.indexOf(parts.weekday) }
|
|
||||||
}
|
|
||||||
|
|
||||||
const h12 = (h: number) => h % 12 || 12
|
|
||||||
|
|
||||||
/** 18:25 → "18:25" (포스트·플랜과 같은 24시간제) */
|
|
||||||
export function clockShort(iso: string) {
|
|
||||||
const t = kst(iso)
|
|
||||||
return `${t.h}:${String(t.mi).padStart(2, '0')}`
|
|
||||||
}
|
|
||||||
|
|
||||||
const COMPASS = ['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동', '남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서']
|
|
||||||
|
|
||||||
/** 방위각 → 16방위 이름. 263 → "서" */
|
|
||||||
/** 네이버 지도에서 장소 이름(또는 주소)으로 찾기 */
|
|
||||||
export const naverMap = (query: string) => `https://map.naver.com/p/search/${encodeURIComponent(query)}`
|
|
||||||
|
|
||||||
export const compass = (deg: number) => COMPASS[Math.round(deg / 22.5) % 16]
|
|
||||||
|
|
||||||
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
|
|
||||||
export function timeWords(iso: string) {
|
|
||||||
const t = kst(iso)
|
|
||||||
return `${h12(t.h)}시${t.mi === 0 ? '' : t.mi === 30 ? ' 반' : ` ${t.mi}분`}`
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 발표 시각 → "방금" · "12분 전" · "3시간 전" */
|
|
||||||
export function ago(iso: string | null | undefined, now = Date.now()) {
|
|
||||||
if (!iso) return '오늘'
|
|
||||||
const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
|
|
||||||
if (min < 5) return '방금'
|
|
||||||
if (min < 60) return `${min}분 전`
|
|
||||||
return `${Math.floor(min / 60)}시간 전`
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */
|
|
||||||
export function dayLabel(date: string, index: number) {
|
|
||||||
if (index === 0) return '오늘'
|
|
||||||
if (index === 1) return '내일'
|
|
||||||
const [, m, d] = date.split('-').map(Number)
|
|
||||||
const wd = new Date(`${date}T12:00:00+09:00`).getUTCDay()
|
|
||||||
return `${WEEKDAYS[wd]} ${m}.${d}`
|
|
||||||
}
|
|
||||||
|
|
||||||
export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
|
|
||||||
|
|
||||||
// 서울 월별 대략 일몰 시각(시). 서버 값(/v1/feed hero.sky_mode)이 없을 때만 쓴다
|
|
||||||
const SUNSET_HOUR = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]
|
|
||||||
|
|
||||||
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05 */
|
|
||||||
export function kindOfHour(h: number, month = new Date().getMonth() + 1, minute = 0): TimeKind {
|
|
||||||
const at = h + minute / 60
|
|
||||||
const sunset = SUNSET_HOUR[month - 1]
|
|
||||||
if (at >= 5 && at < 11) return 'morning'
|
|
||||||
if (at >= 11 && at < sunset + 1) return at < sunset - 2 ? 'day' : 'sunset'
|
|
||||||
return 'night'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** "서울 마포구" → "서울" */
|
|
||||||
export const sidoOf = (regionName: string) => regionName.split(' ')[0]
|
|
||||||
|
|
||||||
/** 2026-10-02 ~ 2026-10-11 → "10.2 ~ 10.11", 하루짜리는 "10.3" */
|
|
||||||
export function dateRange(start: string, end: string) {
|
|
||||||
return start === end ? shortDay(start) : `${shortDay(start)} ~ ${shortDay(end)}`
|
|
||||||
}
|
|
||||||
|
|
||||||
const CARD_BG = ['night', 'butter', 'lilac', 'mint', 'peach', 'sky'] as const
|
|
||||||
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', popup: 'peach', exhibition: 'lilac', concert: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
|
|
||||||
|
|
||||||
/** API에 배경색이 없어 아이콘·순서로 카드 배경을 고른다 */
|
|
||||||
export function cardBg(icon: string, index: number) {
|
|
||||||
return ICON_BG[icon] && icon !== 'calendar' ? ICON_BG[icon] : CARD_BG[index % CARD_BG.length]
|
|
||||||
}
|
|
||||||
|
|
||||||
/** "2026-09-23" → "9.23" */
|
|
||||||
export const shortDay = (day: string) => day.split('-').slice(1).map(Number).join('.')
|
|
||||||
|
|
||||||
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: ['계절 소식', 'text-[#1f9d62]'], 2: ['날씨 상식', 'text-[#7a5cd6]'], 3: ['각 원리', 'text-(--orange)'] }
|
|
||||||
|
|
||||||
/** 읽을거리 한 줄 정보: "계절 소식 · 3분" */
|
|
||||||
export const articleMeta = (a: { category: number; read_minutes: number }) => `${ARTICLE_CAT[a.category]?.[0] ?? '읽을거리'} · ${a.read_minutes}분`
|
|
||||||
|
|
||||||
export type Load = 'loading' | 'error' | 'retrying' | 'ready'
|
|
||||||
type QueryLike = { data?: unknown; isPending: boolean; isError: boolean; isFetching: boolean; errorUpdateCount: number }
|
|
||||||
|
|
||||||
/** 데이터가 있으면 ready. 실패 뒤 다시 받는 중(retrying)은 처음 불러오기(loading)와 구분한다 */
|
|
||||||
export function loadOf(q: QueryLike): Load {
|
|
||||||
if (q.data !== undefined) return 'ready'
|
|
||||||
if (q.isError) return q.isFetching ? 'retrying' : 'error'
|
|
||||||
return q.isFetching && q.errorUpdateCount > 0 ? 'retrying' : 'loading'
|
|
||||||
}
|
|
||||||
+68
-18
@@ -1,11 +1,26 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||||
import { nearestRegion } from '../api/client/sdk.gen'
|
import { matchPath, useLocation, useNavigate } from 'react-router'
|
||||||
import type { RegionData } from '../api/client/types.gen'
|
import regionPages from '../../seo/region.json'
|
||||||
|
import { nearestRegion } from '@nalssigak/shared/api/client/sdk.gen'
|
||||||
|
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { track } from '../lib/analytics'
|
import { track } from '../lib/analytics'
|
||||||
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
||||||
|
|
||||||
const KEY = 'nalssigak.b.region'
|
const KEY = 'nalssigak.b.region'
|
||||||
|
|
||||||
|
type RegionPage = (typeof regionPages)[number]
|
||||||
|
|
||||||
|
/** /today/gyeonggi/seongnam 같은 지역 페이지 주소면 그 페이지 */
|
||||||
|
function pageOf(pathname: string): RegionPage | undefined {
|
||||||
|
const m = matchPath('/today/:sido/:place', pathname)
|
||||||
|
return m ? regionPages.find((p) => p.path === `${m.params.sido}/${m.params.place}`) : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 지역 페이지 안의 구: 구로 나뉜 시는 r 이 그 시 안이면 r, 아니면 시청이 있는 구 */
|
||||||
|
function regionIn(page: RegionPage, r?: RegionData | null): RegionData {
|
||||||
|
return page.regions.find((g) => g.code === r?.code) ?? page.regions.find((g) => g.code === page.main)!
|
||||||
|
}
|
||||||
|
|
||||||
function readStored(): RegionData | null {
|
function readStored(): RegionData | null {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(KEY)
|
const raw = localStorage.getItem(KEY)
|
||||||
@@ -26,33 +41,45 @@ function writeStored(r: RegionData) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function RegionProvider({ children }: { children: ReactNode }) {
|
export function RegionProvider({ children }: { children: ReactNode }) {
|
||||||
|
const { pathname } = useLocation()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const page = pageOf(pathname)
|
||||||
|
const pageRef = useRef(page)
|
||||||
|
useEffect(() => {
|
||||||
|
pageRef.current = page
|
||||||
|
}, [page])
|
||||||
const [stored] = useState(readStored)
|
const [stored] = useState(readStored)
|
||||||
const [region, setRegionState] = useState<RegionData>(stored ?? DEFAULT_REGION)
|
const [landing] = useState(page)
|
||||||
|
const [chosen, setRegionState] = useState<RegionData>(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION)))
|
||||||
|
// 앱 안에서 다른 지역 페이지로 옮겨 가면 그 지역으로
|
||||||
|
const region = page && !page.regions.some((g) => g.code === chosen.code) ? regionIn(page, stored) : chosen
|
||||||
const canLocate = typeof navigator !== 'undefined' && 'geolocation' in navigator
|
const canLocate = typeof navigator !== 'undefined' && 'geolocation' in navigator
|
||||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!stored && canLocate ? 'locating' : 'idle')
|
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!landing && !stored && canLocate ? 'locating' : 'idle')
|
||||||
|
|
||||||
|
// 지역 페이지에서 고르면 주소도 그 지역 페이지로 바꿔, 공유한 링크가 보던 화면과 같게 한다
|
||||||
const setRegion = useCallback((r: RegionData) => {
|
const setRegion = useCallback((r: RegionData) => {
|
||||||
setRegionState(r)
|
setRegionState(r)
|
||||||
writeStored(r)
|
writeStored(r)
|
||||||
}, [])
|
const next = regionPages.find((p) => p.regions.some((g) => g.code === r.code))
|
||||||
|
if (pageRef.current && next && next !== pageRef.current) navigate(`/today/${next.path}`)
|
||||||
|
}, [navigate])
|
||||||
|
|
||||||
const findNearest = useCallback((onFound?: () => void) => {
|
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음)
|
||||||
|
const findNearest = useCallback((apply: (r: RegionData) => void, quiet = false) => {
|
||||||
navigator.geolocation.getCurrentPosition(
|
navigator.geolocation.getCurrentPosition(
|
||||||
(pos) => {
|
(pos) => {
|
||||||
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
||||||
.then(({ data: res }) => {
|
.then(({ data: res }) => {
|
||||||
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||||
setRegion(res.region)
|
|
||||||
setLocateStatus('idle')
|
setLocateStatus('idle')
|
||||||
track('region_change', { region_name: res.region.name, method: 'location' })
|
apply(res.region)
|
||||||
onFound?.()
|
|
||||||
})
|
})
|
||||||
.catch(() => setLocateStatus('error'))
|
.catch(() => !quiet && setLocateStatus('error'))
|
||||||
},
|
},
|
||||||
(err) => setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
(err) => !quiet && setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||||
{ timeout: 10000, maximumAge: 600000 },
|
{ timeout: 10000, maximumAge: 600000 },
|
||||||
)
|
)
|
||||||
}, [setRegion])
|
}, [])
|
||||||
|
|
||||||
const locate = useCallback((onFound?: () => void) => {
|
const locate = useCallback((onFound?: () => void) => {
|
||||||
if (!canLocate) {
|
if (!canLocate) {
|
||||||
@@ -60,13 +87,36 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
setLocateStatus('locating')
|
setLocateStatus('locating')
|
||||||
findNearest(onFound)
|
findNearest((r) => {
|
||||||
}, [canLocate, findNearest])
|
setRegion(r)
|
||||||
|
track('region_change', { region_name: r.name, method: 'location' })
|
||||||
|
onFound?.()
|
||||||
|
})
|
||||||
|
}, [canLocate, findNearest, setRegion])
|
||||||
|
|
||||||
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!stored && canLocate) findNearest()
|
if (!canLocate) return
|
||||||
}, [stored, canLocate, findNearest])
|
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
||||||
|
if (!landing) {
|
||||||
|
if (!stored) {
|
||||||
|
findNearest((r) => {
|
||||||
|
setRegion(r)
|
||||||
|
track('region_change', { region_name: r.name, method: 'location' })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 지역 페이지로 들어오면 그 지역을 보여 준다. 구로 나뉜 시는 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구로
|
||||||
|
if (landing.regions.length < 2) return
|
||||||
|
navigator.permissions?.query({ name: 'geolocation' })
|
||||||
|
.then((s) => {
|
||||||
|
if (s.state !== 'granted') return
|
||||||
|
findNearest((r) => {
|
||||||
|
if (pageRef.current === landing && landing.regions.some((g) => g.code === r.code)) setRegionState(r)
|
||||||
|
}, true)
|
||||||
|
})
|
||||||
|
.catch((e) => console.warn('위치 권한 상태를 읽지 못함', e))
|
||||||
|
}, [canLocate, landing, stored, findNearest, setRegion])
|
||||||
|
|
||||||
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
||||||
return <RegionContext value={api}>{children}</RegionContext>
|
return <RegionContext value={api}>{children}</RegionContext>
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { createContext, use } from 'react'
|
import { createContext, use } from 'react'
|
||||||
import type { RegionData } from '../api/client/types.gen'
|
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||||
|
|
||||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
||||||
|
|
||||||
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus }
|
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus }
|
||||||
|
|
||||||
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
|
export { DEFAULT_REGION } from '@nalssigak/shared/lib'
|
||||||
|
|
||||||
export const RegionContext = createContext<RegionApi | null>(null)
|
export const RegionContext = createContext<RegionApi | null>(null)
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createContext, use } from 'react'
|
import { createContext, use } from 'react'
|
||||||
import type { TimeKind } from './lib'
|
import type { TimeKind } from '@nalssigak/shared/lib'
|
||||||
|
|
||||||
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼으로 고른 값은 탭을 옮겨도 유지된다 */
|
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼으로 고른 값은 탭을 옮겨도 유지된다 */
|
||||||
export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
|
export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ import { useState, type CSSProperties, type ReactNode } from 'react'
|
|||||||
import { Link } from 'react-router'
|
import { Link } from 'react-router'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { useCarousel, type Carousel } from './carousel'
|
import { useCarousel, type Carousel } from './carousel'
|
||||||
import { AVATAR_COLORS, iconSrc, moodEmoji, naverMap, type Load } from './lib'
|
import { AVATAR_COLORS, moodEmoji, naverMap, type Load } from '@nalssigak/shared/lib'
|
||||||
|
import { iconSrc } from './lib'
|
||||||
|
|
||||||
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
|
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
"module": "esnext",
|
"module": "esnext",
|
||||||
"types": ["vite/client"],
|
"types": ["vite/client"],
|
||||||
"allowArbitraryExtensions": true,
|
"allowArbitraryExtensions": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
|
||||||
/* Bundler mode */
|
/* Bundler mode */
|
||||||
|
|||||||
+30
-4
@@ -1,16 +1,18 @@
|
|||||||
import { readFileSync, writeFileSync } from 'node:fs'
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||||
import { resolve } from 'node:path'
|
import { dirname, resolve } from 'node:path'
|
||||||
import tailwindcss from '@tailwindcss/vite'
|
import tailwindcss from '@tailwindcss/vite'
|
||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
import { defineConfig, type Plugin } from 'vite'
|
import { defineConfig, type Plugin } from 'vite'
|
||||||
|
|
||||||
type Gak = { name: string; description: string }
|
type Gak = { name: string; description: string }
|
||||||
|
type RegionPage = { path: string; name: string; main: string; regions: { code: string; name: string }[] }
|
||||||
|
|
||||||
const gaks: Gak[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/gak.json'), 'utf8'))
|
const gaks: Gak[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/gak.json'), 'utf8'))
|
||||||
const gakList = `<ul>${gaks.map((g) => `<li><b>${g.name}</b>: ${g.description}</li>`).join('')}</ul>`
|
const gakList = `<ul>${gaks.map((g) => `<li><b>${g.name}</b>: ${g.description}</li>`).join('')}</ul>`
|
||||||
|
const regionPages: RegionPage[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/region.json'), 'utf8'))
|
||||||
|
|
||||||
/** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */
|
/** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */
|
||||||
const PAGES: { path: string; title: string; description: string; body: string }[] = [
|
const PAGES: { path: string; title: string; description: string; body: string; code?: string }[] = [
|
||||||
{
|
{
|
||||||
path: 'gak',
|
path: 'gak',
|
||||||
title: '오늘의 각 · 세차각·빨래각·러닝각 점수 | 날씨각',
|
title: '오늘의 각 · 세차각·빨래각·러닝각 점수 | 날씨각',
|
||||||
@@ -37,6 +39,23 @@ const PAGES: { path: string; title: string; description: string; body: string }[
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
/** 제목 앞자리: 검색어처럼 시군구 이름부터 (경기 성남시 → 성남시) */
|
||||||
|
const headName = (name: string) => name.split(' ').at(-1)!
|
||||||
|
|
||||||
|
/** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */
|
||||||
|
for (const r of regionPages) {
|
||||||
|
const sido = r.path.split('/')[0]
|
||||||
|
const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`))
|
||||||
|
const parts = r.regions.length > 1 ? `<p>${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).join(', ')}별로 따로 계산해요.</p>` : ''
|
||||||
|
PAGES.push({
|
||||||
|
path: `today/${r.path}`,
|
||||||
|
code: r.main,
|
||||||
|
title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[0]}` : ''} | 날씨각`,
|
||||||
|
description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`,
|
||||||
|
body: `<h1>${r.name} 오늘 날씨, 뭐 할까?</h1><p>${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 날씨</h2><ul>${near.map((o) => `<li><a href="/today/${o.path}">${o.name}</a></li>`).join('')}</ul>` : ''}`,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const attr = (s: string) => s.replace(/&/g, '&').replace(/"/g, '"')
|
const attr = (s: string) => s.replace(/&/g, '&').replace(/"/g, '"')
|
||||||
|
|
||||||
function seoPages(): Plugin {
|
function seoPages(): Plugin {
|
||||||
@@ -59,8 +78,15 @@ function seoPages(): Plugin {
|
|||||||
.replace(/(<meta property="og:url" content=")[^"]*"/, `$1${url}"`)
|
.replace(/(<meta property="og:url" content=")[^"]*"/, `$1${url}"`)
|
||||||
.replace(/(<link rel="canonical" href=")[^"]*"/, `$1${url}"`)
|
.replace(/(<link rel="canonical" href=")[^"]*"/, `$1${url}"`)
|
||||||
.replace(/<main>[\s\S]*<\/main>/, `<main>${p.body}<p><a href="/">날씨각 처음으로</a></p></main>`)
|
.replace(/<main>[\s\S]*<\/main>/, `<main>${p.body}<p><a href="/">날씨각 처음으로</a></p></main>`)
|
||||||
writeFileSync(resolve(outDir, `${p.path}.html`), html)
|
// 서버가 오늘 날씨를 채울 때 이 페이지의 구를 알아보는 표시
|
||||||
|
.replace('</head>', p.code ? `<meta name="region-code" content="${p.code}" />\n </head>` : '</head>')
|
||||||
|
const file = resolve(outDir, `${p.path}.html`)
|
||||||
|
mkdirSync(dirname(file), { recursive: true })
|
||||||
|
writeFileSync(file, html)
|
||||||
}
|
}
|
||||||
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
|
const urls = ['', ...PAGES.map((p) => p.path)].map((path) => ` <url><loc>${site}/${path}</loc><lastmod>${today}</lastmod></url>`)
|
||||||
|
writeFileSync(resolve(outDir, 'sitemap.xml'), `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join('\n')}\n</urlset>\n`)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+14735
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"name": "o2o-weather",
|
||||||
|
"private": true,
|
||||||
|
"workspaces": ["frontend", "mobile", "shared"]
|
||||||
|
}
|
||||||
@@ -1,10 +1,18 @@
|
|||||||
// 로그인 토큰 저장소: localStorage + 메모리, 바뀌면 구독자에게 알린다
|
// 로그인 토큰 저장소: 플랫폼 저장소(웹 localStorage, 앱 SecureStore) + 메모리, 바뀌면 구독자에게 알린다
|
||||||
const ACCESS_KEY = 'nalssigak.accessToken'
|
const ACCESS_KEY = 'nalssigak.accessToken'
|
||||||
const REFRESH_KEY = 'nalssigak.refreshToken'
|
const REFRESH_KEY = 'nalssigak.refreshToken'
|
||||||
|
|
||||||
|
export type TokenStorage = {
|
||||||
|
getItem(key: string): string | null
|
||||||
|
setItem(key: string, value: string): void
|
||||||
|
removeItem(key: string): void
|
||||||
|
}
|
||||||
|
|
||||||
|
let storage: TokenStorage | null = null
|
||||||
|
|
||||||
function readStored(key: string): string | null {
|
function readStored(key: string): string | null {
|
||||||
try {
|
try {
|
||||||
return localStorage.getItem(key)
|
return storage?.getItem(key) ?? null
|
||||||
} catch {
|
} catch {
|
||||||
// 사파리 프라이빗 모드 등에서 저장소 접근이 막히면 로그인 안 한 상태로 시작한다
|
// 사파리 프라이빗 모드 등에서 저장소 접근이 막히면 로그인 안 한 상태로 시작한다
|
||||||
return null
|
return null
|
||||||
@@ -13,15 +21,21 @@ function readStored(key: string): string | null {
|
|||||||
|
|
||||||
function writeStored(key: string, value: string | null) {
|
function writeStored(key: string, value: string | null) {
|
||||||
try {
|
try {
|
||||||
if (value) localStorage.setItem(key, value)
|
if (value) storage?.setItem(key, value)
|
||||||
else localStorage.removeItem(key)
|
else storage?.removeItem(key)
|
||||||
} catch {
|
} catch {
|
||||||
// 저장이 막혀도 이번 방문 동안은 메모리 토큰으로 계속 쓴다
|
// 저장이 막혀도 이번 방문 동안은 메모리 토큰으로 계속 쓴다
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let accessToken = readStored(ACCESS_KEY)
|
let accessToken: string | null = null
|
||||||
|
|
||||||
|
/** 앱이 뜰 때 한 번: 저장된 토큰을 읽어 로그인 상태로 시작한다 */
|
||||||
|
export function setTokenStorage(next: TokenStorage) {
|
||||||
|
storage = next
|
||||||
|
accessToken = readStored(ACCESS_KEY)
|
||||||
|
}
|
||||||
const listeners = new Set<(reason: 'change' | 'required') => void>()
|
const listeners = new Set<(reason: 'change' | 'required') => void>()
|
||||||
|
|
||||||
/** 토큰이 바뀌거나(로그인·로그아웃) 로그인이 필요할 때 알림을 받는다 */
|
/** 토큰이 바뀌거나(로그인·로그아웃) 로그인이 필요할 때 알림을 받는다 */
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,75 @@
|
|||||||
|
import { client } from './client/client.gen'
|
||||||
|
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokenStorage, setTokens, type TokenStorage } from './auth'
|
||||||
|
|
||||||
|
let baseUrl = ''
|
||||||
|
|
||||||
|
type Refresh = 'ok' | 'rejected' | 'unreachable'
|
||||||
|
|
||||||
|
// 401이 한꺼번에 와도 갱신은 한 번만
|
||||||
|
let refreshing: Promise<Refresh> | null = null
|
||||||
|
|
||||||
|
/** 서버가 거절하면 'rejected', 네트워크 오류·5xx 면 'unreachable' (이때는 토큰을 지우지 않는다) */
|
||||||
|
function refreshTokens(): Promise<Refresh> {
|
||||||
|
refreshing ??= (async (): Promise<Refresh> => {
|
||||||
|
const token = getRefreshToken()
|
||||||
|
if (!token) return 'rejected'
|
||||||
|
const res = await fetch(`${baseUrl}/v1/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: token }) })
|
||||||
|
if (res.status >= 500) return 'unreachable'
|
||||||
|
const body = res.ok ? await res.json() : null
|
||||||
|
if (!body?.result?.success || !body.access_token) return 'rejected'
|
||||||
|
setTokens(body.access_token, body.refresh_token ?? token)
|
||||||
|
return 'ok'
|
||||||
|
})()
|
||||||
|
.catch((): Refresh => 'unreachable')
|
||||||
|
.finally(() => {
|
||||||
|
refreshing = null
|
||||||
|
})
|
||||||
|
return refreshing
|
||||||
|
}
|
||||||
|
|
||||||
|
const NO_REFRESH = ['/v1/auth/login', '/v1/auth/signup', '/v1/auth/refresh']
|
||||||
|
|
||||||
|
/** 같은 요청을 토큰만 바꿔(null 이면 빼고) 다시 보낼 수 있게 복사한다 */
|
||||||
|
function withToken(request: Request, token: string | null) {
|
||||||
|
const copy = request.clone()
|
||||||
|
if (token) copy.headers.set('Authorization', `Bearer ${token}`)
|
||||||
|
else copy.headers.delete('Authorization')
|
||||||
|
return copy
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 401이면 토큰을 한 번 갱신해 같은 요청을 다시 보낸다.
|
||||||
|
* 갱신이 거절되면 토큰을 지우고, 로그인 없이 되는 요청은 그냥 다시 보내고, 로그인이 꼭 필요한 요청만 로그인 창을 띄운다.
|
||||||
|
*/
|
||||||
|
async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||||
|
const request = input instanceof Request && !init ? input : new Request(input, init)
|
||||||
|
const retry = request.clone()
|
||||||
|
const response = await fetch(request)
|
||||||
|
if (response.status !== 401 || NO_REFRESH.includes(new URL(request.url).pathname)) return response
|
||||||
|
if (request.headers.has('Authorization')) {
|
||||||
|
const result = await refreshTokens()
|
||||||
|
if (result === 'unreachable') return response
|
||||||
|
if (result === 'ok') {
|
||||||
|
const again = await fetch(withToken(retry, getAccessToken()))
|
||||||
|
if (again.status !== 401) return again
|
||||||
|
}
|
||||||
|
if (getAccessToken()) clearTokens()
|
||||||
|
const anonymous = await fetch(withToken(retry, null))
|
||||||
|
if (anonymous.status !== 401) return anonymous
|
||||||
|
}
|
||||||
|
// 로그아웃하다 만료된 거면 로그인 창을 띄우지 않는다
|
||||||
|
if (new URL(request.url).pathname !== '/v1/auth/logout') emitAuthRequired()
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 앱이 뜰 때 한 번: API 주소와 토큰 저장소를 정하고 401 갱신·토큰 헤더를 건다 */
|
||||||
|
export function configureApi(options: { baseUrl: string; storage: TokenStorage }) {
|
||||||
|
baseUrl = options.baseUrl
|
||||||
|
setTokenStorage(options.storage)
|
||||||
|
client.setConfig({ baseUrl, throwOnError: true, fetch: authFetch })
|
||||||
|
client.interceptors.request.use((request) => {
|
||||||
|
const token = getAccessToken()
|
||||||
|
if (token) request.headers.set('Authorization', `Bearer ${token}`)
|
||||||
|
return request
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import type { RegionData } from '../api/client/types.gen'
|
||||||
|
|
||||||
|
/** 위치를 모를 때 시작 지역 */
|
||||||
|
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
|
||||||
|
|
||||||
|
export const MEDALS = ['gold', 'silver', 'bronze'] as const
|
||||||
|
|
||||||
|
/** 고를 수 있는 프로필 캐릭터 (백엔드 CHARACTERS 와 같아야 한다) */
|
||||||
|
export const CHARACTERS = [
|
||||||
|
['rabbit', '토끼'],
|
||||||
|
['bear', '곰'],
|
||||||
|
['dog', '강아지'],
|
||||||
|
['sun', '해님'],
|
||||||
|
['moon', '달님'],
|
||||||
|
['cloud', '구름'],
|
||||||
|
] as const
|
||||||
|
|
||||||
|
/** 프로필 배경색 (백엔드 COLORS 와 같아야 한다) */
|
||||||
|
export const AVATAR_COLORS: Record<string, string> = { orange: '#ff8e4e', blue: '#4f97e3', green: '#1f9d62', purple: '#7a5cd6', pink: '#d6457a', brown: '#a8643a' }
|
||||||
|
|
||||||
|
/** 오늘 기분 (백엔드 MOODS 와 같아야 한다) */
|
||||||
|
export const MOODS = [
|
||||||
|
['clear', '☀️', '맑음'],
|
||||||
|
['partly', '⛅', '구름 조금'],
|
||||||
|
['cloudy', '☁️', '흐림'],
|
||||||
|
['rain', '🌧️', '비'],
|
||||||
|
['thunder', '⚡', '번개'],
|
||||||
|
['snow', '❄️', '눈'],
|
||||||
|
['fog', '🌫️', '안개'],
|
||||||
|
['rainbow', '🌈', '무지개'],
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export const moodEmoji = (mood?: string | null) => MOODS.find(([k]) => k === mood)?.[1]
|
||||||
|
|
||||||
|
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
|
||||||
|
|
||||||
|
// 달(1~12) → 계절 이름과 아이콘. 봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2 (서버 각 제철 기준과 같다)
|
||||||
|
const SEASONS: [string, string][] = [['겨울', 'snow'], ['봄', 'garden'], ['여름', 'sun'], ['가을', 'maple']]
|
||||||
|
export const seasonOf = (month: number) => SEASONS[Math.floor((month % 12) / 3)]
|
||||||
|
|
||||||
|
const KST = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Seoul', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23', weekday: 'short' })
|
||||||
|
const WD_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||||
|
|
||||||
|
/** 한국 시각으로 쪼개기 (브라우저 시간대와 상관없이) */
|
||||||
|
export function kst(input: string | Date) {
|
||||||
|
const parts = Object.fromEntries(KST.formatToParts(typeof input === 'string' ? new Date(input) : input).map((p) => [p.type, p.value]))
|
||||||
|
return { y: +parts.year, mo: +parts.month, d: +parts.day, h: +parts.hour, mi: +parts.minute, wd: WD_EN.indexOf(parts.weekday) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const h12 = (h: number) => h % 12 || 12
|
||||||
|
|
||||||
|
/** 18:25 → "18:25" (포스트·플랜과 같은 24시간제) */
|
||||||
|
export function clockShort(iso: string) {
|
||||||
|
const t = kst(iso)
|
||||||
|
return `${t.h}:${String(t.mi).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const COMPASS = ['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동', '남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서']
|
||||||
|
|
||||||
|
/** 방위각 → 16방위 이름. 263 → "서" */
|
||||||
|
/** 네이버 지도에서 장소 이름(또는 주소)으로 찾기 */
|
||||||
|
export const naverMap = (query: string) => `https://map.naver.com/p/search/${encodeURIComponent(query)}`
|
||||||
|
|
||||||
|
export const compass = (deg: number) => COMPASS[Math.round(deg / 22.5) % 16]
|
||||||
|
|
||||||
|
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
|
||||||
|
export function timeWords(iso: string) {
|
||||||
|
const t = kst(iso)
|
||||||
|
return `${h12(t.h)}시${t.mi === 0 ? '' : t.mi === 30 ? ' 반' : ` ${t.mi}분`}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 발표 시각 → "방금" · "12분 전" · "3시간 전" */
|
||||||
|
export function ago(iso: string | null | undefined, now = Date.now()) {
|
||||||
|
if (!iso) return '오늘'
|
||||||
|
const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
|
||||||
|
if (min < 5) return '방금'
|
||||||
|
if (min < 60) return `${min}분 전`
|
||||||
|
return `${Math.floor(min / 60)}시간 전`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */
|
||||||
|
export function dayLabel(date: string, index: number) {
|
||||||
|
if (index === 0) return '오늘'
|
||||||
|
if (index === 1) return '내일'
|
||||||
|
const [, m, d] = date.split('-').map(Number)
|
||||||
|
const wd = new Date(`${date}T12:00:00+09:00`).getUTCDay()
|
||||||
|
return `${WEEKDAYS[wd]} ${m}.${d}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
|
||||||
|
|
||||||
|
// 서울 월별 대략 일몰 시각(시). 서버 값(/v1/feed hero.sky_mode)이 없을 때만 쓴다
|
||||||
|
const SUNSET_HOUR = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]
|
||||||
|
|
||||||
|
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05 */
|
||||||
|
export function kindOfHour(h: number, month = new Date().getMonth() + 1, minute = 0): TimeKind {
|
||||||
|
const at = h + minute / 60
|
||||||
|
const sunset = SUNSET_HOUR[month - 1]
|
||||||
|
if (at >= 5 && at < 11) return 'morning'
|
||||||
|
if (at >= 11 && at < sunset + 1) return at < sunset - 2 ? 'day' : 'sunset'
|
||||||
|
return 'night'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "서울 마포구" → "서울" */
|
||||||
|
export const sidoOf = (regionName: string) => regionName.split(' ')[0]
|
||||||
|
|
||||||
|
/** 2026-10-02 ~ 2026-10-11 → "10.2 ~ 10.11", 하루짜리는 "10.3" */
|
||||||
|
export function dateRange(start: string, end: string) {
|
||||||
|
return start === end ? shortDay(start) : `${shortDay(start)} ~ ${shortDay(end)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const CARD_BG = ['night', 'butter', 'lilac', 'mint', 'peach', 'sky'] as const
|
||||||
|
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', popup: 'peach', exhibition: 'lilac', concert: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
|
||||||
|
|
||||||
|
/** API에 배경색이 없어 아이콘·순서로 카드 배경을 고른다 */
|
||||||
|
export function cardBg(icon: string, index: number) {
|
||||||
|
return ICON_BG[icon] && icon !== 'calendar' ? ICON_BG[icon] : CARD_BG[index % CARD_BG.length]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "2026-09-23" → "9.23" */
|
||||||
|
export const shortDay = (day: string) => day.split('-').slice(1).map(Number).join('.')
|
||||||
|
|
||||||
|
export const ARTICLE_LABEL: Record<number, string> = { 1: '계절 소식', 2: '날씨 상식', 3: '각 원리' }
|
||||||
|
|
||||||
|
/** 읽을거리 한 줄 정보: "계절 소식 · 3분" */
|
||||||
|
export const articleMeta = (a: { category: number; read_minutes: number }) => `${ARTICLE_LABEL[a.category] ?? '읽을거리'} · ${a.read_minutes}분`
|
||||||
|
|
||||||
|
export type Load = 'loading' | 'error' | 'retrying' | 'ready'
|
||||||
|
type QueryLike = { data?: unknown; isPending: boolean; isError: boolean; isFetching: boolean; errorUpdateCount: number }
|
||||||
|
|
||||||
|
/** 데이터가 있으면 ready. 실패 뒤 다시 받는 중(retrying)은 처음 불러오기(loading)와 구분한다 */
|
||||||
|
export function loadOf(q: QueryLike): Load {
|
||||||
|
if (q.data !== undefined) return 'ready'
|
||||||
|
if (q.isError) return q.isFetching ? 'retrying' : 'error'
|
||||||
|
return q.isFetching && q.errorUpdateCount > 0 ? 'retrying' : 'loading'
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { RainType, Sky, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
|
||||||
|
import type { TimeKind } from '.'
|
||||||
|
|
||||||
|
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
|
||||||
|
export const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
|
||||||
|
export const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
|
||||||
|
morning: { label: '아침', hour: 7 },
|
||||||
|
day: { label: '낮', hour: 13 },
|
||||||
|
sunset: { label: '저녁', hour: 18 },
|
||||||
|
night: { label: '밤', hour: 22 },
|
||||||
|
}
|
||||||
|
|
||||||
|
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간
|
||||||
|
export const SLOT_KEY: Record<TimeKind, string> = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' }
|
||||||
|
|
||||||
|
/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */
|
||||||
|
export function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
|
||||||
|
const k = kind && SLOT_KEY[kind]
|
||||||
|
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items
|
||||||
|
const on = items.filter((g) => g.slot_ranks?.[k] != null && g.slots?.[k] != null)
|
||||||
|
return [
|
||||||
|
...on.map((g) => ({ ...g, score: g.slots![k], rank: g.slot_ranks![k], active: true })).sort((a, b) => a.rank - b.rank),
|
||||||
|
...items.filter((g) => !on.includes(g)).map((g) => ({ ...g, active: false })),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
|
||||||
|
|
||||||
|
/** 예보 칸 하나의 하늘: 비·눈이 오면 그걸, 아니면 구름 양 */
|
||||||
|
export function weatherOf(slot?: WeatherSlot): Weather {
|
||||||
|
const r = slot?.rain_type
|
||||||
|
if (r === RainType.RAIN || r === RainType.SHOWER) return 'rain'
|
||||||
|
if (r === RainType.SNOW) return 'snow'
|
||||||
|
if (r === RainType.SLEET) return 'sleet'
|
||||||
|
return slot?.sky === Sky.CLOUDY ? 'cloudy' : slot?.sky === Sky.PARTLY ? 'partly' : 'clear'
|
||||||
|
}
|
||||||
|
|
||||||
|
export const WEATHER_ICON: Record<Weather, string> = { clear: 'sun', partly: 'sun_cloud', cloudy: 'cloud', rain: 'rain', snow: 'snow', sleet: 'snow' }
|
||||||
|
|
||||||
|
export const WANING = ['기우는 달', '하현달', '그믐달']
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 반지름 r 인 달에서 밝은 쪽(lit) 또는 어두운 쪽 경로. 차오르는 달 기준(오른쪽이 밝음), 기우는 달은 좌우를 뒤집어 쓴다.
|
||||||
|
* 바깥 반원과 명암 경계(가로 반지름 r·|1-2k| 인 타원 호)로 이루어진다.
|
||||||
|
*/
|
||||||
|
export function moonPath(pct: number, r: number, lit: boolean) {
|
||||||
|
const k = pct / 100
|
||||||
|
const edge = `A${r * Math.abs(1 - 2 * k)},${r} 0 0 ${k < 0.5 ? 0 : 1} 0,${-r}`
|
||||||
|
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
|
||||||
|
}
|
||||||
File renamed without changes.
@@ -1,5 +1,5 @@
|
|||||||
import { RainType, Sky, type WeatherSlot } from '../api/client/types.gen'
|
import { RainType, Sky, type WeatherSlot } from '../api/client/types.gen'
|
||||||
import { kst } from './lib'
|
import { kst } from '.'
|
||||||
|
|
||||||
const RAIN_TEXT: Partial<Record<RainType, string>> = { [RainType.RAIN]: '비', [RainType.SLEET]: '진눈깨비', [RainType.SNOW]: '눈', [RainType.SHOWER]: '소나기' }
|
const RAIN_TEXT: Partial<Record<RainType, string>> = { [RainType.RAIN]: '비', [RainType.SLEET]: '진눈깨비', [RainType.SNOW]: '눈', [RainType.SHOWER]: '소나기' }
|
||||||
const SKY_TEXT: Record<Sky, string> = { [Sky.CLEAR]: '맑음', [Sky.PARTLY]: '구름 많음', [Sky.CLOUDY]: '흐림' }
|
const SKY_TEXT: Record<Sky, string> = { [Sky.CLEAR]: '맑음', [Sky.PARTLY]: '구름 많음', [Sky.CLOUDY]: '흐림' }
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"name": "@nalssigak/shared",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "tsc -p ."
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@tanstack/react-query": "^5.104.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "es2023",
|
||||||
|
"lib": ["ES2023", "DOM"],
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true
|
||||||
|
},
|
||||||
|
"include": ["api", "lib"]
|
||||||
|
}
|
||||||
Reference in new issue
Block a user