Compare commits

..
Author SHA1 Message Date
minaChoi 2ab2271d61 refactor: 웹·앱 공통 코드를 shared 패키지로 분리 (npm workspaces)
- API 클라이언트·토큰 갱신·순수 함수를 shared/ (@nalssigak/shared) 로 옮김
- 토큰 저장소·API 주소는 configureApi 로 플랫폼에서 넣는다 (웹 localStorage)
- 루트 package.json 에 frontend·mobile·shared workspaces, lock 파일 하나로
- 웹 Docker 빌드 대상을 저장소 루트로 (compose context ., 루트 .dockerignore)
2026-10-14 14:27:47 +09:00
57 changed files with 15158 additions and 3625 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
# 저장소 루트를 빌드 대상으로 쓰는 건 frontend 이미지뿐이라 frontend·shared·루트 package 파일만 넘긴다
*
!package.json
!package-lock.json
!frontend
!shared
!mobile/package.json
**/node_modules
**/dist
**/*.log
**/.DS_Store
+3
View File
@@ -4,6 +4,9 @@
.env.*
!.env.example
# npm workspaces 의존성 (frontend·mobile·shared 가 루트 하나를 같이 쓴다)
node_modules/
# Python 바이트코드/캐시
__pycache__/
*.py[cod]
-8
View File
@@ -15,11 +15,3 @@ async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)")
async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), gu: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
err, html = await service.page(f"today/{sido}/{place}/{gu}")
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
+1 -8
View File
@@ -24,9 +24,6 @@ R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin
춘천 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]))
G = '''장안 jangan 권선 gwonseon 팔달 paldal 영통 yeongtong 수정 sujeong 중원 jungwon 분당 bundang 만안 manan 동안 dongan 원미 wonmi 소사 sosa 오정 ojeong 상록 sangnok 단원 danwon 덕양 deogyang 일산동 ilsandong 일산서 ilsanseo 처인 cheoin 기흥 giheung 수지 suji
만세 manse 효행 hyohaeng 병점 byeongjeom 동탄 dongtan 상당 sangdang 서원 seowon 흥덕 heungdeok 청원 cheongwon 동남 dongnam 서북 seobuk 남 nam 북 buk 의창 uichang 성산 seongsan 마산합포 masanhappo 마산회원 masanhoewon 진해 jinhae 완산 wansan 덕진 deokjin'''.split()
GU = dict(zip(G[::2], G[1::2]))
# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다
CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'}
pages = {}
@@ -39,12 +36,8 @@ for row in csv.DictReader(open(SRC, encoding='utf-8')):
p['regions'].append(r)
if len(rest) == 1 or CITY_MAIN[place] == rest[1]:
p['main'] = r['code']
# 구로 나뉜 시의 구도 자기 주소를 갖는다: /today/gyeonggi/seongnam/bundang
if len(rest) == 2:
gu = f"{path}/{GU[rest[1][:-1]]}"
pages[gu] = dict(path=gu, name=row['name'], main=r['code'], regions=[r])
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 if p['path'].count('/') == 1) == 256
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')
-11
View File
@@ -65,14 +65,3 @@ async def test_today_page_fills_real_feed(offline, monkeypatch):
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
@pytest.mark.anyio
async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
async def template(self, path):
return TEMPLATE if path == "today/gyeonggi/seongnam/bundang" 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/gyeonggi/seongnam/bundang")
assert page.status_code == 200 and "지금 20°" in page.text
+7 -3
View File
@@ -4,7 +4,8 @@ services:
# 운영형: docker compose up --build → http://localhost:8080
frontend:
build:
context: ./frontend
context: .
dockerfile: frontend/Dockerfile
target: prod
args:
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
@@ -19,13 +20,16 @@ services:
frontend-dev:
profiles: ["dev"]
build:
context: ./frontend
context: .
dockerfile: frontend/Dockerfile
target: dev
ports:
- "5173:5173"
volumes:
- ./frontend:/app
- ./frontend:/app/frontend
- ./shared:/app/shared
- /app/node_modules
- /app/frontend/node_modules
environment:
- CHOKIDAR_USEPOLLING=true
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
-7
View File
@@ -1,7 +0,0 @@
node_modules
dist
.git
*.log
.DS_Store
Dockerfile
.dockerignore
+13 -5
View File
@@ -2,13 +2,19 @@
# ---- deps: package.json이 바뀔 때만 다시 설치 ----
FROM node:24-alpine AS deps
# 빌드 대상은 저장소 루트(npm workspaces). 웹에 필요한 frontend·shared 만 설치한다
WORKDIR /app
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: 코드 수정이 바로 반영되는 개발 서버 ----
FROM deps AS dev
COPY . .
COPY shared shared
COPY frontend frontend
WORKDIR /app/frontend
EXPOSE 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
ARG VITE_SITE_URL=""
ENV VITE_SITE_URL=$VITE_SITE_URL
COPY . .
COPY shared shared
COPY frontend frontend
WORKDIR /app/frontend
RUN npm run build
# ---- prod: nginx로 정적 파일 제공 ----
FROM nginx:1.29-alpine AS prod
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/frontend/dist /usr/share/nginx/html
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
+1 -1
View File
@@ -32,7 +32,7 @@ server {
}
# 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
location ~ ^/today/[a-z]+/[a-z]+(/[a-z]+)?$ {
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;
+1 -1
View File
@@ -2,7 +2,7 @@ import { defineConfig } from '@hey-api/openapi-ts'
export default defineConfig({
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
output: 'src/api/client',
output: '../shared/api/client',
parser: {
patch: {
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
-2691
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -11,6 +11,7 @@
"api": "openapi-ts"
},
"dependencies": {
"@nalssigak/shared": "*",
"@tailwindcss/vite": "^4.3.3",
"@tanstack/react-query": "^5.104.0",
"embla-carousel-react": "^8.6.0",
-546
View File
@@ -1420,62 +1420,6 @@
}
]
},
{
"path": "gyeonggi/suwon/jangan",
"name": "경기 수원시 장안구",
"main": "4111100000",
"regions": [
{
"code": "4111100000",
"name": "경기 수원시 장안구",
"short_name": "수원시 장안구",
"lat": 37.30101,
"lon": 127.01222
}
]
},
{
"path": "gyeonggi/suwon/gwonseon",
"name": "경기 수원시 권선구",
"main": "4111300000",
"regions": [
{
"code": "4111300000",
"name": "경기 수원시 권선구",
"short_name": "수원시 권선구",
"lat": 37.25473,
"lon": 126.97407
}
]
},
{
"path": "gyeonggi/suwon/paldal",
"name": "경기 수원시 팔달구",
"main": "4111500000",
"regions": [
{
"code": "4111500000",
"name": "경기 수원시 팔달구",
"short_name": "수원시 팔달구",
"lat": 37.2831,
"lon": 127.03783
}
]
},
{
"path": "gyeonggi/suwon/yeongtong",
"name": "경기 수원시 영통구",
"main": "4111700000",
"regions": [
{
"code": "4111700000",
"name": "경기 수원시 영통구",
"short_name": "수원시 영통구",
"lat": 37.25631,
"lon": 127.04863
}
]
},
{
"path": "gyeonggi/seongnam",
"name": "경기 성남시",
@@ -1504,48 +1448,6 @@
}
]
},
{
"path": "gyeonggi/seongnam/sujeong",
"name": "경기 성남시 수정구",
"main": "4113100000",
"regions": [
{
"code": "4113100000",
"name": "경기 성남시 수정구",
"short_name": "성남시 수정구",
"lat": 37.44749,
"lon": 127.14772
}
]
},
{
"path": "gyeonggi/seongnam/jungwon",
"name": "경기 성남시 중원구",
"main": "4113300000",
"regions": [
{
"code": "4113300000",
"name": "경기 성남시 중원구",
"short_name": "성남시 중원구",
"lat": 37.42767,
"lon": 127.13942
}
]
},
{
"path": "gyeonggi/seongnam/bundang",
"name": "경기 성남시 분당구",
"main": "4113500000",
"regions": [
{
"code": "4113500000",
"name": "경기 성남시 분당구",
"short_name": "성남시 분당구",
"lat": 37.37997,
"lon": 127.12102
}
]
},
{
"path": "gyeonggi/uijeongbu",
"name": "경기 의정부시",
@@ -1581,34 +1483,6 @@
}
]
},
{
"path": "gyeonggi/anyang/manan",
"name": "경기 안양시 만안구",
"main": "4117100000",
"regions": [
{
"code": "4117100000",
"name": "경기 안양시 만안구",
"short_name": "안양시 만안구",
"lat": 37.38378,
"lon": 126.9345
}
]
},
{
"path": "gyeonggi/anyang/dongan",
"name": "경기 안양시 동안구",
"main": "4117300000",
"regions": [
{
"code": "4117300000",
"name": "경기 안양시 동안구",
"short_name": "안양시 동안구",
"lat": 37.3897,
"lon": 126.95336
}
]
},
{
"path": "gyeonggi/bucheon",
"name": "경기 부천시",
@@ -1637,48 +1511,6 @@
}
]
},
{
"path": "gyeonggi/bucheon/wonmi",
"name": "경기 부천시 원미구",
"main": "4119200000",
"regions": [
{
"code": "4119200000",
"name": "경기 부천시 원미구",
"short_name": "부천시 원미구",
"lat": 37.49659,
"lon": 126.787
}
]
},
{
"path": "gyeonggi/bucheon/sosa",
"name": "경기 부천시 소사구",
"main": "4119400000",
"regions": [
{
"code": "4119400000",
"name": "경기 부천시 소사구",
"short_name": "부천시 소사구",
"lat": 37.48004,
"lon": 126.79994
}
]
},
{
"path": "gyeonggi/bucheon/ojeong",
"name": "경기 부천시 오정구",
"main": "4119600000",
"regions": [
{
"code": "4119600000",
"name": "경기 부천시 오정구",
"short_name": "부천시 오정구",
"lat": 37.52835,
"lon": 126.79581
}
]
},
{
"path": "gyeonggi/gwangmyeong",
"name": "경기 광명시",
@@ -1742,34 +1574,6 @@
}
]
},
{
"path": "gyeonggi/ansan/sangnok",
"name": "경기 안산시 상록구",
"main": "4127100000",
"regions": [
{
"code": "4127100000",
"name": "경기 안산시 상록구",
"short_name": "안산시 상록구",
"lat": 37.29852,
"lon": 126.84682
}
]
},
{
"path": "gyeonggi/ansan/danwon",
"name": "경기 안산시 단원구",
"main": "4127300000",
"regions": [
{
"code": "4127300000",
"name": "경기 안산시 단원구",
"short_name": "안산시 단원구",
"lat": 37.31673,
"lon": 126.81442
}
]
},
{
"path": "gyeonggi/goyang",
"name": "경기 고양시",
@@ -1798,48 +1602,6 @@
}
]
},
{
"path": "gyeonggi/goyang/deogyang",
"name": "경기 고양시 덕양구",
"main": "4128100000",
"regions": [
{
"code": "4128100000",
"name": "경기 고양시 덕양구",
"short_name": "고양시 덕양구",
"lat": 37.63458,
"lon": 126.8342
}
]
},
{
"path": "gyeonggi/goyang/ilsandong",
"name": "경기 고양시 일산동구",
"main": "4128500000",
"regions": [
{
"code": "4128500000",
"name": "경기 고양시 일산동구",
"short_name": "고양시 일산동구",
"lat": 37.65591,
"lon": 126.77706
}
]
},
{
"path": "gyeonggi/goyang/ilsanseo",
"name": "경기 고양시 일산서구",
"main": "4128700000",
"regions": [
{
"code": "4128700000",
"name": "경기 고양시 일산서구",
"short_name": "고양시 일산서구",
"lat": 37.67249,
"lon": 126.75278
}
]
},
{
"path": "gyeonggi/gwacheon",
"name": "경기 과천시",
@@ -1980,48 +1742,6 @@
}
]
},
{
"path": "gyeonggi/yongin/cheoin",
"name": "경기 용인시 처인구",
"main": "4146100000",
"regions": [
{
"code": "4146100000",
"name": "경기 용인시 처인구",
"short_name": "용인시 처인구",
"lat": 37.23148,
"lon": 127.20384
}
]
},
{
"path": "gyeonggi/yongin/giheung",
"name": "경기 용인시 기흥구",
"main": "4146300000",
"regions": [
{
"code": "4146300000",
"name": "경기 용인시 기흥구",
"short_name": "용인시 기흥구",
"lat": 37.2776,
"lon": 127.11679
}
]
},
{
"path": "gyeonggi/yongin/suji",
"name": "경기 용인시 수지구",
"main": "4146500000",
"regions": [
{
"code": "4146500000",
"name": "경기 용인시 수지구",
"short_name": "용인시 수지구",
"lat": 37.31939,
"lon": 127.1001
}
]
},
{
"path": "gyeonggi/paju",
"name": "경기 파주시",
@@ -2113,62 +1833,6 @@
}
]
},
{
"path": "gyeonggi/hwaseong/manse",
"name": "경기 화성시 만세구",
"main": "4159100000",
"regions": [
{
"code": "4159100000",
"name": "경기 화성시 만세구",
"short_name": "화성시 만세구",
"lat": 37.1377,
"lon": 126.92566
}
]
},
{
"path": "gyeonggi/hwaseong/hyohaeng",
"name": "경기 화성시 효행구",
"main": "4159300000",
"regions": [
{
"code": "4159300000",
"name": "경기 화성시 효행구",
"short_name": "화성시 효행구",
"lat": 37.20918,
"lon": 126.95915
}
]
},
{
"path": "gyeonggi/hwaseong/byeongjeom",
"name": "경기 화성시 병점구",
"main": "4159500000",
"regions": [
{
"code": "4159500000",
"name": "경기 화성시 병점구",
"short_name": "화성시 병점구",
"lat": 37.20875,
"lon": 127.0359
}
]
},
{
"path": "gyeonggi/hwaseong/dongtan",
"name": "경기 화성시 동탄구",
"main": "4159700000",
"regions": [
{
"code": "4159700000",
"name": "경기 화성시 동탄구",
"short_name": "화성시 동탄구",
"lat": 37.19724,
"lon": 127.09687
}
]
},
{
"path": "gyeonggi/gwangju",
"name": "경기 광주시",
@@ -2302,62 +1966,6 @@
}
]
},
{
"path": "chungbuk/cheongju/sangdang",
"name": "충북 청주시 상당구",
"main": "4311100000",
"regions": [
{
"code": "4311100000",
"name": "충북 청주시 상당구",
"short_name": "청주시 상당구",
"lat": 36.584,
"lon": 127.51173
}
]
},
{
"path": "chungbuk/cheongju/seowon",
"name": "충북 청주시 서원구",
"main": "4311200000",
"regions": [
{
"code": "4311200000",
"name": "충북 청주시 서원구",
"short_name": "청주시 서원구",
"lat": 36.63726,
"lon": 127.48329
}
]
},
{
"path": "chungbuk/cheongju/heungdeok",
"name": "충북 청주시 흥덕구",
"main": "4311300000",
"regions": [
{
"code": "4311300000",
"name": "충북 청주시 흥덕구",
"short_name": "청주시 흥덕구",
"lat": 36.6182,
"lon": 127.35942
}
]
},
{
"path": "chungbuk/cheongju/cheongwon",
"name": "충북 청주시 청원구",
"main": "4311400000",
"regions": [
{
"code": "4311400000",
"name": "충북 청주시 청원구",
"short_name": "청주시 청원구",
"lat": 36.64431,
"lon": 127.48766
}
]
},
{
"path": "chungbuk/chungju",
"name": "충북 충주시",
@@ -2519,34 +2127,6 @@
}
]
},
{
"path": "chungnam/cheonan/dongnam",
"name": "충남 천안시 동남구",
"main": "4413100000",
"regions": [
{
"code": "4413100000",
"name": "충남 천안시 동남구",
"short_name": "천안시 동남구",
"lat": 36.80412,
"lon": 127.15247
}
]
},
{
"path": "chungnam/cheonan/seobuk",
"name": "충남 천안시 서북구",
"main": "4413300000",
"regions": [
{
"code": "4413300000",
"name": "충남 천안시 서북구",
"short_name": "천안시 서북구",
"lat": 36.87556,
"lon": 127.1572
}
]
},
{
"path": "chungnam/gongju",
"name": "충남 공주시",
@@ -2764,34 +2344,6 @@
}
]
},
{
"path": "gyeongbuk/pohang/nam",
"name": "경북 포항시 남구",
"main": "4711100000",
"regions": [
{
"code": "4711100000",
"name": "경북 포항시 남구",
"short_name": "포항시 남구",
"lat": 36.00569,
"lon": 129.36167
}
]
},
{
"path": "gyeongbuk/pohang/buk",
"name": "경북 포항시 북구",
"main": "4711300000",
"regions": [
{
"code": "4711300000",
"name": "경북 포항시 북구",
"short_name": "포항시 북구",
"lat": 36.03885,
"lon": 129.36791
}
]
},
{
"path": "gyeongbuk/gyeongju",
"name": "경북 경주시",
@@ -3128,76 +2680,6 @@
}
]
},
{
"path": "gyeongnam/changwon/uichang",
"name": "경남 창원시 의창구",
"main": "4812100000",
"regions": [
{
"code": "4812100000",
"name": "경남 창원시 의창구",
"short_name": "창원시 의창구",
"lat": 35.254,
"lon": 128.64015
}
]
},
{
"path": "gyeongnam/changwon/seongsan",
"name": "경남 창원시 성산구",
"main": "4812300000",
"regions": [
{
"code": "4812300000",
"name": "경남 창원시 성산구",
"short_name": "창원시 성산구",
"lat": 35.19838,
"lon": 128.70294
}
]
},
{
"path": "gyeongnam/changwon/masanhappo",
"name": "경남 창원시 마산합포구",
"main": "4812500000",
"regions": [
{
"code": "4812500000",
"name": "경남 창원시 마산합포구",
"short_name": "창원시 마산합포구",
"lat": 35.19687,
"lon": 128.56786
}
]
},
{
"path": "gyeongnam/changwon/masanhoewon",
"name": "경남 창원시 마산회원구",
"main": "4812700000",
"regions": [
{
"code": "4812700000",
"name": "경남 창원시 마산회원구",
"short_name": "창원시 마산회원구",
"lat": 35.22093,
"lon": 128.57971
}
]
},
{
"path": "gyeongnam/changwon/jinhae",
"name": "경남 창원시 진해구",
"main": "4812900000",
"regions": [
{
"code": "4812900000",
"name": "경남 창원시 진해구",
"short_name": "창원시 진해구",
"lat": 35.13306,
"lon": 128.71008
}
]
},
{
"path": "gyeongnam/jinju",
"name": "경남 진주시",
@@ -3737,34 +3219,6 @@
}
]
},
{
"path": "jeonbuk/jeonju/wansan",
"name": "전북 전주시 완산구",
"main": "5211100000",
"regions": [
{
"code": "5211100000",
"name": "전북 전주시 완산구",
"short_name": "전주시 완산구",
"lat": 35.80919,
"lon": 127.12192
}
]
},
{
"path": "jeonbuk/jeonju/deokjin",
"name": "전북 전주시 덕진구",
"main": "5211300000",
"regions": [
{
"code": "5211300000",
"name": "전북 전주시 덕진구",
"short_name": "전주시 덕진구",
"lat": 35.82639,
"lon": 127.13642
}
]
},
{
"path": "jeonbuk/gunsan",
"name": "전북 군산시",
+9 -67
View File
@@ -1,72 +1,14 @@
import { client } from './client/client.gen'
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth'
import { configureApi } from '@nalssigak/shared/api/setup'
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(/\/+$/, '')
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(`${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
// 사파리 프라이빗 모드 등에서는 localStorage 를 읽는 것만으로 에러가 나서 쓸 때마다 꺼낸다
configureApi({
baseUrl: API_BASE_URL,
storage: {
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
},
})
+2 -2
View File
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation } from 'react-router'
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 { kindOfHour, kst, seasonOf, type TimeKind } from './lib'
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
import './b.css'
import { AuthProvider } from './auth'
import { RegionProvider } from './region'
+3 -3
View File
@@ -1,9 +1,9 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen'
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 { useSheet } from './sheetContext'
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
+6 -5
View File
@@ -1,12 +1,13 @@
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
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 { cardBg, clockShort, fall } from './lib'
import type { SlideBg } from './types'
import { deg } from './weatherText'
import { cardBg, clockShort } from '@nalssigak/shared/lib'
import { fall } from './lib'
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 { 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 { useSheet } from './sheetContext'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
+4 -3
View File
@@ -1,9 +1,10 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions, listArticlesOptions } from '../api/client/@tanstack/react-query.gen'
import { ArticleCategory } from '../api/client/types.gen'
import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen'
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 { Chips, Ic, Skel, StateBox, Thumb } from './ui'
+10 -33
View File
@@ -1,7 +1,6 @@
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 regionPages from '../../seo/region.json'
import { setTokens, subscribeAuth } from '../api/auth'
import { setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
import { SITE_URL } from '../api/setup'
import {
addCommentMutation,
@@ -19,13 +18,14 @@ import {
signupMutation,
unlikeCommentMutation,
updateMeMutation,
} from '../api/client/@tanstack/react-query.gen'
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
import { ownPage, useRegion } from './regionContext'
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 { useSky } from './skyContext'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
@@ -134,7 +134,6 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{state.type === 'region' && <RegionSheet onDone={onClose} />}
</div>
)}
{!state && <RegionLinks />}
</dialog>
)
}
@@ -989,27 +988,6 @@ function MeSheet({ onDone }: { onDone: () => void }) {
/* ---------- 지역 ---------- */
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const
/** 구 코드 → 그 구의 지역 페이지 주소 */
const pageHref = (code: string) => {
const p = ownPage(code)
return p ? `/today/${p.path}` : '/'
}
/** 지역 바꾸기가 닫혀 있을 때도 지역 페이지 링크를 HTML에 둔다 (검색 로봇이 링크를 따라가게) */
function RegionLinks() {
return (
<nav aria-label="지역별 오늘 날씨">
<ul>
{regionPages.map((p) => (
<li key={p.path}>
<a href={`/today/${p.path}`}>{p.name} 오늘 날씨</a>
</li>
))}
</ul>
</nav>
)
}
function RegionSheet({ onDone }: { onDone: () => void }) {
const { region, setRegion, locate, locateStatus } = useRegion()
const { me, logout } = useAuth()
@@ -1041,11 +1019,10 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
<ul className={cx('mt-2 flex flex-col transition-opacity', list.isPlaceholderData && 'opacity-60')}>
{regions.map((r) => (
<li key={r.code}>
<a
href={pageHref(r.code)}
<button
type="button"
aria-current={r.code === region.code ? 'true' : undefined}
onClick={(e) => {
e.preventDefault()
onClick={() => {
setRegion(r)
track('region_change', { region_name: r.name, method: 'list' })
onDone()
@@ -1054,7 +1031,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
>
{r.name}
{r.code === region.code && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
</a>
</button>
</li>
))}
</ul>
+3 -3
View File
@@ -1,9 +1,9 @@
import { useQuery } from '@tanstack/react-query'
import { useState, type ReactNode } from 'react'
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
import type { BestTime, SkyPlanData } from '../api/client/types.gen'
import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { BestTime, SkyPlanData } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { clockShort, loadOf } from './lib'
import { clockShort, loadOf } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext'
import { MapLink, Sec, Skel, StateBox } from './ui'
+6 -51
View File
@@ -1,28 +1,21 @@
import { Fragment, useEffect, useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getFeedOptions, getWeatherTodayOptions } from '../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 { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { BandArticle, BandEvent, Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen'
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 { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
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
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
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 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'
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 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 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 = [
{ 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[] }) {
const { open } = useSheet()
return (
+2 -2
View File
@@ -1,8 +1,8 @@
import { useRef, useState, type ReactNode } from 'react'
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 { cardBg, dateRange, loadOf, shortDay } from './lib'
import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
+3 -3
View File
@@ -1,8 +1,8 @@
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
import { clearTokens, getAccessToken, subscribeAuth } from '../api/auth'
import { meOptions } from '../api/client/@tanstack/react-query.gen'
import { logout as logoutOnServer } from '../api/client/sdk.gen'
import { clearTokens, getAccessToken, subscribeAuth } from '@nalssigak/shared/api/auth'
import { meOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { logout as logoutOnServer } from '@nalssigak/shared/api/client/sdk.gen'
import { AuthContext } from './authContext'
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
+1 -1
View File
@@ -1,5 +1,5 @@
import { createContext, use } from 'react'
import type { Me } from '../api/client/types.gen'
import type { Me } from '@nalssigak/shared/api/client/types.gen'
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void }
+2 -131
View File
@@ -1,4 +1,5 @@
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 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`
}
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 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_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'
}
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)'] }
+8 -8
View File
@@ -1,19 +1,19 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useLocation, useNavigate } from 'react-router'
import { matchPath, useLocation, useNavigate } from 'react-router'
import regionPages from '../../seo/region.json'
import { nearestRegion } from '../api/client/sdk.gen'
import type { RegionData } from '../api/client/types.gen'
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 { DEFAULT_REGION, ownPage, RegionContext, type LocateStatus } from './regionContext'
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
const KEY = 'nalssigak.b.region'
type RegionPage = (typeof regionPages)[number]
/** /today/gyeonggi/seongnam, /today/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
/** /today/gyeonggi/seongnam 같은 지역 페이지 주소면 그 페이지 */
function pageOf(pathname: string): RegionPage | undefined {
const path = pathname.match(/^\/today\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
return path ? regionPages.find((p) => p.path === path) : undefined
const m = matchPath('/today/:sido/:place', pathname)
return m ? regionPages.find((p) => p.path === `${m.params.sido}/${m.params.place}`) : undefined
}
/** 지역 페이지 안의 구: 구로 나뉜 시는 r 이 그 시 안이면 r, 아니면 시청이 있는 구 */
@@ -60,7 +60,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
const setRegion = useCallback((r: RegionData) => {
setRegionState(r)
writeStored(r)
const next = ownPage(r.code)
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])
+2 -6
View File
@@ -1,15 +1,11 @@
import { createContext, use } from 'react'
import regionPages from '../../seo/region.json'
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 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 const ownPage = (code: string) => regionPages.find((p) => p.regions.length === 1 && p.regions[0].code === code)
export { DEFAULT_REGION } from '@nalssigak/shared/lib'
export const RegionContext = createContext<RegionApi | null>(null)
+1 -1
View File
@@ -1,5 +1,5 @@
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 }
+2 -1
View File
@@ -2,7 +2,8 @@ import { useState, type CSSProperties, type ReactNode } from 'react'
import { Link } from 'react-router'
import { cx } from '../lib/utils'
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 }
+6 -18
View File
@@ -12,7 +12,7 @@ const gakList = `<ul>${gaks.map((g) => `<li><b>${g.name}</b>: ${g.description}</
const regionPages: RegionPage[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/region.json'), 'utf8'))
/** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */
const PAGES: { path: string; title: string; description: string; body: string; code?: string; keywords?: string }[] = [
const PAGES: { path: string; title: string; description: string; body: string; code?: string }[] = [
{
path: 'gak',
title: '오늘의 각 · 세차각·빨래각·러닝각 점수 | 날씨각',
@@ -41,29 +41,18 @@ const PAGES: { path: string; title: string; description: string; body: string; c
/** 제목 앞자리: 검색어처럼 시군구 이름부터 (경기 성남시 → 성남시) */
const headName = (name: string) => name.split(' ').at(-1)!
/** 검색어로 많이 치는 꼴: 성남시 → 성남. 중구처럼 두 글자는 그대로 */
const bareName = (name: string) => (name.length > 2 ? name.slice(0, -1) : name)
/** 지역마다 한 장: /today/gyeonggi/seongnam, 구로 나뉜 시의 구는 /today/gyeonggi/seongnam/bundang. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */
/** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */
for (const r of regionPages) {
const sido = r.path.split('/')[0]
const city = r.path.split('/').slice(0, 2).join('/')
const isGu = r.path !== city
const gus = regionPages.filter((o) => o.path.startsWith(`${r.path}/`))
// 시도의 다른 시군구 + 같은 시의 다른 구
const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`) && (o.path.split('/').length === 2 || (isGu && o.path.startsWith(`${city}/`))))
const parts = gus.length ? `<p>${r.name}는 ${gus.map((g) => `<a href="/today/${g.path}">${headName(g.name)}</a>`).join(', ')}별로 따로 계산해요.</p>` : ''
const head = headName(r.name)
const bare = bareName(head)
const guNames = r.regions.length > 1 ? r.regions.map((g) => g.name.split(' ').at(-1)!) : []
const keywords = [...new Set([`${bare} 날씨`, `${head} 날씨`, `${bare} 오늘 날씨`, `${r.name} 날씨`, ...guNames.flatMap((g) => [`${g} 날씨`, `${bareName(g)} 날씨`]), '날씨각'])].join(', ')
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,
keywords,
title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[isGu ? 1 : 0]}` : ''} | 날씨각`,
title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[0]}` : ''} | 날씨각`,
description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`,
body: `<h1>${r.name} 오늘 날씨, 뭐 할까?</h1><p>${bare} 날씨, 오늘 ${head}에서는 뭐 하기 좋을까요? ${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>` : ''}`,
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>` : ''}`,
})
}
@@ -86,7 +75,6 @@ function seoPages(): Plugin {
.replace(/<title>[^<]*<\/title>/, `<title>${p.title}</title>`)
.replace(/(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"/g, `$1${attr(p.description)}"`)
.replace(/(<meta (?:property|name)="(?:og:title|twitter:title)" content=")[^"]*"/g, `$1${attr(p.title)}"`)
.replace(/(<meta name="keywords" content=")[^"]*"/, (m, head) => (p.keywords ? `${head}${attr(p.keywords)}"` : m))
.replace(/(<meta property="og:url" content=")[^"]*"/, `$1${url}"`)
.replace(/(<link rel="canonical" href=")[^"]*"/, `$1${url}"`)
.replace(/<main>[\s\S]*<\/main>/, `<main>${p.body}<p><a href="/">날씨각 처음으로</a></p></main>`)
+14735
View File
File diff suppressed because it is too large. Load diff
+5
View File
@@ -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 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 {
try {
return localStorage.getItem(key)
return storage?.getItem(key) ?? null
} catch {
// 사파리 프라이빗 모드 등에서 저장소 접근이 막히면 로그인 안 한 상태로 시작한다
return null
@@ -13,15 +21,21 @@ function readStored(key: string): string | null {
function writeStored(key: string, value: string | null) {
try {
if (value) localStorage.setItem(key, value)
else localStorage.removeItem(key)
if (value) storage?.setItem(key, value)
else storage?.removeItem(key)
} catch {
// 저장이 막혀도 이번 방문 동안은 메모리 토큰으로 계속 쓴다
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>()
/** 토큰이 바뀌거나(로그인·로그아웃) 로그인이 필요할 때 알림을 받는다 */
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+75
View File
@@ -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
})
}
+136
View File
@@ -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'
}
+50
View File
@@ -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 { kst } from './lib'
import { kst } from '.'
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]: '흐림' }
+12
View File
@@ -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"
}
}
+17
View File
@@ -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"]
}